<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);

header('Content-Type: application/json');

try {
    require_once '../db.php';

    if (!isset($_SESSION['user_id'])) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Non autorisé.']);
        exit;
    }

    $userId = $_SESSION['user_id'];
    $method = $_SERVER['REQUEST_METHOD'];

    // GET : Liste des notes & moyennes
    if ($method === 'GET') {
        $stmtNotes = $pdo->prepare("
            SELECT n.*, s.name as subject_name, s.but_competence 
            FROM notes n 
            JOIN subjects s ON n.subject_id = s.id 
            WHERE s.user_id = :user_id 
            ORDER BY n.id DESC
        ");
        $stmtNotes->execute(['user_id' => $userId]);
        $notes = $stmtNotes->fetchAll();

        $competenceAverages = [
            'Concevoir' => ['total' => 0, 'coef' => 0],
            'Développer' => ['total' => 0, 'coef' => 0],
            'Exprimer' => ['total' => 0, 'coef' => 0],
            'Entreprendre' => ['total' => 0, 'coef' => 0],
            'Comprendre' => ['total' => 0, 'coef' => 0]
        ];

        $globalTotal = 0;
        $globalCoef = 0;

        foreach ($notes as $note) {
            $score = (float)$note['score'];
            $coef = (float)$note['coefficient'];

            $comps = [];
            if (!empty($note['competencies'])) {
                $comps = json_decode($note['competencies'], true);
            }
            if (empty($comps) && isset($note['but_competence'])) {
                $comps = [$note['but_competence']];
            }

            foreach ($comps as $comp) {
                if (isset($competenceAverages[$comp])) {
                    $competenceAverages[$comp]['total'] += ($score * $coef);
                    $competenceAverages[$comp]['coef'] += $coef;
                }
            }

            $globalTotal += ($score * $coef);
            $globalCoef += $coef;
        }

        $averagesFormatted = [];
        foreach ($competenceAverages as $compName => $data) {
            $averagesFormatted[$compName] = $data['coef'] > 0 ? round($data['total'] / $data['coef'], 2) : null;
        }

        $globalAverage = $globalCoef > 0 ? round($globalTotal / $globalCoef, 2) : null;

        echo json_encode([
            'success' => true,
            'notes' => $notes,
            'competence_averages' => $averagesFormatted,
            'global_average' => $globalAverage
        ]);
        exit;
    }

    // POST : Ajouter une note (multi-compétences)
    if ($method === 'POST') {
        $data = json_decode(file_get_contents('php://input'), true);

        $subjectName = trim($data['subject_name'] ?? $data['subject'] ?? '');
        $butCompetence = $data['but_competence'] ?? 'Concevoir';
        
        $competenciesInput = $data['competencies'] ?? [$butCompetence];
        if (!is_array($competenciesInput)) {
            $competenciesInput = [$butCompetence];
        }
        $competenciesJson = json_encode($competenciesInput);

        $title = trim($data['title'] ?? '');
        $score = isset($data['score']) ? (float)$data['score'] : null;
        $coef = isset($data['coefficient']) ? (float)$data['coefficient'] : 1.0;
        $teacherComment = trim($data['teacher_comment'] ?? '');
        $lessonLearned = trim($data['lesson_learned'] ?? '');

        if (empty($subjectName) || empty($title) || $score === null) {
            echo json_encode(['success' => false, 'message' => 'Matière, intitulé et note sont requis.']);
            exit;
        }

        if ($score < 0 || $score > 20) {
            echo json_encode(['success' => false, 'message' => 'La note doit être comprise entre 0 et 20.']);
            exit;
        }

        $stmtSub = $pdo->prepare("SELECT id FROM subjects WHERE user_id = :user_id AND LOWER(name) = LOWER(:name) LIMIT 1");
        $stmtSub->execute(['user_id' => $userId, 'name' => $subjectName]);
        $subject = $stmtSub->fetch();

        if ($subject) {
            $subjectId = $subject['id'];
        } else {
            $stmtInsSub = $pdo->prepare("INSERT INTO subjects (user_id, name, but_competence) VALUES (:user_id, :name, :comp)");
            $stmtInsSub->execute(['user_id' => $userId, 'name' => $subjectName, 'comp' => $butCompetence]);
            $subjectId = $pdo->lastInsertId();
        }

        $stmtNote = $pdo->prepare("
            INSERT INTO notes (subject_id, title, score, coefficient, teacher_comment, lesson_learned, competencies, created_at) 
            VALUES (:subject_id, :title, :score, :coef, :teacher_comment, :lesson_learned, :competencies, CURDATE())
        ");
        $stmtNote->execute([
            'subject_id'      => $subjectId,
            'title'           => $title,
            'score'           => $score,
            'coef'            => $coef,
            'teacher_comment' => $teacherComment,
            'lesson_learned'  => $lessonLearned,
            'competencies'    => $competenciesJson
        ]);

        echo json_encode(['success' => true, 'message' => 'Note enregistrée !']);
        exit;
    }

    // DELETE : Supprimer une note
    if ($method === 'DELETE') {
        $data = json_decode(file_get_contents('php://input'), true);
        $noteId = $data['id'] ?? null;

        if ($noteId) {
            $stmt = $pdo->prepare("
                DELETE n FROM notes n 
                JOIN subjects s ON n.subject_id = s.id 
                WHERE n.id = :id AND s.user_id = :user_id
            ");
            $stmt->execute(['id' => $noteId, 'user_id' => $userId]);
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => 'ID manquant.']);
        }
        exit;
    }

} catch (Throwable $e) {
    echo json_encode(['success' => false, 'message' => 'Erreur BDD : ' . $e->getMessage()]);
}
?>