<?php
/**
 * Güvenli Batch Ödül API'si
 * Her çağrıda maksimum 100 kişi işler
 * Hata olsa bile devam eder, her ödül kesin verilir
 */

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

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

session_start();
if (!isset($_SESSION['logged_in'])) {
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$matchId = $_POST['match_id'] ?? $_GET['match_id'] ?? null;
$batchSize = 100; // Her seferde işlenecek kişi sayısı

if (!$matchId) {
    echo json_encode(['error' => 'Match ID required']);
    exit;
}

// Maç bilgisi
$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 = (int)$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']})";

// Toplam bekleyen tahmin sayısı
$countSql = "
    SELECT COUNT(*)
    FROM daily_predictions dp
    LEFT JOIN daily_rewards_given drg ON drg.prediction_id = dp.id
    WHERE dp.match_id = ? AND drg.prediction_id IS NULL
";
$countStmt = $pdo->prepare($countSql);
$countStmt->execute([$matchId]);
$totalRemaining = (int)$countStmt->fetchColumn();

if ($totalRemaining === 0) {
    echo json_encode([
        'success' => true,
        'processed' => 0,
        'remaining' => 0,
        'total_remaining' => 0,
        'done' => true,
        'message' => 'Tüm ödüller dağıtıldı!'
    ]);
    exit;
}

// Bu batch için işlenecek tahminler (LIMIT ile)
$sql = "
    SELECT dp.id as prediction_id, dp.user_id, dp.selected_option
    FROM daily_predictions dp
    LEFT JOIN daily_rewards_given drg ON drg.prediction_id = dp.id
    WHERE dp.match_id = ? AND drg.prediction_id IS NULL
    LIMIT ?
";
$stmt = $pdo->prepare($sql);
$stmt->execute([$matchId, $batchSize]);
$predictions = $stmt->fetchAll(PDO::FETCH_ASSOC);

$processed = 0;
$errors = [];

foreach ($predictions as $pred) {
    $userId = $pred['user_id'];
    $selectedOption = (int)$pred['selected_option'];
    $predictionId = $pred['prediction_id'];

    // Her kullanıcı için ayrı transaction - hata olsa bile diğerleri etkilenmez
    try {
        $pdo->beginTransaction();

        // Zaten ödül verilmiş mi kontrol (race condition önleme)
        $check = $pdo->prepare("SELECT COUNT(*) FROM daily_rewards_given WHERE prediction_id = ?");
        $check->execute([$predictionId]);
        if ($check->fetchColumn() > 0) {
            $pdo->rollBack();
            continue;
        }

        // Option text al
        $optStmt = $pdo->prepare("SELECT option_text FROM daily_match_options WHERE id = ?");
        $optStmt->execute([$selectedOption]);
        $optionText = $optStmt->fetchColumn() ?: 'Bilinmeyen';

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

        if ($isCorrect) {
            // Doğru tahmin - kredi ve puan ekle
            $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 {
            // Yanlış tahmin - puan düş
            $pdo->prepare("UPDATE users
                           SET points = COALESCE(points,0) - ?
                           WHERE id = ?")->execute([$losePoints, $userId]);

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

            $pdo->prepare("INSERT INTO daily_rewards_given (match_id, user_id, prediction_id, result) VALUES (?, ?, ?, 'lose')")
                ->execute([$matchId, $userId, $predictionId]);
        }

        $pdo->commit();
        $processed++;

    } catch (Exception $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        $errors[] = "User $userId: " . $e->getMessage();
    }
}

// Kalan sayıyı tekrar hesapla
$countStmt->execute([$matchId]);
$newRemaining = (int)$countStmt->fetchColumn();

echo json_encode([
    'success' => true,
    'processed' => $processed,
    'remaining' => $newRemaining,
    'done' => ($newRemaining === 0),
    'errors' => $errors,
    'message' => $processed > 0 ? "$processed kişiye ödül verildi" : "İşlenecek kayıt yok"
]);
