<?php
session_start();
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: login.php');
    exit;
}
require_once __DIR__ . '/../src/Core/Database.php';
require_once __DIR__ . '/../src/Includes/helpers.php';
use HatiApp\Core\Database;

$db = new Database();
$conn = $db->getConnection();
$message = '';
$message_type = '';
$master = null;
$projects = [];
$master_id = $_GET['master_id'] ?? 0;

if ($master_id > 0) {
    try {
        $stmt_master = $conn->prepare("SELECT id, master_name FROM masters WHERE id = ?");
        $stmt_master->execute([$master_id]);
        $master = $stmt_master->fetch(PDO::FETCH_ASSOC);

        $stmt_projects = $conn->prepare("SELECT id, project_name FROM projects ORDER BY project_name ASC");
        $stmt_projects->execute();
        $projects = $stmt_projects->fetchAll(PDO::FETCH_ASSOC);

    } catch (PDOException $e) {
        die("Hata: " . $e->getMessage());
    }
}

if (!$master) {
    die("Usta bulunamadı.");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'submit_evaluation') {
    $project_id = $_POST['project_id'] ?? null;
    $technical_skill_rating = $_POST['technical_skill_rating'] ?? 0;
    $quality_attention_rating = $_POST['quality_attention_rating'] ?? 0;
    $time_management_rating = $_POST['time_management_rating'] ?? 0;
    $problem_solving_rating = $_POST['problem_solving_rating'] ?? 0;
    $communication_rating = $_POST['communication_rating'] ?? 0;
    $work_discipline_rating = $_POST['work_discipline_rating'] ?? 0;
    $customer_satisfaction_rating = $_POST['customer_satisfaction_rating'] ?? 0;
    $innovation_rating = $_POST['innovation_rating'] ?? 0;
    $resource_usage_rating = $_POST['resource_usage_rating'] ?? 0;
    $notes = $_POST['notes'] ?? '';
    $evaluation_date = date('Y-m-d');
    $evaluator_user_id = $_SESSION['user_id'];

    $ratings_array = [$technical_skill_rating, $quality_attention_rating, $time_management_rating, $problem_solving_rating, $communication_rating, $work_discipline_rating, $customer_satisfaction_rating, $innovation_rating, $resource_usage_rating];
    $total_ratings = array_sum($ratings_array);
    $overall_rating = $total_ratings / count($ratings_array);

    try {
        $stmt = $conn->prepare("INSERT INTO master_evaluations (master_id, project_id, evaluator_user_id, evaluation_date, technical_skill_rating, quality_attention_rating, time_management_rating, problem_solving_rating, communication_rating, work_discipline_rating, customer_satisfaction_rating, innovation_rating, resource_usage_rating, overall_rating, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $master_id,
            $project_id,
            $evaluator_user_id,
            $evaluation_date,
            $technical_skill_rating,
            $quality_attention_rating,
            $time_management_rating,
            $problem_solving_rating,
            $communication_rating,
            $work_discipline_rating,
            $customer_satisfaction_rating,
            $innovation_rating,
            $resource_usage_rating,
            $overall_rating,
            $notes
        ]);

        header("Location: view_master_evaluation.php?id=$master_id");
        exit;
    } catch (PDOException $e) {
        $message = 'Hata: Değerlendirme kaydedilirken bir sorun oluştu. ' . $e->getMessage();
        $message_type = 'error';
    }
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Usta Değerlendirme Formu</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
<?php require_once __DIR__ . '/../src/Includes/header.php'; ?>

    <h2>Usta Değerlendirme Formu</h2>
    <p><strong>Değerlendirilen Usta:</strong> <?php echo htmlspecialchars($master['master_name']); ?></p>

    <?php if ($message): ?>
        <p style="color: <?php echo $message_type === 'success' ? 'green' : 'red'; ?>;">
            <?php echo htmlspecialchars($message); ?>
        </p>
    <?php endif; ?>

    <form action="create_master_evaluation.php?master_id=<?php echo $master_id; ?>" method="POST">
        <input type="hidden" name="action" value="submit_evaluation">
        <div class="form-section-title">Genel Bilgiler</div>
        <div class="form-grid">
            <div class="form-group full-width">
                <label for="project_id">İlgili Proje:</label>
                <select id="project_id" name="project_id" required>
                    <option value="">Seçiniz</option>
                    <?php foreach ($projects as $project): ?>
                        <option value="<?php echo $project['id']; ?>"><?php echo htmlspecialchars($project['project_name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>

        <div class="form-section-title">Değerlendirme Kriterleri (1-10 Puan)</div>
        <div class="form-grid">
            <?php 
            $criteria = [
                'technical_skill' => 'Teknik Yeterlilik',
                'quality_attention' => 'İş Kalitesi / Detaylara Özen',
                'time_management' => 'Zaman Yönetimi',
                'problem_solving' => 'Problem Çözme Yeteneği',
                'communication' => 'İletişim ve İşbirliği',
                'work_discipline' => 'İş Disiplini',
                'customer_satisfaction' => 'Müşteri Memnuniyeti',
                'innovation' => 'Yenilik ve Öğrenmeye Açıklık',
                'resource_usage' => 'Kaynak ve Malzeme Kullanımı'
            ];
            foreach ($criteria as $key => $label): ?>
                <div class="form-group">
                    <label for="<?php echo $key; ?>_rating"><?php echo htmlspecialchars($label); ?></label>
                    <select id="<?php echo $key; ?>_rating" name="<?php echo $key; ?>_rating" required>
                        <?php for ($i = 10; $i >= 1; $i--): ?>
                            <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
                        <?php endfor; ?>
                    </select>
                </div>
            <?php endforeach; ?>
        </div>
        
        <div class="form-group full-width">
            <label for="notes">Yorumlar:</label>
            <textarea id="notes" name="notes" rows="5" placeholder="Ek yorumlarınızı buraya yazabilirsiniz."></textarea>
        </div>

        <div class="form-actions">
            <button type="submit">Değerlendirmeyi Kaydet</button>
        </div>
    </form>
</main>
</body>
</html>