<?php
// get_dashboard_data.php — Backend Logic for Dashboard

// 1. Settings
header('Content-Type: application/json');
date_default_timezone_set('Asia/Kolkata');
error_reporting(0); // JSON break na ho isliye errors chupao

// 2. Database Connection
if (file_exists("includes/config.php")) {
    require_once "includes/config.php";
} elseif (file_exists("../includes/config.php")) {
    require_once "../includes/config.php";
} else {
    echo json_encode(["error" => "Config missing"]);
    exit;
}

// 3. Time Variables
$today = date('Y-m-d'); // Sirf date use karenge taaki exact match ho sake

// Helper functions for Safe Query Execution (Crash se bachane ke liye)
function get_val($conn, $sql) {
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        return (float)($row['val'] ?? 0);
    }
    return 0;
}

function get_count($conn, $sql) {
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        return (int)($row['val'] ?? 0);
    }
    return 0;
}

// Deposit and Withdrawal Statuses (Catch all possible positive statuses)
$dep_status = "'success', 'successful', '1', 'approved', 'completed'";
$wd_status  = "'approved', 'success', 'completed', '1'";
$pend_status = "'pending', '0'";

// ====================================================
// 4. MAIN KPI QUERIES
// ====================================================

// A. Total Users
$total_users = get_count($conn, "SELECT COUNT(id) as val FROM users");

// B. Total Deposits (All Time - Success only)
$total_deposits = get_val($conn, "SELECT SUM(amount) as val FROM deposits WHERE status IN ($dep_status)");

// C. Total Withdrawals (All Time - Success only)
$total_withdrawals = get_val($conn, "SELECT SUM(amount) as val FROM withdrawals WHERE status IN ($wd_status)");

// D. Pending Withdrawals Count
$pending_withdrawals = get_count($conn, "SELECT COUNT(id) as val FROM withdrawals WHERE status IN ($pend_status)");

// E. 💸 Today Income Distributed (Actual money distributed to users via daily plans)
$today_income = get_val($conn, "SELECT SUM(amount) as val FROM daily_income_log WHERE DATE(created_at) = '$today'");

// F. Today Gateway Deposits (Gateway ID != 1)
$today_gdep = get_val($conn, "SELECT SUM(amount) as val FROM deposits WHERE status IN ($dep_status) AND (gateway_id != 1 OR gateway_id IS NULL) AND DATE(created_at) = '$today'");

// G. 🔥 Today Manual Deposits (Gateway ID = 1)
$today_mdep = get_val($conn, "SELECT SUM(amount) as val FROM deposits WHERE status IN ($dep_status) AND gateway_id = 1 AND DATE(created_at) = '$today'");

// H. Today Withdrawals
$today_wd = get_val($conn, "SELECT SUM(amount) as val FROM withdrawals WHERE status IN ($wd_status) AND DATE(created_at) = '$today'");


// ====================================================
// 5. CHARTS DATA (Last 7 Days)
// ====================================================
$labels = [];
$chart_dep = [];
$chart_with = [];
$chart_users = [];
$chart_income = [];

for ($i = 6; $i >= 0; $i--) {
    $d = date('Y-m-d', strtotime("-$i days"));
    $labels[] = date('d M', strtotime($d));
    
    // Daily Deposit
    $dep_val = get_val($conn, "SELECT SUM(amount) as val FROM deposits WHERE status IN ($dep_status) AND DATE(created_at)='$d'");
    $chart_dep[] = $dep_val;
    
    // Daily Withdrawal
    $chart_with[] = get_val($conn, "SELECT SUM(amount) as val FROM withdrawals WHERE status IN ($wd_status) AND DATE(created_at)='$d'");

    // Daily New Users
    $chart_users[] = get_count($conn, "SELECT COUNT(id) as val FROM users WHERE DATE(created_at)='$d'");
    
    // 💸 Daily Income Distributed (Real data from logs)
    $chart_income[] = get_val($conn, "SELECT SUM(amount) as val FROM daily_income_log WHERE DATE(created_at)='$d'");
}

// ====================================================
// 6. LEADERBOARD (Top 5 Real Depositors)
// ====================================================
$lb_sql = "SELECT u.mobile, SUM(d.amount) as total 
           FROM deposits d 
           JOIN users u ON d.user_id = u.id 
           WHERE d.status IN ($dep_status) AND (d.gateway_id != 1 OR d.gateway_id IS NULL)
           GROUP BY d.user_id 
           ORDER BY total DESC 
           LIMIT 5";

$lb_res = $conn->query($lb_sql);
$leaderboard = [];

if ($lb_res && $lb_res->num_rows > 0) {
    while($row = $lb_res->fetch_assoc()) {
        $leaderboard[] = $row;
    }
}

// ====================================================
// 7. FINAL JSON OUTPUT
// ====================================================
$response = [
    "total_users"           => $total_users,
    "total_deposits"        => $total_deposits,
    "total_withdrawals"     => $total_withdrawals,
    "pending_withdrawals"   => $pending_withdrawals,
    "today_income"          => $today_income,
    "today_gateway_deposits"=> $today_gdep,  
    "today_manual_deposits" => $today_mdep,  
    "today_withdrawals"     => $today_wd,
    "charts" => [
        "labels"      => $labels,
        "deposits"    => $chart_dep,
        "withdrawals" => $chart_with,
        "new_users"   => $chart_users,
        "income"      => $chart_income
    ],
    "leaderboard" => $leaderboard
];

echo json_encode($response);
?>