<?php
require_once '../../config/db.php';
require_once '../../core/Auth.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

try {
    $user_id = Auth::check();
    
    $pdo->beginTransaction();

    // Lock user row
    $stmt = $pdo->prepare("SELECT xp, level, diamonds, last_check_in FROM users WHERE id = ? FOR UPDATE");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    // Verify Eligibility
    if ($user['last_check_in']) {
        $last = new DateTime($user['last_check_in']);
        $now = new DateTime();
        if ($last->format('Y-m-d') === $now->format('Y-m-d')) {
            throw new Exception("Ya has reclamado tu bono de hoy.");
        }
    }

    // Grant Rewards
    $bonus_diamonds = 10;
    $bonus_xp = 50;

    $new_diamonds = $user['diamonds'] + $bonus_diamonds;
    $new_xp = $user['xp'] + $bonus_xp;
    
    // Level Up Logic?
    // For now simple increment
    
    // Update User
    $sql = "UPDATE users SET 
            diamonds = ?, 
            xp = ?, 
            last_check_in = NOW() 
            WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$new_diamonds, $new_xp, $user_id]);

    // Record Transaction
    $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'gift_received', ?, 'Daily Bonus Check-in')");
    $stmt->execute([$user_id, $bonus_diamonds]);

    $pdo->commit();

    echo json_encode([
        'status' => 'success',
        'message' => '¡Bono diario reclamado!',
        'rewards' => [
            'diamonds' => $bonus_diamonds,
            'xp' => $bonus_xp
        ],
        'new_balance' => $new_diamonds,
        'new_xp' => $new_xp
    ]);

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
