<?php
header('Access-Control-Allow-Origin: *'); // Admin panel cross-origin access ke liye
header('Content-Type: application/json');
require_once '../config/db.php';

// Debugging (Production me isse off kar dein)
error_reporting(E_ALL);
ini_set('display_errors', 1);

$type = $_GET['type'] ?? 'users';
$data = [];

try {
    if ($type === 'users') {
// Is query ko apne admin-fetch.php mein 'users' wale block mein replace karein
$query = "
    SELECT 
        u.id, u.wallet, u.name, u.email, u.mobile, u.referral_id, 
        u.account_id, u.balance, u.leocxx_coin, u.leoexx_balance, u.password,
        u.created_at AS joining_date,
        COALESCE(u.stop_roi,   0) AS stop_roi,
        COALESCE(u.stop_level, 0) AS stop_level,
        COALESCE(u.stop_all,   0) AS stop_all,
        COALESCE(u.reward_tier_1, 0) AS reward_tier_1,
        COALESCE(u.reward_tier_2, 0) AS reward_tier_2,
        COALESCE(u.reward_tier_3, 0) AS reward_tier_3,
        CASE 
            WHEN u.status = 'blocked' THEN 'blocked'
            WHEN COALESCE(SUM(CASE WHEN d.status = 'success' THEN d.amount ELSE 0 END), 0) > 0 THEN 'active'
            ELSE 'inactive'
        END AS status,
        sp.name AS sponsor_name,
        MIN(CASE WHEN d.status = 'success' THEN d.created_at END) AS activation_date,
        COALESCE(SUM(CASE WHEN d.status = 'success' THEN d.amount ELSE 0 END), 0) AS activation_amount
    FROM users u
    LEFT JOIN users sp ON sp.account_id = u.referral_id
    LEFT JOIN deposits d ON d.wallet = u.wallet
    GROUP BY u.id, u.wallet, u.name, u.email, u.mobile, u.referral_id,
             u.account_id, u.balance, u.leocxx_coin, u.leoexx_balance, u.password,
             u.created_at, u.status, u.stop_roi, u.stop_level, u.stop_all,
             u.reward_tier_1, u.reward_tier_2, u.reward_tier_3, sp.name
    ORDER BY u.id ASC
";

        $res = mysqli_query($conn, $query);
        if (!$res) throw new Exception('Users Query Error: ' . mysqli_error($conn));
        $data = mysqli_fetch_all($res, MYSQLI_ASSOC);

        // Serial Number (S.No) add karne ke liye
        foreach ($data as $key => $row) {
            $data[$key]['sno'] = $key + 1;
        }

    } elseif ($type === 'deposits') {
        $query = "
            SELECT d.*, u.name, u.email, u.mobile, u.account_id 
            FROM deposits d
            LEFT JOIN users u ON d.wallet = u.wallet
            ORDER BY d.id DESC
        ";
        $res = mysqli_query($conn, $query);
        if (!$res) throw new Exception("Deposits Error: " . mysqli_error($conn));
        $data = mysqli_fetch_all($res, MYSQLI_ASSOC);

    }  // Is block ko apni API file ke withdrawals section me replace karein
 elseif ($type === 'withdrawals') {
    // Check if $conn exists
    if (!isset($conn)) {
        throw new Exception("Database connection variable '$conn' not found.");
    }

    $query = "SELECT * FROM withdrawals ORDER BY id DESC"; // Simple query for testing
    
    $res = mysqli_query($conn, $query);
    if (!$res) {
        throw new Exception("Query Failed: " . mysqli_error($conn));
    }
    $data = mysqli_fetch_all($res, MYSQLI_ASSOC);
    
}elseif ($type === 'incomes') {
        $query = "
            SELECT i.*, u.name, u.email 
            FROM incomes i 
            LEFT JOIN users u ON i.wallet = u.wallet 
            ORDER BY i.id DESC
        ";
        $res = mysqli_query($conn, $query);
        if (!$res) throw new Exception("Incomes Error: " . mysqli_error($conn));
        $data = mysqli_fetch_all($res, MYSQLI_ASSOC);
    }

    // Response bhejna
    echo json_encode($data);

} 

catch (Exception $e) {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}
?>