<?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 === 'GET') {
    $action = $_GET['action'] ?? '';

    if ($action === 'daily') {
        // Get today's 3 daily puzzles (seeded by date)
        $today = date('Y-m-d');
        $seed = crc32($today);

        // Fetch puzzles and use the seed to deterministically select 3
        $offset = abs($seed) % 100;
        $res = supabase_rest('GET', "puzzles?select=id,fen,moves,rating,themes,title&order=id.asc&offset={$offset}&limit=3", [], $token);

        if ($res['status'] >= 200 && $res['status'] < 300) {
            echo json_encode([
                'puzzles' => $res['data'] ?? [],
                'date' => $today
            ]);
        } else {
            echo json_encode(['puzzles' => [], 'date' => $today]);
        }

    } elseif ($action === 'streak') {
        // Get player's current streak
        $profileRes = supabase_rest('GET', 'profiles?select=puzzle_streak,best_puzzle_streak,puzzle_rating', [], $token);
        if (!empty($profileRes['data'])) {
            echo json_encode($profileRes['data'][0]);
        } else {
            echo json_encode(['puzzle_streak' => 0, 'best_puzzle_streak' => 0, 'puzzle_rating' => 1200]);
        }

    } else {
        // List puzzles with optional filters
        $theme = $_GET['theme'] ?? '';
        $rating = intval($_GET['rating'] ?? 1200);
        $limit = min(intval($_GET['limit'] ?? 20), 50);

        $query = 'puzzles?select=id,fen,moves,rating,themes,title';

        if ($theme) {
            $query .= "&themes=cs.{{$theme}}";
        }

        // Get puzzles close to player's rating (within 200 range)
        $ratingMin = $rating - 200;
        $ratingMax = $rating + 200;
        $query .= "&rating=gte.{$ratingMin}&rating=lte.{$ratingMax}";
        $query .= "&order=rating.asc&limit={$limit}";

        $res = supabase_rest('GET', $query, [], $token);

        if ($res['status'] >= 200 && $res['status'] < 300) {
            echo json_encode(['puzzles' => $res['data'] ?? []]);
        } else {
            echo json_encode(['puzzles' => []]);
        }
    }
    exit;
}

// POST requests
$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';

switch ($action) {
    case 'attempt':
        $puzzleId = $input['puzzle_id'] ?? '';
        $solved = $input['solved'] ?? false;
        $timeMs = intval($input['time_ms'] ?? 0);

        if (!$puzzleId) {
            http_response_code(400);
            echo json_encode(['error' => 'missing puzzle_id']);
            exit;
        }

        // Get player's current puzzle_rating
        $profileRes = supabase_rest('GET', 'profiles?select=id,puzzle_rating,puzzle_streak,best_puzzle_streak', [], $token);
        $profile = $profileRes['data'][0] ?? null;

        if (!$profile) {
            http_response_code(404);
            echo json_encode(['error' => 'profile not found']);
            exit;
        }

        $playerRating = $profile['puzzle_rating'] ?? 1200;
        $currentStreak = $profile['puzzle_streak'] ?? 0;
        $bestStreak = $profile['best_puzzle_streak'] ?? 0;

        // Get puzzle rating
        $puzzleRes = supabase_rest('GET', "puzzles?id=eq.{$puzzleId}&select=rating", [], $token);
        $puzzleRating = $puzzleRes['data'][0]['rating'] ?? 1200;

        // ELO calculation (K-factor = 32 for puzzles)
        $K = 32;
        $expected = 1 / (1 + pow(10, ($puzzleRating - $playerRating) / 400));
        $score = $solved ? 1 : 0;
        $newRating = round($playerRating + $K * ($score - $expected));

        // Update streak
        $newStreak = $solved ? $currentStreak + 1 : 0;
        $newBestStreak = max($bestStreak, $newStreak);

        // Record attempt
        $attemptData = [
            'puzzle_id' => $puzzleId,
            'solved' => $solved,
            'time_ms' => $timeMs,
            'rating_before' => $playerRating,
            'rating_after' => $newRating
        ];
        supabase_rest('POST', 'puzzle_attempts', $attemptData, $token);

        // Update profile
        supabase_rest('PATCH', "profiles?id=eq.{$profile['id']}", [
            'puzzle_rating' => $newRating,
            'puzzle_streak' => $newStreak,
            'best_puzzle_streak' => $newBestStreak
        ], $token);

        // Award coins for solving
        $coinsAwarded = 0;
        if ($solved) {
            $coinsAwarded = 10;
            if ($newStreak >= 5) $coinsAwarded = 20;
            if ($newStreak >= 10) $coinsAwarded = 30;
            supabase_rest('POST', 'rpc/add_coins', ['amount' => $coinsAwarded], $token);
        }

        echo json_encode([
            'ok' => true,
            'rating_before' => $playerRating,
            'rating_after' => $newRating,
            'rating_change' => $newRating - $playerRating,
            'streak' => $newStreak,
            'best_streak' => $newBestStreak,
            'coins_awarded' => $coinsAwarded
        ]);
        break;

    case 'streak':
        // Reset/get streak info
        $profileRes = supabase_rest('GET', 'profiles?select=puzzle_streak,best_puzzle_streak,puzzle_rating', [], $token);
        if (!empty($profileRes['data'])) {
            echo json_encode($profileRes['data'][0]);
        } else {
            echo json_encode(['puzzle_streak' => 0, 'best_puzzle_streak' => 0, 'puzzle_rating' => 1200]);
        }
        break;

    default:
        http_response_code(400);
        echo json_encode(['error' => 'invalid action']);
}
