<?php

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: 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);
$input = getInput();
$action = $input['action'] ?? 'claim';

$db = supabase($token);

if ($action === 'claim') {
    $profiles = $db->get('profiles', ['id' => 'eq.' . $userId, 'select' => 'coins', 'limit' => 1]);
    $profile = is_array($profiles) && !empty($profiles) && !isset($profiles['error']) ? $profiles[0] : null;

    if (!$profile) jsonError('Profile not found');

    $reward = 100;
    $newCoins = ($profile['coins'] ?? 0) + $reward;

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

    $sdb = supabaseService();
    $sdb->insert('economy_transactions', [
        'player_id' => $userId,
        'type' => 'daily_reward',
        'currency' => 'coins',
        'amount' => $reward,
        'balance_after' => $newCoins,
        'description' => 'Daily reward'
    ]);

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

jsonError('Invalid action');
