<?php
require_once __DIR__ . '/../config/database.php';

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

$token = get_auth_token();

if (!$token) {
    http_response_code(401);
    echo json_encode(['error' => 'unauthorized']);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST') {
    $profileRes = supabase_rest('GET', 'profiles?select=id,coins,xp,level,daily_streak,last_daily_reward', [], $token);
    if (empty($profileRes['data'])) {
        http_response_code(400);
        echo json_encode(['error' => 'profile not found']);
        exit;
    }

    $profile = $profileRes['data'][0];
    $lastClaim = $profile['last_daily_reward'] ?? null;
    $today = date('Y-m-d');

    if ($lastClaim === $today) {
        echo json_encode(['error' => 'already_claimed', 'message' => 'لقد جمعت المكافأة اليوم']);
        exit;
    }

    $yesterday = date('Y-m-d', strtotime('-1 day'));
    $streak = ($lastClaim === $yesterday) ? ($profile['daily_streak'] ?? 0) + 1 : 1;

    // Load reward config from system_config
    $cfgRes = supabase_rest('GET', 'system_config?select=key,value&key=in.(daily_reward_base,daily_reward_streak_bonus)', [], SUPABASE_SERVICE_KEY);
    $rewardBase = 50;
    $rewardBonus = 10;
    if (!empty($cfgRes['data'])) {
        foreach ($cfgRes['data'] as $cfg) {
            if ($cfg['key'] === 'daily_reward_base') $rewardBase = (int)$cfg['value'];
            if ($cfg['key'] === 'daily_reward_streak_bonus') $rewardBonus = (int)$cfg['value'];
        }
    }
    $reward = $rewardBase + ($streak - 1) * $rewardBonus;
    $newCoins = ($profile['coins'] ?? 0) + $reward;

    // XP award for daily claim
    $dailyXp = 25;
    $newXp = (int)($profile['xp'] ?? 0) + $dailyXp;
    $currentLevel = (int)($profile['level'] ?? 1);

    $profileUpdate = [
        'coins' => $newCoins,
        'xp' => $newXp,
        'daily_streak' => $streak,
        'last_daily_reward' => $today,
    ];

    // Check for level up
    $levelRes = supabase_rest('GET', "xp_levels?level=eq." . ($currentLevel + 1) . "&select=level,xp_required,reward_coins", [], SUPABASE_SERVICE_KEY);
    $levelUpCoinsBonus = 0;
    if (!empty($levelRes['data']) && $newXp >= (int)$levelRes['data'][0]['xp_required']) {
        $newLevel = (int)$levelRes['data'][0]['level'];
        $levelUpCoinsBonus = (int)($levelRes['data'][0]['reward_coins'] ?? 0);
        $profileUpdate['level'] = $newLevel;
        $newCoins += $levelUpCoinsBonus;
        $profileUpdate['coins'] = $newCoins;
    }

    supabase_rest('PATCH', "profiles?id=eq.{$profile['id']}", $profileUpdate, SUPABASE_SERVICE_KEY);

    // Log economy_transaction for daily reward coins
    supabase_rest('POST', 'economy_transactions', [
        'player_id' => $profile['id'],
        'type' => 'daily_reward',
        'currency' => 'coins',
        'amount' => $reward,
        'balance_after' => $newCoins - $levelUpCoinsBonus,
        'reason' => "Daily reward day {$streak}",
        'source_id' => null,
    ], SUPABASE_SERVICE_KEY);

    // Log level up reward separately if applicable
    if ($levelUpCoinsBonus > 0) {
        supabase_rest('POST', 'economy_transactions', [
            'player_id' => $profile['id'],
            'type' => 'level_up_reward',
            'currency' => 'coins',
            'amount' => $levelUpCoinsBonus,
            'balance_after' => $newCoins,
            'reason' => 'Level up reward',
            'source_id' => null,
        ], SUPABASE_SERVICE_KEY);
    }

    echo json_encode([
        'ok' => true,
        'reward' => $reward,
        'streak' => $streak,
        'coins' => $newCoins,
        'xp_awarded' => $dailyXp,
        'new_xp' => $newXp,
    ]);
} else {
    http_response_code(405);
    echo json_encode(['error' => 'method not allowed']);
}
