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

if (isset($_POST['proses'])) {
    $id = (int)($_POST['id'] ?? 0);
    $action = mysqli_real_escape_string($call, $_POST['action'] ?? '');

    if ($id <= 0 || !in_array($action, ['Success', 'Cancel'], true)) {
        header('Location: ../index?page=ProsesTopup&msg=16');
        exit();
    }

    $topupQuery = mysqli_query($call, "SELECT * FROM tb_balance WHERE id = '$id' LIMIT 1");

    if (!$topupQuery || mysqli_num_rows($topupQuery) === 0) {
        header('Location: ../index?page=ProsesTopup&msg=53');
        exit();
    }

    $topup = mysqli_fetch_assoc($topupQuery);

    if (($topup['status'] ?? '') !== 'Pending') {
        header('Location: ../index?page=ProsesTopup&msg=53');
        exit();
    }

    $agentInput = (string)($topup['agent_code'] ?? '');
    $agent = agent_find_by_identifier($call, $agentInput);
    $agentCode = mysqli_real_escape_string($call, $agent !== null ? (string)($agent['agent_code'] ?? agent_public_name($agent)) : $agentInput);
    $agentNameForHistory = mysqli_real_escape_string($call, $agent !== null ? agent_public_name($agent) : $agentInput);
    $balance = (float)($topup['balance'] ?? 0);
    $price = (float)($topup['amount'] ?? 0);
    $metode = mysqli_real_escape_string($call, (string)($topup['metode'] ?? ''));
    $namaRekening = mysqli_real_escape_string($call, (string)($topup['nama_rekening'] ?? ''));
    $nomorRekening = mysqli_real_escape_string($call, (string)($topup['nomor_rekening'] ?? ''));
    $whatsapp = trim((string)($topup['whatsapp'] ?? ''));
    $trxid = trim((string)($topup['trxid'] ?? ''));

    mysqli_begin_transaction($call);

    $updateBalance = mysqli_query(
        $call,
        "UPDATE tb_balance SET status = '$action' WHERE id = '$id' AND status = 'Pending'"
    );

    if (!$updateBalance || mysqli_affected_rows($call) !== 1) {
        mysqli_rollback($call);
        header('Location: ../index?page=ProsesTopup&msg=53');
        exit();
    }

    if ($action === 'Success') {
        $updateAgent = mysqli_query(
            $call,
            "UPDATE tb_agent SET agent_balance = agent_balance + '$balance' WHERE agent_code = '$agentCode'"
        );

        if (!$updateAgent || mysqli_affected_rows($call) !== 1) {
            mysqli_rollback($call);
            header('Location: ../index?page=ProsesTopup&msg=13');
            exit();
        }
    }

    $isQrisMethod = function_exists('topup_is_qris_method') && topup_is_qris_method($metode);
    if ($isQrisMethod || $action === 'Success') {
        $insertTransaksi = mysqli_query(
            $call,
            "INSERT INTO tb_topup (agent_code, amount, harga, metode, nama_rekening, nomor_rekening, tanggal, status)
             VALUES ('$agentNameForHistory', '$balance', '$price', '$metode', '$namaRekening', '$nomorRekening', NOW(), '$action')"
        );

        if (!$insertTransaksi) {
            mysqli_rollback($call);
            header('Location: ../index?page=ProsesTopup&msg=13');
            exit();
        }
    }

    if (!mysqli_commit($call)) {
        mysqli_rollback($call);
        header('Location: ../index?page=ProsesTopup&msg=13');
        exit();
    }

    $agentName = topup_agent_name($call, $agentInput);
    $currencyPrice = number_format($price, 0, ',', '.');
    $coinAmount = number_format($balance, 0, ',', '.');
    $statusLabel = $action === 'Success' ? 'BERHASIL' : 'DITOLAK';

    if ($whatsapp !== '' && $whatsapp !== '0') {
        $message = "Update topup {$statusLabel}\n"
            . "TrxID: {$trxid}\n"
            . "Agent: {$agentName}\n"
            . "Nominal: Rp {$currencyPrice}\n"
            . "Coin: {$coinAmount}\n"
            . "Metode: " . ($topup['metode'] ?? '-') . "\n"
            . "Status: {$action}\n"
            . "Diproses: " . date('Y-m-d H:i:s');

        wa_send_message($call, $whatsapp, $message);
    }

    header('Location: ../index?page=ProsesTopup&msg=15');
    exit();
}
?>
