<?php
require_once '../config.php';

$userId = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;

if ($userId <= 0) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "A valid user_id parameter is required."]);
    exit();
}

try {
    $db = getDBConnection();

    // 1. Fetch user profile name & points
    $stmt = $db->prepare("SELECT full_name, points, points_quiz, points_challenges, points_referrals, points_other, `rank`, win_streak, accuracy_rate, fastest_answer, today_points, temp_pass_active, temp_pass_expires_at FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch();
    $name = $user ? explode(" ", $user['full_name'])[0] : "User";
    $points = $user ? intval($user['points']) : 0;
    $points_quiz = $user ? intval($user['points_quiz']) : 0;
    $points_challenges = $user ? intval($user['points_challenges']) : 0;
    $points_referrals = $user ? intval($user['points_referrals']) : 0;
    $points_other = $user ? intval($user['points_other']) : 0;
    $rank = $user ? intval($user['rank']) : 12;
    $win_streak = $user ? intval($user['win_streak']) : 7;
    $accuracy_rate = $user ? intval($user['accuracy_rate']) : 92;
    $fastest_answer = $user ? floatval($user['fastest_answer']) : 5.8;
    $today_points = $user ? intval($user['today_points']) : 18;
    $temp_pass_active = $user ? intval($user['temp_pass_active']) : 0;
    $temp_pass_expires_at = $user ? $user['temp_pass_expires_at'] : null;

    // 2. Fetch Wallet values
    $stmt = $db->prepare("SELECT balance FROM wallets WHERE user_id = ?");
    $stmt->execute([$userId]);
    $wallet = $stmt->fetch();

    $balance = $wallet ? floatval($wallet['balance']) : 0.00;
    $today_winnings = getTodayWinnings($userId);

    // Fetch transaction aggregates from database ledger
    $stmt = $db->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM wallet_transactions WHERE user_id = ? AND action = 'topup'");
    $stmt->execute([$userId]);
    $total_deposited = floatval($stmt->fetchColumn());

    $stmt = $db->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM wallet_transactions WHERE user_id = ? AND action = 'referral'");
    $stmt->execute([$userId]);
    $total_rewarded = floatval($stmt->fetchColumn());

    $stmt = $db->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM wallet_transactions WHERE user_id = ? AND action = 'reward'");
    $stmt->execute([$userId]);
    $total_earned = floatval($stmt->fetchColumn());

    $stmt = $db->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM wallet_transactions WHERE user_id = ? AND action = 'withdraw'");
    $stmt->execute([$userId]);
    $total_withdrawn = floatval($stmt->fetchColumn());

    // Fetch influencer and contestant statuses
    $stmt = $db->prepare("SELECT status FROM influencers WHERE user_id = ?");
    $stmt->execute([$userId]);
    $influencer_status = $stmt->fetchColumn() ?: null;

    $stmt = $db->prepare("SELECT status FROM contestants WHERE user_id = ?");
    $stmt->execute([$userId]);
    $contestant_status = $stmt->fetchColumn() ?: null;

    // 3. Fetch active quizzes
    $stmt = $db->query("SELECT * FROM quizzes WHERE is_active = 1 ORDER BY id ASC");
    $quizzes = $stmt->fetchAll();

    // 4. Fetch Global Leaderboard thinkers
    $stmt = $db->query("SELECT name, score, `rank`, avatar FROM leaderboard ORDER BY `rank` ASC");
    $leaderboard = $stmt->fetchAll();

    echo json_encode([
        "status" => "success",
        "data" => [
            "first_name" => $name,
            "influencer_status" => $influencer_status,
            "contestant_status" => $contestant_status,
            "wallet" => [
                "balance" => $balance,
                "today_winnings" => $today_winnings,
                "deposited" => $total_deposited,
                "rewarded" => $total_rewarded,
                "earned" => $total_earned,
                "withdrawn" => $total_withdrawn
            ],
            "points" => [
                "points" => $points,
                "points_quiz" => $points_quiz,
                "points_challenges" => $points_challenges,
                "points_referrals" => $points_referrals,
                "points_other" => $points_other,
                "rank" => $rank,
                "win_streak" => $win_streak,
                "accuracy_rate" => $accuracy_rate,
                "fastest_answer" => $fastest_answer,
                "today_points" => $today_points
            ],
            "quizzes" => $quizzes,
            "leaderboard" => $leaderboard
        ]
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Dashboard statistics loading failed: " . $e->getMessage()]);
}
?>