<?php

header('Content-Type: application/json');
require_once __DIR__ . '/../includes/cors.php';

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

require_once __DIR__ . '/../includes/supabase.php';
require_once __DIR__ . '/../includes/auth.php';

$token = requireAuth();
$userId = getUserId($token);
$db = supabase($token);

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    getBattlePass($db, $userId);
}

if ($method === 'POST') {
    $input = getInput();
    if (($input['action'] ?? '') === 'claim_tier') claimTier($db, $userId, $input);
    else jsonError('Invalid action');
}

function getBattlePass($db, string $userId): void {
    // Load active season from DB (admin-configurable)
    $sdb = supabaseService();
    $seasons = $sdb->get('seasons', ['is_active' => 'eq.true', 'select' => '*', 'limit' => 1]);
    if (!empty($seasons) && !isset($seasons['error']) && !empty($seasons[0])) {
        $s = $seasons[0];
        $season = [
            'id' => $s['id'],
            'name' => $s['name_ar'] ?? $s['name'],
            'name_en' => $s['name'],
            'starts_at' => $s['starts_at'],
            'ends_at' => $s['ends_at'],
            'total_tiers' => intval($s['total_tiers'] ?? 30),
            'xp_per_tier' => intval($s['xp_per_tier'] ?? 100)
        ];
    } else {
        // Fallback hardcoded
        $season = [
            'id' => 'season_1',
            'name' => 'الموسم الأول',
            'name_en' => 'Season 1',
            'starts_at' => '2026-06-01',
            'ends_at' => '2026-07-01',
            'total_tiers' => 30,
            'xp_per_tier' => 100
        ];
    }

    // Get player XP
    $profiles = $db->get('profiles', ['id' => 'eq.' . $userId, 'select' => 'xp,level', 'limit' => 1]);
    $profile = is_array($profiles) && !empty($profiles) ? $profiles[0] : ['xp' => 0];
    $totalXp = $profile['xp'] ?? 0;

    // Calculate current tier
    $currentTier = min(intval($totalXp / $season['xp_per_tier']), $season['total_tiers']);
    $tierProgress = ($totalXp % $season['xp_per_tier']) / $season['xp_per_tier'];

    // Generate tier rewards
    $tiers = [];
    for ($i = 1; $i <= $season['total_tiers']; $i++) {
        $reward = generateTierReward($i);
        $tiers[] = [
            'tier' => $i,
            'unlocked' => $i <= $currentTier,
            'reward_free' => $reward['free'],
            'reward_premium' => $reward['premium']
        ];
    }

    // Days remaining
    $endsAt = strtotime($season['ends_at']);
    $daysLeft = max(0, intval(($endsAt - time()) / 86400));

    jsonResponse([
        'season' => $season,
        'current_tier' => $currentTier,
        'tier_progress' => round($tierProgress, 2),
        'total_xp' => $totalXp,
        'days_left' => $daysLeft,
        'tiers' => $tiers
    ]);
}

function generateTierReward(int $tier): array {
    $freeRewards = [
        ['type' => 'coins', 'amount' => 50],
        ['type' => 'coins', 'amount' => 75],
        ['type' => 'xp_boost', 'amount' => 1],
        ['type' => 'coins', 'amount' => 100],
        ['type' => 'coins', 'amount' => 50],
    ];
    $premiumRewards = [
        ['type' => 'gems', 'amount' => 10],
        ['type' => 'coins', 'amount' => 200],
        ['type' => 'frame', 'id' => 'season_frame_' . ceil($tier / 10)],
        ['type' => 'gems', 'amount' => 20],
        ['type' => 'coins', 'amount' => 300],
    ];

    return [
        'free' => $freeRewards[($tier - 1) % count($freeRewards)],
        'premium' => $premiumRewards[($tier - 1) % count($premiumRewards)]
    ];
}

function claimTier($db, string $userId, array $input): void {
    $tier = intval($input['tier'] ?? 0);
    $coins = intval($input['coins'] ?? 0);

    if ($tier < 1) jsonError('Invalid tier');

    $profiles = $db->get('profiles', ['id' => 'eq.' . $userId, 'select' => 'coins', 'limit' => 1]);
    $profile = is_array($profiles) && !empty($profiles) ? $profiles[0] : ['coins' => 0];
    $newCoins = ($profile['coins'] ?? 0) + $coins;
    $db->update('profiles', ['coins' => $newCoins], ['id' => 'eq.' . $userId]);

    jsonResponse(['success' => true, 'coins' => $newCoins]);
}
