<?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);
$sdb = supabaseService();

$DAY_REWARDS = [50, 75, 100, 125, 150, 200, 300];

if ($method === 'GET') {
    $profiles = $db->get('profiles', ['id' => 'eq.' . $userId, 'select' => 'daily_streak,last_daily_reward,coins', 'limit' => 1]);
    $profile = is_array($profiles) && !empty($profiles) && !isset($profiles['error']) ? $profiles[0] : null;
    if (!$profile) {
        ensureProfile($sdb, $userId, $token);
        $profiles = $db->get('profiles', ['id' => 'eq.' . $userId, 'select' => 'daily_streak,last_daily_reward,coins', 'limit' => 1]);
        $profile = is_array($profiles) && !empty($profiles) && !isset($profiles['error']) ? $profiles[0] : null;
        if (!$profile) jsonError('Profile not found');
    }

    $streak = $profile['daily_streak'] ?? 0;
    $lastClaim = $profile['last_daily_reward'] ?? null;
    $today = gmdate('Y-m-d');
    $yesterday = gmdate('Y-m-d', strtotime('-1 day'));

    $alreadyClaimed = $lastClaim && substr($lastClaim, 0, 10) === $today;

    // If last claim was before yesterday, streak resets
    if ($lastClaim && substr($lastClaim, 0, 10) < $yesterday) {
        $streak = 0;
    }

    $dayIndex = $streak % 7;
    $todayReward = $DAY_REWARDS[$dayIndex];

    jsonResponse([
        'streak' => $streak,
        'already_claimed' => $alreadyClaimed,
        'today_reward' => $todayReward,
        'day_index' => $dayIndex,
        'last_claim' => $lastClaim
    ]);
}

if ($method === 'POST') {
    $input = getInput();
    $action = $input['action'] ?? 'claim';

    if ($action !== 'claim') jsonError('Invalid action');

    $profiles = $db->get('profiles', ['id' => 'eq.' . $userId, 'select' => 'daily_streak,last_daily_reward,coins', 'limit' => 1]);
    $profile = is_array($profiles) && !empty($profiles) && !isset($profiles['error']) ? $profiles[0] : null;
    if (!$profile) {
        ensureProfile($sdb, $userId, $token);
        $profiles = $db->get('profiles', ['id' => 'eq.' . $userId, 'select' => 'daily_streak,last_daily_reward,coins', 'limit' => 1]);
        $profile = is_array($profiles) && !empty($profiles) && !isset($profiles['error']) ? $profiles[0] : null;
        if (!$profile) jsonError('Profile not found');
    }

    $streak = $profile['daily_streak'] ?? 0;
    $lastClaim = $profile['last_daily_reward'] ?? null;
    $today = gmdate('Y-m-d');
    $yesterday = gmdate('Y-m-d', strtotime('-1 day'));
    $now = gmdate('c');

    // Check if already claimed today
    if ($lastClaim && substr($lastClaim, 0, 10) === $today) {
        jsonError('Already claimed today');
    }

    // Calculate new streak
    if (!$lastClaim || substr($lastClaim, 0, 10) < $yesterday) {
        // Streak broken (or first time) — reset to day 1
        $streak = 1;
    } else {
        // Last claim was yesterday — streak continues
        $streak = $streak + 1;
    }

    // Day index (0-6) determines reward amount
    $dayIndex = ($streak - 1) % 7;
    $reward = $DAY_REWARDS[$dayIndex];

    $currentCoins = $profile['coins'] ?? 0;
    $newCoins = $currentCoins + $reward;

    // Update profile: coins, streak, last_daily_reward
    $db->update('profiles', [
        'coins' => $newCoins,
        'daily_streak' => $streak,
        'last_daily_reward' => $now
    ], ['id' => 'eq.' . $userId]);

    // Record transaction
    $sdb->insert('economy_transactions', [
        'player_id' => $userId,
        'type' => 'daily_reward',
        'currency' => 'coins',
        'amount' => $reward,
        'balance_after' => $newCoins,
        'reason' => 'Daily reward day ' . $streak
    ]);

    // Check streak achievements
    checkAchievements($sdb, $userId, 'daily_streak', $streak);

    jsonResponse([
        'coins' => $reward,
        'total_coins' => $newCoins,
        'streak' => $streak,
        'day_index' => $dayIndex
    ]);
}

jsonError('Method not allowed', 405);

function ensureProfile($sdb, string $userId, string $token): void {
    $user = verifyToken($token);
    $email = $user['email'] ?? '';
    $name = $user['user_metadata']['display_name'] ?? $user['user_metadata']['full_name'] ?? explode('@', $email)[0] ?? 'Player';
    $sdb->insert('profiles', [
        'id' => $userId,
        'display_name' => $name,
        'coins' => 0,
        'gems' => 0,
        'xp' => 0,
        'level' => 1,
        'daily_streak' => 0,
    ]);
}

function checkAchievements($sdb, string $userId, string $type, int $value): void {
    $achievements = $sdb->get('achievements', ['select' => 'id,condition,coins_reward,xp_reward']);
    if (!is_array($achievements) || isset($achievements['error'])) return;

    foreach ($achievements as $a) {
        $condition = $a['condition'];
        if (is_string($condition)) $condition = json_decode($condition, true);
        if (!$condition || ($condition['type'] ?? '') !== $type) continue;
        if ($value < ($condition['count'] ?? PHP_INT_MAX)) continue;

        // Check if already earned
        $existing = $sdb->get('player_achievements', [
            'player_id' => 'eq.' . $userId,
            'achievement_id' => 'eq.' . $a['id'],
            'limit' => 1
        ]);
        if (is_array($existing) && !isset($existing['error']) && !empty($existing)) {
            if (($existing[0]['completed'] ?? false)) continue;
            // Update progress
            $sdb->update('player_achievements', [
                'progress' => $value,
                'completed' => true,
                'completed_at' => gmdate('c')
            ], ['player_id' => 'eq.' . $userId, 'achievement_id' => 'eq.' . $a['id']]);
        } else {
            $sdb->insert('player_achievements', [
                'player_id' => $userId,
                'achievement_id' => $a['id'],
                'progress' => $value,
                'completed' => true,
                'completed_at' => gmdate('c')
            ]);
        }
    }
}
