<?php
header('Content-Type: application/json');
session_start();
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'];
$taskId = $_POST['task_id'] ?? null;
$proofType = $_POST['proof_type'] ?? 'none';

if (!$taskId) {
    echo json_encode(['success' => false, 'message' => 'ID de la quête manquant.']);
    exit;
}

$proofData = null;

// GESTION UPLOAD IMAGE
if ($proofType === 'image') {
    if (!isset($_FILES['proof_file']) || $_FILES['proof_file']['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['success' => false, 'message' => 'Veuillez sélectionner une image de preuve.']);
        exit;
    }

    $file = $_FILES['proof_file'];
    $allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
    
    if (!in_array($file['type'], $allowedTypes)) {
        echo json_encode(['success' => false, 'message' => 'Format d\'image non supporté.']);
        exit;
    }

    $uploadDir = '../uploads/proofs/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = 'proof_' . $userId . '_' . $taskId . '_' . time() . '.' . $extension;
    $targetFilePath = $uploadDir . $filename;

    if (move_uploaded_file($file['tmp_name'], $targetFilePath)) {
        $proofData = 'uploads/proofs/' . $filename;
    } else {
        echo json_encode(['success' => false, 'message' => 'Échec de la sauvegarde de l\'image.']);
        exit;
    }
} 
// GESTION LIEN
else if ($proofType === 'link') {
    $link = trim($_POST['proof_link'] ?? '');
    if (empty($link) || !filter_var($link, FILTER_VALIDATE_URL)) {
        echo json_encode(['success' => false, 'message' => 'Lien URL invalide (doit commencer par http:// ou https://).']);
        exit;
    }
    $proofData = $link;
}

try {
    $pdo->beginTransaction();

    // 1. Récupérer l'XP de la quête
    $stmtTask = $pdo->prepare("SELECT xp_reward, is_completed FROM tasks WHERE id = :id AND user_id = :user_id");
    $stmtTask->execute(['id' => $taskId, 'user_id' => $userId]);
    $task = $stmtTask->fetch();

    if (!$task || $task['is_completed']) {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => 'Quête introuvable ou déjà complétée.']);
        exit;
    }

    // 2. Valider la quête
    $stmtUpdate = $pdo->prepare("
        UPDATE tasks 
        SET is_completed = 1, proof_type = :proof_type, proof_data = :proof_data, completed_at = NOW() 
        WHERE id = :id AND user_id = :user_id
    ");
    $stmtUpdate->execute([
        'proof_type' => $proofType,
        'proof_data' => $proofData,
        'id'         => $taskId,
        'user_id'    => $userId
    ]);

    // 3. Calcul de l'XP & Niveaux
    $xpEarned = (int)$task['xp_reward'];
    
    $stmtStats = $pdo->prepare("SELECT level, current_xp FROM user_stats WHERE user_id = :user_id");
    $stmtStats->execute(['user_id' => $userId]);
    $stats = $stmtStats->fetch();

    $newXp = $stats['current_xp'] + $xpEarned;
    $newLevel = (int)$stats['level'];
    $xpNeeded = $newLevel * 1000;

    // Level Up
    while ($newXp >= $xpNeeded) {
        $newXp -= $xpNeeded;
        $newLevel++;
        $xpNeeded = $newLevel * 1000;
    }

    $stmtUpdateStats = $pdo->prepare("UPDATE user_stats SET level = :level, current_xp = :xp WHERE user_id = :user_id");
    $stmtUpdateStats->execute(['level' => $newLevel, 'xp' => $newXp, 'user_id' => $userId]);

    $pdo->commit();

    echo json_encode([
        'success' => true,
        'message' => 'Quête accomplie !',
        'xp_earned' => $xpEarned
    ]);

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