<?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 : Lister les quêtes avec titre du cours lié
    if ($method === 'GET') {
        $stmt = $pdo->prepare("
            SELECT t.*, c.title as course_title 
            FROM tasks t 
            LEFT JOIN courses c ON t.course_id = c.id 
            WHERE t.user_id = :user_id 
            ORDER BY t.created_at DESC
        ");
        $stmt->execute(['user_id' => $userId]);
        echo json_encode($stmt->fetchAll());
        exit;
    }

    // POST : Créer, Modifier ou Valider par lien
    if ($method === 'POST') {
        $data = json_decode(file_get_contents('php://input'), true);

        $id = (!empty($data['id']) && is_numeric($data['id'])) ? intval($data['id']) : null;
        $title = trim($data['title'] ?? '');
        $description = trim($data['description'] ?? '');
        $dueDate = !empty($data['due_date']) ? $data['due_date'] : (!empty($data['completed_at']) ? $data['completed_at'] : null);
        $xpReward = intval($data['xp_reward'] ?? 50);
        $courseId = (!empty($data['course_id']) && is_numeric($data['course_id'])) ? intval($data['course_id']) : null;
        $isCompleted = isset($data['is_completed']) ? intval($data['is_completed']) : null;
        $proofData = $data['proof_data'] ?? null;

        // CAS 1 : VALIDATION DE QUÊTE VIA LIEN (+ GAIN XP DANS USER_STATS)
        if ($id && $isCompleted !== null) {
            $stmt = $pdo->prepare("UPDATE tasks SET is_completed = :completed, proof_data = :proof WHERE id = :id AND user_id = :user_id");
            $stmt->execute(['completed' => $isCompleted, 'proof' => $proofData, 'id' => $id, 'user_id' => $userId]);

            $newXpTotal = 0;
            if ($isCompleted === 1) {
                $stmtXp = $pdo->prepare("SELECT xp_reward FROM tasks WHERE id = :id");
                $stmtXp->execute(['id' => $id]);
                $task = $stmtXp->fetch();
                $xpGained = $task ? intval($task['xp_reward']) : 50;

                $stmtUserStats = $pdo->prepare("
                    INSERT INTO user_stats (user_id, current_xp) VALUES (:user_id, :xp)
                    ON DUPLICATE KEY UPDATE current_xp = COALESCE(current_xp, 0) + :xp
                ");
                $stmtUserStats->execute(['user_id' => $userId, 'xp' => $xpGained]);

                $stmtGet = $pdo->prepare("SELECT current_xp FROM user_stats WHERE user_id = :user_id");
                $stmtGet->execute(['user_id' => $userId]);
                $uData = $stmtGet->fetch();
                $newXpTotal = intval($uData['current_xp'] ?? 0);
            }

            echo json_encode(['success' => true, 'message' => 'Quête validée !', 'new_xp' => $newXpTotal]);
            exit;
        }

        // CAS 2 : MODIFICATION D'UNE QUÊTE EXISTANTE (UPDATE STRICT SUR L'ID AVEC DESCRIPTION)
        if ($id) {
            $stmt = $pdo->prepare("
                UPDATE tasks 
                SET title = :title, description = :description, due_date = :due_date, completed_at = :due_date_cat, xp_reward = :xp, course_id = :course_id 
                WHERE id = :id AND user_id = :user_id
            ");
            $stmt->execute([
                'title'        => $title,
                'description'  => $description,
                'due_date'     => $dueDate,
                'due_date_cat' => $dueDate,
                'xp'           => $xpReward,
                'course_id'    => $courseId,
                'id'           => $id,
                'user_id'      => $userId
            ]);
            echo json_encode(['success' => true, 'message' => 'Quête mise à jour !']);
            exit;
        }

        // CAS 3 : CRÉATION D'UNE QUÊTE (AVEC DESCRIPTION)
        if (empty($title)) {
            echo json_encode(['success' => false, 'message' => 'Titre obligatoire.']);
            exit;
        }

        $stmt = $pdo->prepare("
            INSERT INTO tasks (user_id, course_id, title, description, due_date, completed_at, xp_reward, is_completed, created_at) 
            VALUES (:user_id, :course_id, :title, :description, :due_date, :due_date_cat, :xp, 0, NOW())
        ");
        $stmt->execute([
            'user_id'      => $userId,
            'course_id'    => $courseId,
            'title'        => $title,
            'description'  => $description,
            'due_date'     => $dueDate,
            'due_date_cat' => $dueDate,
            'xp'           => $xpReward
        ]);

        echo json_encode(['success' => true, 'message' => 'Quête créée !']);
        exit;
    }

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

        if ($id) {
            $stmt = $pdo->prepare("DELETE FROM tasks WHERE id = :id AND user_id = :user_id");
            $stmt->execute(['id' => $id, 'user_id' => $userId]);
            echo json_encode(['success' => true, 'message' => 'Quête supprimée !']);
            exit;
        }
        exit;
    }

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