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

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

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

function bayarvip_callback_payload(): array
{
    $raw = file_get_contents('php://input');
    $decoded = json_decode((string)$raw, true);

    if (is_array($decoded)) {
        return $decoded;
    }

    return $_POST;
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
    bayarvip_json_response(200, [
        'success' => true,
        'message' => 'BayarVIP callback ready',
    ]);
}

$payload = bayarvip_callback_payload();

if (function_exists('wa_log')) {
    wa_log('bayarvip_callback_incoming', [
        'keys' => array_keys($payload),
        'transaction_id' => $payload['transaction_id'] ?? null,
        'status' => $payload['status'] ?? null,
        'provider_status' => $payload['provider_status'] ?? null,
    ]);
}

$transactionId = trim((string)($payload['transaction_id'] ?? ''));
$amount = (int)($payload['amount'] ?? 0);

if ($transactionId === '' || $amount <= 0) {
    bayarvip_json_response(400, [
        'success' => false,
        'message' => 'INVALID_PARAMETER',
    ]);
}

if (!bayarvip_verify_callback($call, $payload)) {
    bayarvip_json_response(403, [
        'success' => false,
        'message' => 'INVALID_SIGNATURE',
    ]);
}

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

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

if ((int)round((float)($topup['amount'] ?? 0)) !== $amount) {
    bayarvip_json_response(409, [
        'success' => false,
        'message' => 'AMOUNT_MISMATCH',
    ]);
}

$action = bayarvip_status_action($payload);

if ($action === null) {
    bayarvip_json_response(200, [
        'success' => true,
        'message' => 'PENDING_IGNORED',
    ]);
}

$result = topup_finalize_request($call, (int)$topup['id'], $action);

if (!$result['ok']) {
    bayarvip_json_response(500, [
        'success' => false,
        'message' => 'PROCESS_FAILED',
        'code' => $result['code'] ?? 'unknown',
    ]);
}

if (empty($result['already_processed'])) {
    $processedTopup = is_array($result['topup'] ?? null) ? $result['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: {$transactionId}\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);
}

bayarvip_json_response(200, [
    'success' => true,
    'message' => 'OK',
]);
