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

// CORS headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

// Include DB credentials
include_once __DIR__ . '/config.php';

// Connect to database
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) {
    die(json_encode([
        "success" => false,
        "error" => "Database connection failed: " . $conn->connect_error
    ]));
}

// Function to safely get sum
function getSafeSum($value) {
    return $value === null ? 0 : floatval($value);
}

// ===== Fetch totals from wallet tables =====
$totalsQuery = "
    SELECT 
        (SELECT COALESCE(SUM(CAST(deposit_amount AS DECIMAL(18,2))),0) FROM wallet_deposit) AS total_deposits,
        (SELECT COALESCE(SUM(CAST(withdraw_amount AS DECIMAL(18,2))),0) FROM wallet_withdraw) AS total_withdraws,
        (SELECT COALESCE(SUM(Balance),0) FROM liveaccounts) AS total_equity
";
$result = $conn->query($totalsQuery);
$totals = $result ? $result->fetch_assoc() : [];

// Calculate derived fields
$totalDeposits = getSafeSum($totals['total_deposits'] ?? 0);
$totalWithdraws = getSafeSum($totals['total_withdraws'] ?? 0);
$totalEquity = getSafeSum($totals['total_equity'] ?? 0);

$totals = [
    "total_deposits" => $totalDeposits,
    "total_withdraws" => $totalWithdraws,
    "net_deposit" => $totalDeposits - $totalWithdraws,
    "total_equity" => $totalEquity,
    "total_credit" => $totalDeposits,
    "credit_used" => $totalDeposits - $totalWithdraws,
    "withdrawable_equity" => $totalEquity
];

// Fetch total clients
$clientsResult = $conn->query("SELECT COUNT(*) AS total_clients FROM loginusers");
$totalClients = $clientsResult ? intval($clientsResult->fetch_assoc()['total_clients']) : 0;

// Fetch total trading accounts
$accountsResult = $conn->query("SELECT COUNT(*) AS total_accounts FROM liveaccounts");
$totalTradingAccounts = $accountsResult ? intval($accountsResult->fetch_assoc()['total_accounts']) : 0;

// Total transactions (deposits + withdrawals)
$totalTransactions = $totalDeposits + $totalWithdraws;

// Return JSON response
echo json_encode([
    "success" => true,
    "totals" => $totals,
    "total_clients" => $totalClients,
    "total_trading_accounts" => $totalTradingAccounts,
    "total_transactions" => $totalTransactions
]);

$conn->close();
?>
