<?php
// Ensure CORS is allowed. config.php handles standard headers.
require_once '../config.php';

// Action dispatcher
$action = isset($_GET['action']) ? $_GET['action'] : '';

try {
    $db = getDBConnection();

    if ($action === 'get_stats') {
        // Total Users
        $totalUsers = $db->query("SELECT COUNT(*) FROM users")->fetchColumn();
        // Total Points distributed
        $totalPoints = $db->query("SELECT SUM(points) FROM users")->fetchColumn() ?: 0;
        // Total Wallets balance
        $totalBalance = $db->query("SELECT SUM(balance) FROM wallets")->fetchColumn() ?: 0.00;
        // Total Earned/Paid
        $totalEarned = $db->query("SELECT SUM(amount) FROM wallet_transactions WHERE action = 'reward'")->fetchColumn() ?: 0.00;
        $totalWithdrawn = $db->query("SELECT SUM(amount) FROM wallet_transactions WHERE action = 'withdraw'")->fetchColumn() ?: 0.00;

        // Total Quiz Attempts
        $totalAttempts = $db->query("SELECT COUNT(*) FROM quiz_attempts")->fetchColumn() ?: 0;
        // Total Questions count
        $totalQuestions = $db->query("SELECT COUNT(*) FROM quiz_questions")->fetchColumn() ?: 0;

        echo json_encode([
            "status" => "success",
            "stats" => [
                "total_users" => intval($totalUsers),
                "total_points" => intval($totalPoints),
                "total_balance" => floatval($totalBalance),
                "total_earned" => floatval($totalEarned),
                "total_withdrawn" => floatval($totalWithdrawn),
                "total_attempts" => intval($totalAttempts),
                "total_questions" => intval($totalQuestions)
            ]
        ]);
        exit();
    }

    if ($action === 'get_quizzes') {
        $stmt = $db->query("SELECT q.*, (SELECT COUNT(*) FROM quiz_questions WHERE quiz_id = q.id) as question_count, (SELECT COUNT(*) FROM quiz_attempts WHERE quiz_id = q.id) as attempt_count FROM quizzes q ORDER BY q.id ASC");
        $quizzes = $stmt->fetchAll();
        echo json_encode(["status" => "success", "quizzes" => $quizzes]);
        exit();
    }

    if ($action === 'toggle_quiz') {
        $data = json_decode(file_get_contents("php://input"), true);
        $quizId = intval($data['quiz_id'] ?? 0);
        $isActive = intval($data['is_active'] ?? 1);

        $stmt = $db->prepare("UPDATE quizzes SET is_active = ? WHERE id = ?");
        $stmt->execute([$isActive, $quizId]);

        echo json_encode(["status" => "success", "message" => "Quiz status updated successfully."]);
        exit();
    }

    if ($action === 'get_questions') {
        $quizId = isset($_GET['quiz_id']) ? intval($_GET['quiz_id']) : 0;
        $difficulty = isset($_GET['difficulty']) ? $_GET['difficulty'] : '';
        $search = isset($_GET['search']) ? $_GET['search'] : '';
        $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 50;
        $offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0;

        $query = "SELECT q.*, qz.title as quiz_title FROM quiz_questions q JOIN quizzes qz ON q.quiz_id = qz.id WHERE 1=1";
        $params = [];

        if ($quizId > 0) {
            $query .= " AND q.quiz_id = ?";
            $params[] = $quizId;
        }
        if (!empty($difficulty)) {
            $query .= " AND q.difficulty = ?";
            $params[] = $difficulty;
        }
        if (!empty($search)) {
            $query .= " AND q.question_text LIKE ?";
            $params[] = "%$search%";
        }

        $query .= " ORDER BY q.id DESC LIMIT " . intval($limit) . " OFFSET " . intval($offset);
        $stmt = $db->prepare($query);
        $stmt->execute($params);
        $questions = $stmt->fetchAll();

        // Get total count for pagination
        $countQuery = "SELECT COUNT(*) FROM quiz_questions q WHERE 1=1";
        $countParams = [];
        if ($quizId > 0) {
            $countQuery .= " AND q.quiz_id = ?";
            $countParams[] = $quizId;
        }
        if (!empty($difficulty)) {
            $countQuery .= " AND q.difficulty = ?";
            $countParams[] = $difficulty;
        }
        if (!empty($search)) {
            $countQuery .= " AND q.question_text LIKE ?";
            $countParams[] = "%$search%";
        }
        $stmtCount = $db->prepare($countQuery);
        $stmtCount->execute($countParams);
        $total = $stmtCount->fetchColumn();

        echo json_encode(["status" => "success", "questions" => $questions, "total" => intval($total)]);
        exit();
    }

    if ($action === 'add_question') {
        $data = json_decode(file_get_contents("php://input"), true);
        $quizId = intval($data['quiz_id'] ?? 0);
        $questionText = trim($data['question_text'] ?? '');
        $optA = trim($data['option_a'] ?? '');
        $optB = trim($data['option_b'] ?? '');
        $optC = trim($data['option_c'] ?? '');
        $optD = trim($data['option_d'] ?? '');
        $correctOption = intval($data['correct_option'] ?? 0); // 0 = A, 1 = B, 2 = C, 3 = D
        $difficulty = trim($data['difficulty'] ?? 'easy');

        if ($quizId <= 0 || empty($questionText) || empty($optA) || empty($optB) || empty($optC) || empty($optD)) {
            http_response_code(400);
            echo json_encode(["status" => "error", "message" => "All fields are required to add a question."]);
            exit();
        }

        $stmt = $db->prepare("INSERT INTO quiz_questions (quiz_id, question_text, option_a, option_b, option_c, option_d, correct_option, difficulty) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$quizId, $questionText, $optA, $optB, $optC, $optD, $correctOption, $difficulty]);

        echo json_encode(["status" => "success", "message" => "Question added successfully."]);
        exit();
    }

    if ($action === 'delete_question') {
        $data = json_decode(file_get_contents("php://input"), true);
        $questionId = intval($data['question_id'] ?? 0);

        $stmt = $db->prepare("DELETE FROM quiz_questions WHERE id = ?");
        $stmt->execute([$questionId]);

        echo json_encode(["status" => "success", "message" => "Question deleted successfully."]);
        exit();
    }

    if ($action === 'import_questions') {
        $data = json_decode(file_get_contents("php://input"), true);
        $questions = $data['questions'] ?? [];

        if (empty($questions) || !is_array($questions)) {
            http_response_code(400);
            echo json_encode(["status" => "error", "message" => "No questions found in the upload payload."]);
            exit();
        }

        $db->beginTransaction();
        $stmt = $db->prepare("INSERT INTO quiz_questions (quiz_id, question_text, option_a, option_b, option_c, option_d, correct_option, difficulty) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");

        $count = 0;
        foreach ($questions as $q) {
            $quizId = intval($q['quiz_id'] ?? 0);
            $text = trim($q['question_text'] ?? '');
            $optA = trim($q['option_a'] ?? '');
            $optB = trim($q['option_b'] ?? '');
            $optC = trim($q['option_c'] ?? '');
            $optD = trim($q['option_d'] ?? '');
            $correct = intval($q['correct_option'] ?? 0);
            $difficulty = trim($q['difficulty'] ?? 'easy');

            if ($quizId > 0 && !empty($text) && !empty($optA) && !empty($optB)) {
                $stmt->execute([$quizId, $text, $optA, $optB, $optC, $optD, $correct, $difficulty]);
                $count++;
            }
        }
        $db->commit();

        echo json_encode(["status" => "success", "message" => "Successfully imported $count questions in bulk."]);
        exit();
    }

    if ($action === 'get_users') {
        $search = isset($_GET['search']) ? $_GET['search'] : '';
        $verified = isset($_GET['verified']) ? $_GET['verified'] : '';
        $balance = isset($_GET['balance']) ? $_GET['balance'] : '';
        $newOnly = isset($_GET['new_only']) ? $_GET['new_only'] : '';
        $referredOnly = isset($_GET['referred_only']) ? $_GET['referred_only'] : '';

        $query = "SELECT u.id, u.full_name, u.email, u.phone, u.points, u.`rank`, u.is_verified, u.referred_by, u.created_at, w.balance FROM users u LEFT JOIN wallets w ON u.id = w.user_id WHERE 1=1";
        $params = [];

        if (!empty($search)) {
            $query .= " AND (u.full_name LIKE ? OR u.email LIKE ? OR u.phone LIKE ?)";
            $params[] = "%$search%";
            $params[] = "%$search%";
            $params[] = "%$search%";
        }
        if ($verified !== '') {
            $query .= " AND u.is_verified = ?";
            $params[] = intval($verified);
        }
        if ($balance === 'positive') {
            $query .= " AND w.balance > 0";
        } elseif ($balance === 'zero') {
            $query .= " AND (w.balance IS NULL OR w.balance = 0)";
        }
        if ($newOnly === '1') {
            $query .= " AND u.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
        }
        if ($referredOnly === '1') {
            $query .= " AND u.referred_by IS NOT NULL AND u.referred_by != ''";
        }

        $query .= " ORDER BY u.points DESC LIMIT 100";
        $stmt = $db->prepare($query);
        $stmt->execute($params);
        $users = $stmt->fetchAll();

        echo json_encode(["status" => "success", "users" => $users]);
        exit();
    }

    if ($action === 'adjust_funds') {
        $data = json_decode(file_get_contents("php://input"), true);
        $userId = intval($data['user_id'] ?? 0);
        $type = trim($data['type'] ?? 'wallet'); // 'wallet' or 'points'
        $method = trim($data['method'] ?? 'add'); // 'add' or 'deduct'
        $amount = floatval($data['amount'] ?? 0);
        $notes = trim($data['notes'] ?? 'Admin Manual Adjustment');

        if ($userId <= 0 || $amount <= 0) {
            http_response_code(400);
            echo json_encode(["status" => "error", "message" => "Invalid user or amount parameters."]);
            exit();
        }

        $db->beginTransaction();

        if ($type === 'wallet') {
            // Lock and get wallet
            $stmt = $db->prepare("SELECT balance FROM wallets WHERE user_id = ? FOR UPDATE");
            $stmt->execute([$userId]);
            $wallet = $stmt->fetch();
            $balance_before = $wallet ? floatval($wallet['balance']) : 0.00;

            if ($method === 'add') {
                $balance_after = $balance_before + $amount;
                $actionType = 'topup';
            } else {
                $balance_after = max(0, $balance_before - $amount);
                $actionType = 'withdraw';
            }

            // Update balance
            $stmt = $db->prepare("UPDATE wallets SET balance = ? WHERE user_id = ?");
            $stmt->execute([$balance_after, $userId]);

            // Add transaction log
            $ref = uniqid('TXN-ADM-', true);
            $ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
            $stmt = $db->prepare("INSERT INTO wallet_transactions (user_id, action, amount, balance_before, balance_after, reference, ip_address) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$userId, $actionType, $amount, $balance_before, $balance_after, $ref, $ip]);

        } else {
            // Adjust points
            $stmt = $db->prepare("SELECT points FROM users WHERE id = ? FOR UPDATE");
            $stmt->execute([$userId]);
            $points_before = intval($stmt->fetchColumn());

            if ($method === 'add') {
                $points_after = $points_before + intval($amount);
            } else {
                $points_after = max(0, $points_before - intval($amount));
            }

            $stmt = $db->prepare("UPDATE users SET points = ? WHERE id = ?");
            $stmt->execute([$points_after, $userId]);
        }

        $db->commit();
        echo json_encode(["status" => "success", "message" => "Balances updated successfully."]);
        exit();
    }

    if ($action === 'get_transactions') {
        $actionFilter = isset($_GET['action_filter']) ? $_GET['action_filter'] : '';
        $search = isset($_GET['search']) ? $_GET['search'] : '';
        $startDate = isset($_GET['start_date']) ? $_GET['start_date'] : '';
        $endDate = isset($_GET['end_date']) ? $_GET['end_date'] : '';

        $query = "SELECT t.*, u.full_name, u.email FROM wallet_transactions t JOIN users u ON t.user_id = u.id WHERE 1=1";
        $params = [];

        if (!empty($actionFilter)) {
            $query .= " AND t.action = ?";
            $params[] = $actionFilter;
        }
        if (!empty($search)) {
            $query .= " AND (u.full_name LIKE ? OR u.email LIKE ? OR t.reference LIKE ?)";
            $params[] = "%$search%";
            $params[] = "%$search%";
            $params[] = "%$search%";
        }
        if (!empty($startDate)) {
            $query .= " AND DATE(t.created_at) >= ?";
            $params[] = $startDate;
        }
        if (!empty($endDate)) {
            $query .= " AND DATE(t.created_at) <= ?";
            $params[] = $endDate;
        }

        // Calculate Totals using same filters before sorting/limits
        $sumQuery = "SELECT
                        SUM(CASE WHEN t.action = 'topup' THEN t.amount ELSE 0 END) as total_deposits,
                        SUM(CASE WHEN t.action = 'withdraw' THEN t.amount ELSE 0 END) as total_withdrawals,
                        SUM(CASE WHEN t.action = 'reward' THEN t.amount ELSE 0 END) as total_rewards,
                        SUM(CASE WHEN t.action = 'referral' THEN t.amount ELSE 0 END) as total_referrals
                     FROM wallet_transactions t
                     JOIN users u ON t.user_id = u.id
                     WHERE 1=1";
        $sumParams = [];
        if (!empty($actionFilter)) {
            $sumQuery .= " AND t.action = ?";
            $sumParams[] = $actionFilter;
        }
        if (!empty($search)) {
            $sumQuery .= " AND (u.full_name LIKE ? OR u.email LIKE ? OR t.reference LIKE ?)";
            $sumParams[] = "%$search%";
            $sumParams[] = "%$search%";
            $sumParams[] = "%$search%";
        }
        if (!empty($startDate)) {
            $sumQuery .= " AND DATE(t.created_at) >= ?";
            $sumParams[] = $startDate;
        }
        if (!empty($endDate)) {
            $sumQuery .= " AND DATE(t.created_at) <= ?";
            $sumParams[] = $endDate;
        }

        $sumStmt = $db->prepare($sumQuery);
        $sumStmt->execute($sumParams);
        $sums = $sumStmt->fetch();

        // Main transactions query execution
        $query .= " ORDER BY t.id DESC LIMIT 100";
        $stmt = $db->prepare($query);
        $stmt->execute($params);
        $txns = $stmt->fetchAll();

        echo json_encode([
            "status" => "success",
            "transactions" => $txns,
            "totals" => [
                "deposits" => floatval($sums['total_deposits'] ?? 0),
                "withdrawals" => floatval($sums['total_withdrawals'] ?? 0),
                "rewards" => floatval($sums['total_rewards'] ?? 0),
                "referrals" => floatval($sums['total_referrals'] ?? 0)
            ]
        ]);
        exit();
    }

    if ($action === 'get_leaderboard') {
        $stmt = $db->query("SELECT u.id, u.full_name, u.email, u.phone, u.points, u.`rank`, w.balance FROM users u LEFT JOIN wallets w ON u.id = w.user_id ORDER BY u.points DESC LIMIT 100");
        $leaderboard = $stmt->fetchAll();
        echo json_encode(["status" => "success", "leaderboard" => $leaderboard]);
        exit();
    }

    if ($action === 'reward_leader') {
        $data = json_decode(file_get_contents("php://input"), true);
        $userId = intval($data['user_id'] ?? 0);
        $amount = floatval($data['amount'] ?? 0);
        $notes = trim($data['notes'] ?? 'Leaderboard Top 2 Reward');

        if ($userId <= 0 || $amount <= 0) {
            http_response_code(400);
            echo json_encode(["status" => "error", "message" => "Invalid user or amount parameters."]);
            exit();
        }

        // Restrict reward to between the 28th and 31st of the month
        $day = intval(date('j'));
        if ($day < 28 || $day > 31) {
            http_response_code(403);
            echo json_encode(["status" => "error", "message" => "Cash rewards can only be processed between the 28th and 31st of the month."]);
            exit();
        }

        // Verify that the user is actually in the top 2 of the leaderboard
        $top2 = $db->query("SELECT id FROM users ORDER BY points DESC LIMIT 2")->fetchAll(PDO::FETCH_COLUMN);
        if (!in_array($userId, $top2)) {
            http_response_code(403);
            echo json_encode(["status" => "error", "message" => "Only the top two users on the leaderboard can be rewarded."]);
            exit();
        }

        // Validate the exact reward amount (1st = 300,000; 2nd = 200,000)
        $rank = array_search($userId, $top2) + 1;
        $expectedAmount = ($rank === 1) ? 300000.00 : 200000.00;

        if (abs($amount - $expectedAmount) > 0.01) {
            http_response_code(400);
            echo json_encode(["status" => "error", "message" => "Invalid reward amount. First place gets ₦300,000 and second place gets ₦200,000."]);
            exit();
        }

        $db->beginTransaction();

        $stmt = $db->prepare("SELECT balance FROM wallets WHERE user_id = ? FOR UPDATE");
        $stmt->execute([$userId]);
        $wallet = $stmt->fetch();
        $balance_before = $wallet ? floatval($wallet['balance']) : 0.00;
        $balance_after = $balance_before + $amount;

        $stmt = $db->prepare("UPDATE wallets SET balance = ? WHERE user_id = ?");
        $stmt->execute([$balance_after, $userId]);

        $ref = uniqid('TXN-REWARD-', true);
        $ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
        $stmt = $db->prepare("INSERT INTO wallet_transactions (user_id, action, amount, balance_before, balance_after, reference, ip_address) VALUES (?, 'reward', ?, ?, ?, ?, ?)");
        $stmt->execute([$userId, $amount, $balance_before, $balance_after, $ref, $ip]);

        $db->commit();
        echo json_encode(["status" => "success", "message" => "Top leaderboard winner rewarded successfully."]);
        exit();
    }

    if ($action === 'get_withdrawal_profiles') {
        $userId = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
        if ($userId <= 0) {
            http_response_code(400);
            echo json_encode(["status" => "error", "message" => "User ID is required."]);
            exit();
        }
        $stmt = $db->prepare("SELECT * FROM user_withdrawal_profiles WHERE user_id = ?");
        $stmt->execute([$userId]);
        $profiles = $stmt->fetchAll();
        echo json_encode(["status" => "success", "profiles" => $profiles]);
        exit();
    }

    if ($action === 'broadcast_info') {
        $data = json_decode(file_get_contents("php://input"), true);
        $title = trim($data['title'] ?? '');
        $message = trim($data['message'] ?? '');
        $category = trim($data['category'] ?? 'general');

        if (empty($title) || empty($message)) {
            http_response_code(400);
            echo json_encode(["status" => "error", "message" => "Title and Message are required for broadcast."]);
            exit();
        }

        $stmt = $db->prepare("INSERT INTO broadcasts (title, message, category) VALUES (?, ?, ?)");
        $stmt->execute([$title, $message, $category]);

        echo json_encode(["status" => "success", "message" => "Information broadcasted to all users successfully."]);
        exit();
    }

    if ($action === 'get_broadcasts') {
        $stmt = $db->query("SELECT * FROM broadcasts ORDER BY id DESC LIMIT 50");
        $broadcasts = $stmt->fetchAll();
        echo json_encode(["status" => "success", "broadcasts" => $broadcasts]);
        exit();
    }

    if ($action === 'get_user_quiz_stats') {
        $userId = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
        if ($userId <= 0) {
            http_response_code(400);
            echo json_encode(["status" => "error", "message" => "Invalid user ID"]);
            exit();
        }

        $stmt = $db->prepare("SELECT COUNT(*) FROM quiz_attempts WHERE user_id = ?");
        $stmt->execute([$userId]);
        $totalAttempts = intval($stmt->fetchColumn());

        $stmt = $db->prepare("SELECT COUNT(*) FROM quiz_attempts WHERE user_id = ? AND reward_earned > 0");
        $stmt->execute([$userId]);
        $wins = intval($stmt->fetchColumn());

        $stmt = $db->prepare("SELECT COUNT(*) FROM quiz_attempts WHERE user_id = ? AND reward_earned = 0");
        $stmt->execute([$userId]);
        $losses = intval($stmt->fetchColumn());

        $stmt = $db->prepare("SELECT qa.*, q.title as quiz_title FROM quiz_attempts qa JOIN quizzes q ON qa.quiz_id = q.id WHERE qa.user_id = ? ORDER BY qa.created_at DESC LIMIT 10");
        $stmt->execute([$userId]);
        $history = $stmt->fetchAll();

        echo json_encode([
            "status" => "success",
            "total_attempts" => $totalAttempts,
            "wins" => $wins,
            "losses" => $losses,
            "history" => $history
        ]);
        exit();
    }

    if ($action === 'edit_question') {
        $data = json_decode(file_get_contents("php://input"), true);
        $questionId = intval($data['question_id'] ?? 0);
        $quizId = intval($data['quiz_id'] ?? 0);
        $questionText = trim($data['question_text'] ?? '');
        $optA = trim($data['option_a'] ?? '');
        $optB = trim($data['option_b'] ?? '');
        $optC = trim($data['option_c'] ?? '');
        $optD = trim($data['option_d'] ?? '');
        $correctOption = intval($data['correct_option'] ?? 0);
        $difficulty = trim($data['difficulty'] ?? 'easy');

        if ($questionId <= 0 || $quizId <= 0 || empty($questionText) || empty($optA) || empty($optB) || empty($optC) || empty($optD)) {
            http_response_code(400);
            echo json_encode(["status" => "error", "message" => "All fields are required to edit a question."]);
            exit();
        }

        $stmt = $db->prepare("UPDATE quiz_questions SET quiz_id = ?, question_text = ?, option_a = ?, option_b = ?, option_c = ?, option_d = ?, correct_option = ?, difficulty = ? WHERE id = ?");
        $stmt->execute([$quizId, $questionText, $optA, $optB, $optC, $optD, $correctOption, $difficulty, $questionId]);

        echo json_encode(["status" => "success", "message" => "Question updated successfully."]);
        exit();
    }

    if ($action === 'get_influencers') {
        $stmt = $db->query("SELECT i.*, u.full_name, u.email, u.phone, u.points, u.is_verified, w.balance FROM influencers i JOIN users u ON i.user_id = u.id LEFT JOIN wallets w ON u.id = w.user_id ORDER BY i.id DESC");
        $influencers = $stmt->fetchAll();
        echo json_encode(["status" => "success", "influencers" => $influencers]);
        exit();
    }

    if ($action === 'update_influencer_status') {
        $data = json_decode(file_get_contents("php://input"), true);
        $id = intval($data['id'] ?? 0);
        $status = trim($data['status'] ?? 'pending');

        if ($id <= 0 || !in_array($status, ['approved', 'rejected', 'pending'])) {
            http_response_code(400);
            echo json_encode(["status" => "error", "message" => "Invalid parameters."]);
            exit();
        }

        $db->beginTransaction();

        $stmt = $db->prepare("UPDATE influencers SET status = ? WHERE id = ?");
        $stmt->execute([$status, $id]);

        $tempPassword = '';
        if ($status === 'approved') {
            // Get user details
            $stmt = $db->prepare("SELECT i.user_id, u.email, u.full_name FROM influencers i JOIN users u ON i.user_id = u.id WHERE i.id = ?");
            $stmt->execute([$id]);
            $userInfo = $stmt->fetch();

            if ($userInfo) {
                $userId = intval($userInfo['user_id']);
                $userEmail = $userInfo['email'];
                $userName = $userInfo['full_name'];

                // Auto generate a temporal password
                $tempPassword = 'TRN-' . strval(rand(100000, 999999));

                // Update users password, temp_pass_active, and temp_pass_expires_at
                $passwordHash = password_hash($tempPassword, PASSWORD_BCRYPT);

                // Self-healing columns check
                try {
                    $db->exec("ALTER TABLE users ADD COLUMN temp_pass_expires_at DATETIME DEFAULT NULL");
                } catch (Exception $e) {
                }
                try {
                    $db->exec("ALTER TABLE users ADD COLUMN temp_pass_active TINYINT DEFAULT 0");
                } catch (Exception $e) {
                }

                $stmt = $db->prepare("UPDATE users SET password_hash = ?, temp_pass_expires_at = DATE_ADD(NOW(), INTERVAL 48 HOUR), temp_pass_active = 1 WHERE id = ?");
                $stmt->execute([$passwordHash, $userId]);

                // Send email to user
                $subject = "Think Rich Naija - Partnership Approved!";
                $body = "
                    <h2>Congratulations, {$userName}!</h2>
                    <p>Your influencer partnership application has been <strong>approved</strong> by the admin team.</p>
                    <p>To secure your partner account, we have generated a temporary password for you:</p>
                    <p style='font-size: 18px; font-weight: bold; background: #f0f0f0; padding: 10px; display: inline-block; font-family: monospace;'>{$tempPassword}</p>
                    <p><strong>IMPORTANT:</strong> You are given 48 hours to reset your password. Please log in using these details and update your password under Privacy & Security immediately.</p>
                    <p>Best regards,<br>Think Rich Naija Team</p>
                ";
                sendEmail($userEmail, $subject, $body);
            }
        }

        $db->commit();

        $resp = ["status" => "success", "message" => "Influencer status updated successfully."];
        if (!empty($tempPassword)) {
            $resp["temp_password"] = $tempPassword;
        }
        echo json_encode($resp);
        exit();
    }

    if ($action === 'get_contestants') {
        $stmt = $db->query("SELECT c.*, u.full_name, u.email, u.phone, u.points, u.is_verified, w.balance FROM contestants c JOIN users u ON c.user_id = u.id LEFT JOIN wallets w ON u.id = w.user_id ORDER BY c.id DESC");
        $contestants = $stmt->fetchAll();
        echo json_encode(["status" => "success", "contestants" => $contestants]);
        exit();
    }

    if ($action === 'update_contestant_status') {
        $data = json_decode(file_get_contents("php://input"), true);
        $id = intval($data['id'] ?? 0);
        $status = trim($data['status'] ?? 'pending');

        if ($id <= 0 || !in_array($status, ['approved', 'rejected', 'pending'])) {
            http_response_code(400);
            echo json_encode(["status" => "error", "message" => "Invalid parameters."]);
            exit();
        }

        $stmt = $db->prepare("UPDATE contestants SET status = ? WHERE id = ?");
        $stmt->execute([$status, $id]);

        echo json_encode(["status" => "success", "message" => "Contestant status updated successfully."]);
        exit();
    }

    if ($action === 'edit_broadcast') {
        $data = json_decode(file_get_contents("php://input"), true);
        $broadcastId = intval($data['id'] ?? 0);
        $title = trim($data['title'] ?? '');
        $message = trim($data['message'] ?? '');
        $category = trim($data['category'] ?? 'general');

        if ($broadcastId <= 0 || empty($title) || empty($message)) {
            http_response_code(400);
            echo json_encode(["status" => "error", "message" => "All fields are required to edit a broadcast."]);
            exit();
        }

        $stmt = $db->prepare("UPDATE broadcasts SET title = ?, message = ?, category = ? WHERE id = ?");
        $stmt->execute([$title, $message, $category, $broadcastId]);

        echo json_encode(["status" => "success", "message" => "Broadcast updated successfully."]);
        exit();
    }

    if ($action === 'delete_broadcast') {
        $data = json_decode(file_get_contents("php://input"), true);
        $broadcastId = intval($data['id'] ?? 0);

        if ($broadcastId <= 0) {
            http_response_code(400);
            echo json_encode(["status" => "error", "message" => "Invalid Broadcast ID."]);
            exit();
        }

        $stmt = $db->prepare("DELETE FROM broadcasts WHERE id = ?");
        $stmt->execute([$broadcastId]);

        echo json_encode(["status" => "success", "message" => "Broadcast message deleted successfully."]);
        exit();
    }

    if ($action === 'get_analysis') {
        $startDate = isset($_GET['start_date']) ? $_GET['start_date'] : '';
        $endDate = isset($_GET['end_date']) ? $_GET['end_date'] : '';

        // 1. Fetch transactions grouped by date
        $wtQuery = "SELECT 
                        DATE(created_at) as date_grp,
                        SUM(CASE WHEN action = 'topup' THEN amount ELSE 0 END) as deposits,
                        SUM(CASE WHEN action = 'withdraw' THEN amount ELSE 0 END) as withdrawals,
                        SUM(CASE WHEN action = 'reward' THEN amount ELSE 0 END) as rewards,
                        SUM(CASE WHEN action = 'referral' THEN amount ELSE 0 END) as referrals
                    FROM wallet_transactions
                    WHERE 1=1";
        $wtParams = [];
        if (!empty($startDate)) {
            $wtQuery .= " AND DATE(created_at) >= ?";
            $wtParams[] = $startDate;
        }
        if (!empty($endDate)) {
            $wtQuery .= " AND DATE(created_at) <= ?";
            $wtParams[] = $endDate;
        }
        $wtQuery .= " GROUP BY DATE(created_at)";
        $wtStmt = $db->prepare($wtQuery);
        $wtStmt->execute($wtParams);
        $wtResults = $wtStmt->fetchAll(PDO::FETCH_ASSOC);

        // 2. Fetch quiz attempts grouped by date
        $qaQuery = "SELECT 
                        DATE(created_at) as date_grp,
                        COUNT(*) as attempts,
                        SUM(CASE WHEN reward_earned > 0 THEN 1 ELSE 0 END) as won,
                        SUM(CASE WHEN reward_earned = 0 THEN 1 ELSE 0 END) as loss,
                        SUM(reward_earned) as reward_amount
                    FROM quiz_attempts
                    WHERE 1=1";
        $qaParams = [];
        if (!empty($startDate)) {
            $qaQuery .= " AND DATE(created_at) >= ?";
            $qaParams[] = $startDate;
        }
        if (!empty($endDate)) {
            $qaQuery .= " AND DATE(created_at) <= ?";
            $qaParams[] = $endDate;
        }
        $qaQuery .= " GROUP BY DATE(created_at)";
        $qaStmt = $db->prepare($qaQuery);
        $qaStmt->execute($qaParams);
        $qaResults = $qaStmt->fetchAll(PDO::FETCH_ASSOC);

        // 3. Merge both datasets by date
        $analysisMap = [];

        foreach ($wtResults as $row) {
            $d = $row['date_grp'];
            if (!isset($analysisMap[$d])) {
                $analysisMap[$d] = [
                    "date" => $d,
                    "deposits" => 0.0,
                    "withdrawals" => 0.0,
                    "rewards" => 0.0,
                    "referrals" => 0.0,
                    "attempts" => 0,
                    "won" => 0,
                    "loss" => 0,
                    "quiz_reward_earned" => 0.0
                ];
            }
            $analysisMap[$d]["deposits"] = floatval($row['deposits']);
            $analysisMap[$d]["withdrawals"] = floatval($row['withdrawals']);
            $analysisMap[$d]["rewards"] = floatval($row['rewards']);
            $analysisMap[$d]["referrals"] = floatval($row['referrals']);
        }

        foreach ($qaResults as $row) {
            $d = $row['date_grp'];
            if (!isset($analysisMap[$d])) {
                $analysisMap[$d] = [
                    "date" => $d,
                    "deposits" => 0.0,
                    "withdrawals" => 0.0,
                    "rewards" => 0.0,
                    "referrals" => 0.0,
                    "attempts" => 0,
                    "won" => 0,
                    "loss" => 0,
                    "quiz_reward_earned" => 0.0
                ];
            }
            $analysisMap[$d]["attempts"] = intval($row['attempts']);
            $analysisMap[$d]["won"] = intval($row['won']);
            $analysisMap[$d]["loss"] = intval($row['loss']);
            $analysisMap[$d]["quiz_reward_earned"] = floatval($row['reward_amount']);
        }

        // Sort by date DESC
        krsort($analysisMap);
        $analysis = array_values($analysisMap);

        echo json_encode([
            "status" => "success",
            "analysis" => $analysis
        ]);
        exit();
    }

    if ($action === 'admin_login') {
        $data = json_decode(file_get_contents("php://input"), true);
        $email = isset($data['email']) ? trim($data['email']) : '';
        $password = isset($data['password']) ? trim($data['password']) : '';

        $admin_email = 'admin@thinkrichnaija.com';
        $admin_password = 'AdminPassword2026!';

        if (strtolower($email) === strtolower($admin_email) && $password === $admin_password) {
            echo json_encode([
                "status" => "success",
                "message" => "Admin login successful.",
                "token" => "ThinkRichAdminToken2026"
            ]);
            exit();
        } else {
            http_response_code(401);
            echo json_encode([
                "status" => "error",
                "message" => "Invalid admin email or password."
            ]);
            exit();
        }
    }

    echo json_encode(["status" => "error", "message" => "Unknown API endpoint action."]);

} catch (Exception $e) {
    if (isset($db) && $db->inTransaction()) {
        $db->rollBack();
    }
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}
