<?php
require_once '../config/connect.php';
require_once '../config/whatsapp.php';
require_once '../config/topup.php';
include_once __DIR__ . '/../../../../vendor/autoload.php';
session_start();

if (isset($_POST['topup_pro'])) {

    $config = HTMLPurifier_Config::createDefault();
    $purifier = new HTMLPurifier($config);

    $tokenx = $purifier->purify($_POST['AgentReq']);
    $amountx = $purifier->purify($_POST['amount']);
    $coin_amountx = $purifier->purify($_POST['balance']);
    $metodex = $purifier->purify($_POST['payment_method']);
    
    $nama_rekening = isset($_POST['nama_rekening']) ? $_POST['nama_rekening'] : '';
    $nomor_rekening = isset($_POST['nomor_rekening']) ? $_POST['nomor_rekening'] : '';
    
    $token = mysqli_real_escape_string($call, $tokenx);
    $amount = mysqli_real_escape_string($call, $amountx);
    $coin_amount = (float)str_replace([',', '.', ' '], '', (string)$coin_amountx);
    $metode = mysqli_real_escape_string($call, $metodex);
    $whatsappx = wa_get_verified_agent_whatsapp($call, $token);
    if ($whatsappx === '') {
        $whatsappx = wa_get_agent_whatsapp($call, $token);
    }

    if (isset($data_admin['level']) && $data_admin['level'] == "connect") {
        header('Location: ../Topup?msg=24');
        exit();
    } elseif ($whatsappx === '') {
        header('Location: ../VerifyWhatsapp?msg=70');
        exit();
    } else {
        $result = topup_create_request($call, [
            'agent_name' => $token,
            'whatsapp' => $whatsappx,
            'amount' => (float)str_replace([',', '.', ' '], '', (string)$amount),
            'balance' => $coin_amount,
            'payment_method' => $metode,
            'nama_rekening' => $nama_rekening,
            'nomor_rekening' => $nomor_rekening,
        ]);

        if (!$result['ok']) {
            header('Location: ../Topup?msg=' . topup_error_to_msg_code((string)$result['code']));
            exit();
        }

        $agentData = agent_find_by_identifier($call, $token) ?? [];
        $agentName = trim((string)($agentData['agent_name'] ?? '-'));
        $agentLevel = trim((string)($agentData['agent_level'] ?? '-'));
        $currencyAmount = number_format((float)$result['amount'], 0, ',', '.');
        $coinLabel = number_format((float)$result['balance'], 0, ',', '.');
        $adminUrl = wa_app_url('ProsesTopup');
        $invoiceUrl = (string)$result['checkout_url'];

        if (topup_is_qris_method((string)$result['payment_method'])) {
            $qrUrl = (string)($result['gateway']['qr_url'] ?? bayarvip_qr_url($call, (string)$result['trxid']));

            $adminMessage = "Request topup QRIS baru\n"
                . "TrxID: {$result['trxid']}\n"
                . "Agent: {$agentName}\n"
                . "Level: {$agentLevel}\n"
                . "Nominal: Rp {$currencyAmount}\n"
                . "Coin: {$coinLabel}\n"
                . "Metode: QRIS Otomatis\n"
                . "Payment ID: {$result['nomor_rekening']}\n"
                . "Invoice: {$invoiceUrl}\n"
                . "Waktu: {$result['created']}\n"
                . "Monitor admin: {$adminUrl}";

            $agentMessage = "Request topup QRIS diterima\n"
                . "TrxID: {$result['trxid']}\n"
                . "Nominal: Rp {$currencyAmount}\n"
                . "Coin: {$coinLabel}\n"
                . "Status: Menunggu pembayaran QRIS\n"
                . "Invoice: {$invoiceUrl}\n"
                . "QRIS: {$qrUrl}";

            wa_send_admin_alert($call, $adminMessage);
            wa_send_message($call, (string)$result['whatsapp'], $agentMessage);

            header('Location: ../Invoice?trxid=' . urlencode((string)$result['trxid']) . '&msg=74');
            exit();
        }

        $adminMessage = "Request topup baru\n"
            . "TrxID: {$result['trxid']}\n"
            . "Agent: {$agentName}\n"
            . "Level: {$agentLevel}\n"
            . "Nominal: Rp {$currencyAmount}\n"
            . "Coin: {$coinLabel}\n"
            . "Metode: {$result['payment_method']}\n"
            . "Rekening: {$result['nama_rekening']} / {$result['nomor_rekening']}\n"
            . "Waktu: {$result['created']}\n"
            . "Proses admin: {$adminUrl}";

        $agentMessage = "Request topup diterima\n"
            . "TrxID: {$result['trxid']}\n"
            . "Nominal: Rp {$currencyAmount}\n"
            . "Coin: {$coinLabel}\n"
            . "Metode: {$result['payment_method']}\n"
            . "Transfer ke: {$result['nama_rekening']} / {$result['nomor_rekening']}\n"
            . "Status: Menunggu konfirmasi admin";

        wa_send_admin_alert($call, $adminMessage);
        wa_send_message($call, (string)$result['whatsapp'], $agentMessage);

        header('Location: ../Topup?msg=29');
        exit();
    }
    header("Location: ../Topup");
    exit();
} else {
    header('Location: ../Topup?msg=24');
    exit();
}
?>
