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

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

$userId = $decoded->sub;
$now = new DateTime();
$nowFormatted = $now->format('Y-m-d H:i:s');

// 📌 5 dakika (300 saniye)
$cooldownSeconds = 300;

// ⏱️ Son açma zamanını al
$stmt = $pdo->prepare("SELECT last_chest_open_time FROM users WHERE id = ?");
$stmt->execute([$userId]);
$lastOpenTime = $stmt->fetchColumn();

if ($lastOpenTime) {
    $last = new DateTime($lastOpenTime);
    $diff = $now->getTimestamp() - $last->getTimestamp();

    if ($diff < $cooldownSeconds) {
        $remaining = $cooldownSeconds - $diff;
        echo json_encode([
            "success" => true,
            "can_open" => false,
            "rewards" => null,
            "winningIndex" => null,
            "message" => "Please wait before opening another chest.",
            "remaining_seconds" => $remaining,
            "last_open_time" => $lastOpenTime
        ]);
        exit;
    }
}

// 🎁 Ödülleri oluştur
$rewardPool = [1, 5, 60];
shuffle($rewardPool);
$rewards = array_slice($rewardPool, 0, 3);
$winningIndex = random_int(0, 2);

// 🔐 Son açma zamanını güncelle
$stmt = $pdo->prepare("UPDATE users SET last_chest_open_time = ? WHERE id = ?");
$stmt->execute([$nowFormatted, $userId]);

// ✅ Cevap
echo json_encode([
    "success" => true,
    "can_open" => true,
    "rewards" => $rewards,
    "winningIndex" => $winningIndex,
    "message" => null,
    "last_open_time" => $nowFormatted
]);