<?php
require_once '/home/akgbilis/fi_sf/config.php';
require_once __DIR__ . '/helpers/notification_helper.php';

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$pdo->beginTransaction();

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    http_response_code(405);
    echo json_encode(["error" => "Invalid request"]);
    exit;
}

$matchId = $_POST['match_id'] ?? null;
$userIds = $_POST['user_ids'] ?? [];
$selectedOptions = $_POST['selected_options'] ?? [];
$predictionIds = $_POST['prediction_ids'] ?? [];

if (!$matchId || empty($userIds)) {
    echo json_encode(["error" => "Missing parameters"]);
    exit;
}

// Get match info
$stmt = $pdo->prepare("SELECT * FROM daily_matches WHERE id = ?");
$stmt->execute([$matchId]);
$match = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$match) {
    echo json_encode(["error" => "Match not found"]);
    exit;
}

$correctOptionId = $match['correct_option_id'];
$winPoints = (int)($match['win_points'] ?? 10);
$losePoints = (int)($match['lose_points'] ?? 5);
$matchInfo = "{$match['home_team']} - {$match['away_team']} ({$match['date']} {$match['time']})";

try {
foreach ($userIds as $userId) {
    $selectedOption = $selectedOptions[$userId] ?? null;
    $predictionId   = $predictionIds[$userId] ?? null;

    // Skip if mapping missing
    if ($selectedOption === null || $predictionId === null) {
        continue;
    }

    // Normalize to int for safe comparison
    $selectedOption = (int)$selectedOption;
    $correctOptionId = (int)$correctOptionId;

    // Skip if reward already given
    $check = $pdo->prepare("SELECT COUNT(*) FROM daily_rewards_given WHERE prediction_id = ?");
    $check->execute([$predictionId]);
    if ($check->fetchColumn() > 0) {
        continue;
    }

    // Get option text
    $stmt = $pdo->prepare("SELECT option_text FROM daily_match_options WHERE id = ?");
    $stmt->execute([$selectedOption]);
    $optionText = $stmt->fetchColumn();

    $isCorrect = ($selectedOption === $correctOptionId);

    if ($isCorrect) {
        $pdo->prepare("UPDATE users 
                       SET credits = COALESCE(credits,0) + 2,
                           points  = COALESCE(points,0)  + ?
                       WHERE id = ?")->execute([$winPoints, $userId]);

        addNotification(
            $pdo,
            $userId,
            "🎉 Congratulations!",
            "Your prediction was correct. You won 2 credits and $winPoints points!",
            $matchInfo,
            $optionText,
            "correct"
        );

        $pdo->prepare("INSERT INTO daily_rewards_given (match_id, user_id, prediction_id, result) VALUES (?, ?, ?, 'win')")
            ->execute([$matchId, $userId, $predictionId]);
    } else {
        $pdo->prepare("UPDATE users 
                       SET points = COALESCE(points,0) - ?
                       WHERE id = ?")->execute([$losePoints, $userId]);

        addNotification(
            $pdo,
            $userId,
            "❌ Oops!",
            "Your prediction was wrong.",
            $matchInfo,
            $optionText,
            "wrong"
        );

        $pdo->prepare("INSERT INTO daily_rewards_given (match_id, user_id, prediction_id, result) VALUES (?, ?, ?, 'lose')")
            ->execute([$matchId, $userId, $predictionId]);
    }
}
} catch (Exception $e) {
    $pdo->rollBack();
    http_response_code(500);
    echo json_encode(["error" => "Server error", "details" => $e->getMessage()]);
    exit;
}

$pdo->commit();
echo json_encode(["success" => true]);