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

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

function bayarvip_status_response(int $statusCode, array $payload): void
{
    http_response_code($statusCode);
    echo json_encode($payload, JSON_UNESCAPED_SLASHES);
    exit();
}

if (!isset($_SESSION['admin'])) {
    bayarvip_status_response(403, [
        'ok' => false,
        'message' => 'FORBIDDEN',
    ]);
}

$trxid = trim((string)($_GET['trxid'] ?? ''));

if ($trxid === '') {
    bayarvip_status_response(400, [
        'ok' => false,
        'message' => 'TRXID_REQUIRED',
    ]);
}

$topup = topup_find_by_trxid($call, $trxid);

if ($topup === null) {
    bayarvip_status_response(404, [
        'ok' => false,
        'message' => 'TRANSACTION_NOT_FOUND',
    ]);
}

$currentAgent = $_SESSION['admin'] ?? [];
$currentLevel = (string)($currentAgent['agent_level'] ?? '');
$currentAgentRefs = agent_identity_values((array)$currentAgent);

if ($currentLevel !== 'admin' && !in_array((string)($topup['agent_code'] ?? ''), $currentAgentRefs, true)) {
    bayarvip_status_response(403, [
        'ok' => false,
        'message' => 'FORBIDDEN',
    ]);
}

if (!topup_is_qris_method((string)($topup['metode'] ?? ''))) {
    bayarvip_status_response(200, [
        'ok' => true,
        'status' => (string)($topup['status'] ?? ''),
        'message' => 'NOT_QRIS',
    ]);
}

$providerStatus = null;
$providerStatusText = null;

if (($topup['status'] ?? '') === 'Pending') {
    $statusResult = bayarvip_get_status($call, $trxid);

    if (!$statusResult['ok']) {
        bayarvip_status_response(502, [
            'ok' => false,
            'status' => (string)($topup['status'] ?? ''),
            'message' => (string)($statusResult['message'] ?? 'BAYARVIP_STATUS_FAILED'),
            'code' => (string)($statusResult['code'] ?? 'bayarvip_failed'),
        ]);
    }

    $data = is_array($statusResult['data'] ?? null) ? $statusResult['data'] : [];
    $providerStatus = $data['status'] ?? null;
    $providerStatusText = $data['status_text'] ?? ($data['local_status'] ?? null);
    $action = bayarvip_status_action($data);

    if ($action !== null && (int)round((float)($topup['amount'] ?? 0)) === (int)($data['amount'] ?? 0)) {
        $finalizeResult = topup_finalize_request($call, (int)$topup['id'], $action);

        if (!$finalizeResult['ok']) {
            bayarvip_status_response(500, [
                'ok' => false,
                'status' => (string)($topup['status'] ?? ''),
                'message' => 'PROCESS_FAILED',
                'code' => (string)($finalizeResult['code'] ?? 'unknown'),
            ]);
        }

        if (empty($finalizeResult['already_processed'])) {
            $processedTopup = is_array($finalizeResult['topup'] ?? null) ? $finalizeResult['topup'] : $topup;
            $agentCode = (string)($processedTopup['agent_code'] ?? '');
            $agentName = topup_agent_name($call, $agentCode);
            $whatsapp = trim((string)($processedTopup['whatsapp'] ?? ''));
            $currencyPrice = number_format((float)($processedTopup['amount'] ?? 0), 0, ',', '.');
            $coinAmount = number_format((float)($processedTopup['balance'] ?? 0), 0, ',', '.');
            $statusLabel = $action === 'Success' ? 'BERHASIL' : 'DIBATALKAN';
            $message = "Update topup QRIS {$statusLabel}\n"
                . "TrxID: {$trxid}\n"
                . "Agent: {$agentName}\n"
                . "Nominal: Rp {$currencyPrice}\n"
                . "Coin: {$coinAmount}\n"
                . "Status: {$action}\n"
                . "Diproses otomatis: " . date('Y-m-d H:i:s');

            if ($whatsapp !== '' && $whatsapp !== '0') {
                wa_send_message($call, $whatsapp, $message);
            }

            wa_send_admin_alert($call, $message);
        }

        $topup = topup_find_by_trxid($call, $trxid) ?: $topup;
    }
}

bayarvip_status_response(200, [
    'ok' => true,
    'trxid' => $trxid,
    'status' => (string)($topup['status'] ?? ''),
    'provider_status' => $providerStatus,
    'provider_status_text' => $providerStatusText,
    'qr_url' => bayarvip_qr_url($call, $trxid),
]);
