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

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

try {
    $user_id = Auth::check();

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

    // Calculate XP for next level (Mock formula: Level * 1000)
    $next_level_xp = $user['level'] * 1000;
    $progress_percent = min(100, round(($user['xp'] / $next_level_xp) * 100));

    echo json_encode([
        'level' => (int)$user['level'],
        'xp' => (int)$user['xp'],
        'next_level_xp' => $next_level_xp,
        'progress_percent' => $progress_percent,
        'diamonds' => (int)$user['diamonds'],
        'can_check_in' => canCheckIn($user['last_check_in'])
    ]);

} catch (Exception $e) {
    http_response_code(401);
    echo json_encode(['error' => $e->getMessage()]);
}

function canCheckIn($last_date) {
    if (!$last_date) return true;
    
    $last = new DateTime($last_date);
    $now = new DateTime();
    $diff = $now->diff($last);
    
    // Check if distinct day (simple login bonus logic)
    // Or exactly 24h: return $diff->h + ($diff->days * 24) >= 24;
    
    // Let's use "Different Day" logic (reset at midnight)
    return $last->format('Y-m-d') !== $now->format('Y-m-d');
}
?>
