<?php

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

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);
$method = $_SERVER['REQUEST_METHOD'];
$db = supabase($token);

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

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

function getDailyChallenges($db, string $userId): void {
    $today = date('Y-m-d');

    // Get player stats for generating relevant challenges
    $profiles = $db->get('profiles', ['id' => 'eq.' . $userId, 'select' => 'games_played,total_wins,coins,level', 'limit' => 1]);
    $profile = is_array($profiles) && !empty($profiles) ? $profiles[0] : ['level' => 1];
    $level = $profile['level'] ?? 1;

    // Load challenge templates from DB (admin-configurable)
    $sdb = supabaseService();
    $templates = $sdb->get('challenge_templates', ['is_active' => 'eq.true', 'select' => 'id,title,title_ar,type,target,reward_coins,reward_xp,icon']);
    $allChallenges = [];
    if (is_array($templates) && !isset($templates['error'])) {
        foreach ($templates as $t) {
            $allChallenges[] = ['id' => $t['id'], 'title' => $t['title_ar'] ?? $t['title'], 'title_en' => $t['title'], 'target' => intval($t['target']), 'type' => $t['type'], 'reward_coins' => intval($t['reward_coins']), 'reward_xp' => intval($t['reward_xp']), 'icon' => $t['icon'] ?? '🎮'];
        }
    }
    if (empty($allChallenges)) {
        // Fallback if DB is empty
        $allChallenges = [
            ['id' => 'play_3', 'title' => 'العب 3 مباريات', 'title_en' => 'Play 3 games', 'target' => 3, 'type' => 'games_played', 'reward_coins' => 50, 'reward_xp' => 30, 'icon' => '🎮'],
            ['id' => 'win_2', 'title' => 'اربح مباراتين', 'title_en' => 'Win 2 games', 'target' => 2, 'type' => 'wins', 'reward_coins' => 80, 'reward_xp' => 50, 'icon' => '🏆'],
            ['id' => 'beat_bot', 'title' => 'اهزم بوت', 'title_en' => 'Beat a bot', 'target' => 1, 'type' => 'bot_wins', 'reward_coins' => 40, 'reward_xp' => 25, 'icon' => '🤖'],
        ];
    }

    // Pick 3 deterministic per day+user
    $seed = crc32($today . $userId);
    srand($seed);
    $shuffled = $allChallenges;
    shuffle($shuffled);
    $dailyChallenges = array_slice($shuffled, 0, 3);

    // Scale rewards by level
    // Calculate ACTUAL progress by counting today's matches
    $sdb = supabaseService();
    $todayStart = $today . 'T00:00:00+00:00';

    // Get today's matches for this player
    $todayMatchesUrl = SUPABASE_REST . '/matches'
        . '?or=(white_player_id.eq.' . $userId . ',black_player_id.eq.' . $userId . ')'
        . '&status=eq.completed'
        . '&created_at=gte.' . urlencode($todayStart)
        . '&select=id,game_key,result,white_player_id,black_player_id';

    $ch = curl_init($todayMatchesUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'apikey: ' . SUPABASE_SERVICE_KEY,
        'Authorization: Bearer ' . SUPABASE_SERVICE_KEY
    ]);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $matchesJson = curl_exec($ch);
    curl_close($ch);
    $todayMatches = json_decode($matchesJson, true) ?: [];

    // Count stats
    $gamesPlayed = count($todayMatches);
    $wins = 0;
    $chessPlayed = 0;
    $ludoPlayed = 0;
    $dominoPlayed = 0;
    $botWins = 0;

    foreach ($todayMatches as $m) {
        $isWhite = $m['white_player_id'] === $userId;
        $result = $m['result'] ?? '';
        $isWin = ($result === 'white_wins' && $isWhite) || ($result === 'black_wins' && !$isWhite)
            || ($result === 'black_resign' && $isWhite) || ($result === 'white_resign' && !$isWhite);
        if ($isWin) { $wins++; $botWins++; }
        if (($m['game_key'] ?? '') === 'chess') $chessPlayed++;
        if (($m['game_key'] ?? '') === 'ludo') $ludoPlayed++;
        if (($m['game_key'] ?? '') === 'domino') $dominoPlayed++;
    }

    // Map challenge types to actual progress
    $progressMap = [
        'games_played' => $gamesPlayed,
        'wins' => $wins,
        'chess_played' => $chessPlayed,
        'ludo_played' => $ludoPlayed,
        'domino_played' => $dominoPlayed,
        'win_streak' => $wins, // simplified
        'puzzles_solved' => 0, // TODO
        'bot_wins' => $botWins,
        'daily_claimed' => 0,
    ];

    // Check which challenges have been claimed today
    $claimedToday = $sdb->get('economy_transactions', [
        'player_id' => 'eq.' . $userId,
        'type' => 'eq.challenge_reward',
        'created_at' => 'gte.' . urlencode($todayStart),
        'select' => 'reason'
    ]);
    $claimedIds = [];
    if (is_array($claimedToday) && !isset($claimedToday['error'])) {
        foreach ($claimedToday as $ct) {
            if (preg_match('/Daily challenge: (.+)/', $ct['reason'] ?? '', $m)) {
                $claimedIds[] = $m[1];
            }
        }
    }

    foreach ($dailyChallenges as &$c) {
        $c['reward_coins'] = intval($c['reward_coins'] * (1 + $level * 0.1));
        $c['reward_xp'] = intval($c['reward_xp'] * (1 + $level * 0.05));
        $c['progress'] = min($progressMap[$c['type']] ?? 0, $c['target']);
        $c['completed'] = $c['progress'] >= $c['target'];
        $c['claimed'] = in_array($c['id'], $claimedIds);
        $c['date'] = $today;
    }

    // Streak info
    $streak = $profile['daily_streak'] ?? 0;
    $streakBonus = min($streak * 10, 200);

    jsonResponse([
        'challenges' => $dailyChallenges,
        'streak' => $streak,
        'streak_bonus' => $streakBonus,
        'date' => $today
    ]);
}

function claimChallenge($db, string $userId, array $input): void {
    $challengeId = $input['challenge_id'] ?? '';
    $coins = intval($input['coins'] ?? 50);
    $xp = intval($input['xp'] ?? 20);

    if (!$challengeId) jsonError('challenge_id required');

    // Prevent double claim
    $today = date('Y-m-d') . 'T00:00:00+00:00';
    $sdb = supabaseService();
    $existing = $sdb->get('economy_transactions', [
        'player_id' => 'eq.' . $userId,
        'type' => 'eq.challenge_reward',
        'reason' => 'eq.Daily challenge: ' . $challengeId,
        'created_at' => 'gte.' . urlencode($today),
        'limit' => 1
    ]);
    if (is_array($existing) && !isset($existing['error']) && !empty($existing)) {
        jsonError('Already claimed this challenge today');
    }

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

    $newCoins = ($profile['coins'] ?? 0) + $coins;
    $newXp = ($profile['xp'] ?? 0) + $xp;

    $db->update('profiles', ['coins' => $newCoins, 'xp' => $newXp], ['id' => 'eq.' . $userId]);

    // Record transaction
    $sdb->insert('economy_transactions', [
        'player_id' => $userId,
        'type' => 'challenge_reward',
        'currency' => 'coins',
        'amount' => $coins,
        'balance_after' => $newCoins,
        'reason' => 'Daily challenge: ' . $challengeId
    ]);

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