<?php
include_once 'connect.php';

if(isset($_SESSION['admin'])){    
    
function getApiConfig(mysqli $db, string $name): array
{
    $name = mysqli_real_escape_string($db, $name);
    $q = mysqli_query($db, "SELECT * FROM tb_api_config WHERE api_name='$name' LIMIT 1");
    if (!$q || mysqli_num_rows($q) === 0) {
        throw new Exception("API CONFIG NOT FOUND: $name");
    }
    return mysqli_fetch_assoc($q);
}

/* ======================================================
   PRIMARY GAME SERVICE CLASS
====================================================== */
class Whitelabel
{
    private $urlRequest;
    private $agentCode;
    private $secretKey;

    public function __construct(mysqli $db)
    {
        $cfg = getApiConfig($db, 'NEXUSGGR');
        $this->urlRequest = $cfg['api_url'];
        $this->agentCode  = $cfg['agent_code'];
        $this->secretKey  = $cfg['secret_key'];
    }

    public function agentBalance()
    {
        return $this->connect([
            'method'       => 'money_info',
            'agent_code'   => $this->agentCode,
            'agent_token'  => $this->secretKey
        ]);
    }

    public function callPlayer()
    {
        return $this->connect([
            'method'       => 'call_players',
            'agent_code'   => $this->agentCode,
            'agent_token'  => $this->secretKey
        ]);
    }

    public function callList($provider, $gamecode)
    {
        return $this->connect([
            'method'        => 'call_list',
            'agent_code'    => $this->agentCode,
            'agent_token'   => $this->secretKey,
            'provider_code' => $provider,
            'game_code'     => $gamecode
        ]);
    }

    public function callApply($provider, $gamecode, $usercode, $rtp, $type)
    {
        return $this->connect([
            'method'        => 'call_apply',
            'agent_code'    => $this->agentCode,
            'agent_token'   => $this->secretKey,
            'provider_code' => $provider,
            'game_code'     => $gamecode,
            'user_code'     => $usercode,
            'call_rtp'      => $rtp,
            'call_type'     => $type
        ]);
    }

    public function callHistory($offset, $limit)
    {
        return $this->connect([
            'method'      => 'call_history',
            'agent_code'  => $this->agentCode,
            'agent_token' => $this->secretKey,
            'offset'      => $offset,
            'limit'       => $limit
        ]);
    }

    public function getGameLog($userCode, $gameType, $start, $end, $page, $perPage)
    {
        return $this->connect([
            'method'      => 'get_game_log',
            'agent_code'  => $this->agentCode,
            'agent_token' => $this->secretKey,
            'user_code'   => $userCode,
            'game_type'   => $gameType,
            'start'       => $start,
            'end'         => $end,
            'page'        => $page,
            'perPage'     => $perPage
        ]);
    }

    private function connect(array $payload)
    {
        $ch = curl_init($this->urlRequest);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_HTTPHEADER     => ['Content-Type: application/json', 'Accept-Encoding: gzip'],
            CURLOPT_POSTFIELDS     => json_encode($payload),
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_TIMEOUT        => 60,
            CURLOPT_ENCODING       => 'gzip',
        ]);
        $res = curl_exec($ch);
        if ($res === false) {
            $error = curl_error($ch);
            curl_close($ch);

            return [
                'status' => 0,
                'msg' => $error !== '' ? $error : 'API_CURL_ERROR',
            ];
        }
        curl_close($ch);

        $decoded = json_decode($res, true);
        if (!is_array($decoded)) {
            return [
                'status' => 0,
                'msg' => 'API_INVALID_JSON_RESPONSE',
            ];
        }

        return $decoded;
    }
}

/* ======================================================
   SECONDARY GAME SERVICE CLASS
====================================================== */
class Zulhayker
{
    private $url;
    private $agent;
    private $token;

    public function __construct(mysqli $db)
    {
        $cfg = getApiConfig($db, 'SGX');
        $this->url   = $cfg['api_url'];
        $this->agent = $cfg['agent_code'];
        $this->token = $cfg['secret_key'];
    }

    public function agentBalance()
    {
        return $this->connect([
            'command'    => 'agent_info',
            'agent_code' => $this->agent,
            'signature'  => $this->token
        ]);
    }

    public function getGameHistory($userCode = '', $limit = 300)
    {
        $limit = (int)$limit;
        if ($limit <= 0) {
            $limit = 300;
        } elseif ($limit > 500) {
            $limit = 500;
        }

        $payload = [
            'command'    => 'game_history',
            'agent_code' => $this->agent,
            'signature'  => $this->token,
            'limit'      => $limit
        ];

        $userCode = trim((string)$userCode);
        if ($userCode !== '') {
            $payload['user_code'] = $userCode;
        }

        $res = $this->connect($payload);
        return json_decode($res, true);
    }

    private function connect(array $payload)
    {
        $ch = curl_init($this->url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
            CURLOPT_POSTFIELDS     => json_encode($payload),
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_TIMEOUT        => 60,
        ]);
        $res = curl_exec($ch);
        if ($res === false) {
            $error = curl_error($ch);
            curl_close($ch);

            return json_encode([
                'status' => 0,
                'message' => $error !== '' ? $error : 'API_CURL_ERROR',
            ]);
        }

        curl_close($ch);
        return $res;
    }
}

$GS = new Whitelabel($call);
$ZH = new Zulhayker($call);

$sql = "SELECT created, amount FROM tb_transaction ORDER BY created DESC LIMIT 10";
$result = mysqli_query($call, $sql);

$flotData = [];
if ($result && mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $flotData[] = [(int)strtotime($row['created']) * 1000, (float)$row['amount']];
    }
}

if (isset($_SESSION['admin']) && (isset($_SESSION['admin']['agent_name']) || isset($_SESSION['admin']['agent_code']))) {
    $sessionAgentIdentity = (string)($_SESSION['admin']['agent_name'] ?? $_SESSION['admin']['agent_code']);
    $data_admin = agent_find_by_identifier($call, $sessionAgentIdentity) ?? [];
    $operator = !empty($data_admin) ? agent_public_name($data_admin) : '';
} else {
    $operator = '';
}

$operatorSql = mysqli_real_escape_string($call, (string)$operator);
$operatorWhere = !empty($data_admin) ? agent_reference_condition($call, 'agent_code', $data_admin) : "agent_code = '$operatorSql'";

if (isset($data_admin) && isset($data_admin['agent_level']) && $data_admin['agent_level'] == "admin") {
    $memberStats = mysqli_query($call, "SELECT COUNT(*) AS total_member, COALESCE(SUM(balance), 0) AS total_balance FROM tb_user");
} else {
    $memberStats = mysqli_query($call, "SELECT COUNT(*) AS total_member, COALESCE(SUM(balance), 0) AS total_balance FROM tb_user WHERE $operatorWhere");
}
$memberStatsRow = ($memberStats) ? (mysqli_fetch_array($memberStats, MYSQLI_ASSOC) ?: []) : [];
$jumlah_member = (int)($memberStatsRow['total_member'] ?? 0);
$jumlah_saldo = (float)($memberStatsRow['total_balance'] ?? 0);

if (isset($data_admin['agent_level']) && $data_admin['agent_level'] == "admin") {
    $bettingStats = mysqli_query($call, "SELECT COUNT(*) AS total_betting FROM tb_history");
} else {
    $bettingStats = mysqli_query($call, "SELECT COUNT(*) AS total_betting FROM tb_history WHERE $operatorWhere");
}
$bettingStatsRow = ($bettingStats) ? (mysqli_fetch_array($bettingStats, MYSQLI_ASSOC) ?: []) : [];
$jumlah_betting = (int)($bettingStatsRow['total_betting'] ?? 0);

$c_hasil = mysqli_query($call, "SELECT SUM(amount) AS hasil FROM tb_transfer WHERE from_agent = 'parent_admin' AND action = 'deposit'");
$hasil = ($c_hasil) ? (mysqli_fetch_array($c_hasil, MYSQLI_ASSOC)['hasil'] ?? 0) : 0;

$operatorUplineWhere = !empty($data_admin) ? agent_reference_condition($call, 'agent_upline', $data_admin) : "agent_upline = '$operatorSql'";
$cek_j_agent = mysqli_query($call, "SELECT COUNT(*) AS total_agent FROM tb_agent WHERE $operatorUplineWhere");
$jumlahAgentRow = ($cek_j_agent) ? (mysqli_fetch_array($cek_j_agent, MYSQLI_ASSOC) ?: []) : [];
$jumlah_agent = (int)($jumlahAgentRow['total_agent'] ?? 0);

$cek_admin_agent = mysqli_query($call, "SELECT COUNT(*) AS total_agent FROM tb_agent");
$jumlahAdminAgentRow = ($cek_admin_agent) ? (mysqli_fetch_array($cek_admin_agent, MYSQLI_ASSOC) ?: []) : [];
$jumlah_agent_admin = (int)($jumlahAdminAgentRow['total_agent'] ?? 0);

$cek_game = mysqli_query($call, "SELECT COUNT(DISTINCT game_name) AS total_game FROM tb_game");
$jumlahGameRow = ($cek_game) ? (mysqli_fetch_array($cek_game, MYSQLI_ASSOC) ?: []) : [];
$jumlah_game = (int)($jumlahGameRow['total_game'] ?? 0);

$gamelist = mysqli_query($call, "SELECT * FROM tb_game WHERE id IN (SELECT MIN(id) FROM tb_game GROUP BY game_name) LIMIT 1");
$gameH = mysqli_fetch_array($gamelist, MYSQLI_ASSOC) ?? [];

$cek_provider = mysqli_query($call, "SELECT COUNT(DISTINCT provider_name) AS total_provider FROM tb_provider");
$jumlahProviderRow = ($cek_provider) ? (mysqli_fetch_array($cek_provider, MYSQLI_ASSOC) ?: []) : [];
$jumlah_provider = (int)($jumlahProviderRow['total_provider'] ?? 0);

$gscc = $GS->agentBalance();

if (is_array($gscc) && isset($gscc['status']) && $gscc['status'] == 1 && isset($gscc['agent']['balance'])) {
    $gsc = number_format($gscc['agent']['balance']);
} else {
    $gsc = is_array($gscc) ? (string)($gscc['msg'] ?? $gscc['message'] ?? '0') : '0';
}
$chaos = json_decode($ZH->agentbalance(),true);

if (is_array($chaos) && isset($chaos['status']) && $chaos['status'] == 200 && isset($chaos['data']['balance'])) {
    $chaoss = number_format($chaos['data']['balance']);
} else {
    $chaoss = is_array($chaos) ? (string)($chaos['message'] ?? $chaos['msg'] ?? '0') : '0';
}
} else {
	header('location: login.php');
}
