<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');

// Terima request nominal dari frontend
$input = json_decode(file_get_contents('php://input'), true);
$base_nominal = isset($input['nominal']) ? (int)$input['nominal'] : 0;

if ($base_nominal < 1000) {
    echo json_encode(['status' => 'error', 'message' => 'Nominal minimal Rp 1.000']);
    exit;
}

// Konfigurasi Qiospay
$merchant_code = 'QP036963';
$api_key = '812feff6d5e883a1b0bb860bb2af215b5cbde41d937ba0e0814edb88334dd5df';
$url = "https://qiospay.id/api/mutasi/qris/{$merchant_code}/{$api_key}";

// Tarik data mutasi terbaru
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);

$mutasi_data = json_decode($response, true);
$used_amounts = [];

// Kumpulkan semua nominal yang sudah terpakai (uang masuk / CR)
if (isset($mutasi_data['status']) && $mutasi_data['status'] === 'success' && isset($mutasi_data['data'])) {
    foreach ($mutasi_data['data'] as $trx) {
        if ($trx['type'] === 'CR') {
            $used_amounts[] = (int)$trx['amount'];
        }
    }
}

// Proses pengacakan dan validasi (maksimal 100 kali percobaan)
$is_unique = false;
$attempts = 0;
$kode_unik = 0;
$nominal_unik = 0;

while (!$is_unique && $attempts < 100) {
    $kode_unik = rand(1, 399);
    $nominal_unik = $base_nominal + $kode_unik;

    // Jika nominal unik BELUM ADA di mutasi, hentikan pencarian
    if (!in_array($nominal_unik, $used_amounts)) {
        $is_unique = true;
    }
    $attempts++;
}

// Jika gagal menemukan nominal unik
if (!$is_unique) {
    echo json_encode(['status' => 'error', 'message' => 'Sistem sibuk, gagal membuat nominal unik. Coba beberapa saat lagi.']);
    exit;
}

// Kembalikan nominal yang sudah tervalidasi ke frontend
echo json_encode([
    'status' => 'success',
    'nominal_dasar' => $base_nominal,
    'kode_unik' => $kode_unik,
    'nominal_unik' => $nominal_unik
]);
?>