<?php
include_once '../config/connect.php';
require_once '../config/topup.php';

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

if (!$call) {
    echo json_encode(["error" => "Database connection failed"]);
    exit();
}

$currentAgent = $_SESSION['admin'] ?? [];
$currentAgentName = agent_public_name((array)$currentAgent);
$currentAgentRefs = agent_identity_values((array)$currentAgent);
$currentAgentLevel = trim((string)($currentAgent['agent_level'] ?? ($_SESSION['agent_level'] ?? '')));
$requestedAgentName = trim((string)($_GET['agent_name'] ?? ''));
$rateAgentName = $currentAgentName;

if ($requestedAgentName !== '' && $currentAgentLevel === 'admin') {
    $rateAgentName = $requestedAgentName;
} elseif ($requestedAgentName !== '' && $currentAgentLevel === 'head_agent') {
    $requestedAgent = agent_find_by_identifier($call, $requestedAgentName);

    if ($requestedAgent !== null && in_array((string)($requestedAgent['agent_upline'] ?? ''), $currentAgentRefs, true)) {
        $rateAgentName = agent_public_name($requestedAgent);
    }
}

$rateCoin = topup_get_agent_rate($call, $rateAgentName);
$globalRateCoin = topup_get_global_rate($call);

$startDate = isset($_GET['start']) ? mysqli_real_escape_string($call, $_GET['start']) : null;
$endDate = isset($_GET['end']) ? mysqli_real_escape_string($call, $_GET['end']) : null;
$dateFilter = isset($_GET['date']) ? mysqli_real_escape_string($call, $_GET['date']) : date("Y-m-d");

$whereClause = "AND DATE(tanggal) = '$dateFilter'";

if ($startDate && $endDate) {
    $whereClause = "AND DATE(tanggal) BETWEEN '$startDate' AND '$endDate'";
}

$query = mysqli_query($call, "SELECT id, amount, harga, tanggal FROM tb_topup WHERE COALESCE(metode, '') <> 'INJECTED' $whereClause");

$transactions = [];
$totalAmount = 0;
$totalHarga = 0;

while ($row = mysqli_fetch_assoc($query)) {
    $amount = (float)$row["amount"];
    $harga = (float)$row["harga"];

    $transactions[] = [
        "id" => $row["id"],
        "amount" => $amount,
        "harga" => $harga,
        "date" => $row["tanggal"]
    ];

    $totalAmount += $amount;
    $totalHarga += $harga;
}

echo json_encode([
    "rate_coin" => $rateCoin,
    "global_rate_coin" => $globalRateCoin,
    "agent_name" => $rateAgentName,
    "transactions" => $transactions,
    "total_amount" => $totalAmount,
    "total_harga" => $totalHarga
]);
?>
