<?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 using constants
$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 (returns 0 if null)
function getSafeSum($value) {
    return $value === null ? 0 : floatval($value);
}

// Fetch totals from liveaccounts
$totalsQuery = "
    SELECT 
        SUM(deposit) AS total_deposits,
        SUM(withdraw) AS total_withdraws,
        SUM(deposit) - SUM(withdraw) AS net_deposit,
        SUM(Balance) AS total_equity,
        SUM(deposit) AS total_credit,
        SUM(deposit) - SUM(withdraw) AS credit_used,
        SUM(Balance) AS withdrawable_equity
    FROM liveaccounts
";
$result = $conn->query($totalsQuery);
$totals = $result ? $result->fetch_assoc() : [];

// Safe defaults if no data
$totals = [
    "total_deposits" => getSafeSum($totals['total_deposits'] ?? 0),
    "total_withdraws" => getSafeSum($totals['total_withdraws'] ?? 0),
    "net_deposit" => getSafeSum($totals['net_deposit'] ?? 0),
    "total_equity" => getSafeSum($totals['total_equity'] ?? 0),
    "total_credit" => getSafeSum($totals['total_credit'] ?? 0),
    "credit_used" => getSafeSum($totals['credit_used'] ?? 0),
    "withdrawable_equity" => getSafeSum($totals['withdrawable_equity'] ?? 0),
];

// 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 = $totals['total_deposits'] + $totals['total_withdraws'];

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

$conn->close();
