<?php
session_start();
date_default_timezone_set("Asia/Jakarta");
include('../config/koneksi.php');

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

// Function untuk response JSON
function jsonResponse($success, $status, $message = '', $data = null) {
    echo json_encode([
        'success' => $success,
        'status' => $status,
        'message' => $message,
        'data' => $data,
        'timestamp' => date('Y-m-d H:i:s')
    ], JSON_PRETTY_PRINT);
    exit;
}

$trx_id = isset($_GET['trx_id']) ? trim($_GET['trx_id']) : '';

if (empty($trx_id)) {
    jsonResponse(false, 'error', 'Transaction ID tidak ditemukan', null);
}

$trx_id_escaped = mysqli_real_escape_string($conn, $trx_id);

// Cek status langsung dari database (lebih cepat dan reliable)
$sqlTrx = mysqli_query($conn, "SELECT userID, status, kd_transaksi FROM tb_transaksi WHERE note LIKE '%$trx_id_escaped%' AND jenis = 1 LIMIT 1");
$trxData = mysqli_fetch_assoc($sqlTrx);

if (!$trxData) {
    jsonResponse(false, 'error', 'Transaksi tidak ditemukan', null);
}

// Jika status sudah 1 (success), langsung return success
if ($trxData['status'] == 1) {
    jsonResponse(true, 'success', 'Pembayaran sudah diproses', [
        'kd_transaksi' => $trxData['kd_transaksi'],
        'status' => 'success'
    ]);
}

// Jika masih pending, cek via API untuk memastikan
// Ambil merchant UUID dari config
$configQuery = mysqli_query($conn, "SELECT qris_uuid, qris_uuid2 FROM tb_seo WHERE cuid = 1 LIMIT 1");
$config = mysqli_fetch_assoc($configQuery);

$merchantUUID = $config['qris_uuid'] ?? '';

// Check status via API otomatis.vip (optional, untuk double check)
if (!empty($merchantUUID)) {
    $postArray = [
        'uuid' => $merchantUUID,
        'client' => 'client'
    ];

    $jsonData = json_encode($postArray);
    $headerArray = ['Content-Type: application/json'];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://rest.otomatis.vip/api/checkstatus/v2/' . urlencode($trx_id));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode === 200) {
        $apiResponse = json_decode($response, true);
        if ($apiResponse && isset($apiResponse['status']) && $apiResponse['status'] === 'success') {
            // Jika API bilang success tapi DB masih pending, berarti callback belum diproses
            jsonResponse(true, 'pending', 'Menunggu callback dari server', $apiResponse);
        }
    }
}

// Default: masih pending
jsonResponse(true, 'pending', 'Menunggu pembayaran', [
    'kd_transaksi' => $trxData['kd_transaksi'],
    'status' => 'pending'
]);
?>
