<?php
// indopay_api.php
header('Content-Type: application/json');
date_default_timezone_set('Asia/Jakarta');

// === KONFIGURASI ===
$apiKey = "IPY-5VBZ9A56XFUR";
$apiUrl = "https://indo-pay.my.id/h2h/?apikey=" . $apiKey;

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

// Fungsi untuk mengambil data dari Indopay
function fetchIndopay() {
    global $apiUrl;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $output = curl_exec($ch);
    curl_close($ch);
    return json_decode($output, true);
}

if ($action == 'generate') {
    $base_nominal = isset($_GET['base_nominal']) ? (int)$_GET['base_nominal'] : 0;
    if ($base_nominal <= 0) {
        die(json_encode(['success' => false, 'message' => 'Nominal tidak valid']));
    }

    $history = fetchIndopay();
    $used_nominals = [];
    
    // Kumpulkan semua nominal yang sedang pending/tercatat di Indopay
    if (is_array($history)) {
        foreach ($history as $trx) {
            if (isset($trx['nominal'])) {
                $used_nominals[] = (int)$trx['nominal'];
            }
        }
    }

    $unik = 0;
    $max_attempts = 1000;
    $attempts = 0;
    
    // Generate nominal unik (tambah 1-999) dan pastikan tidak bertabrakan
    do {
        $random_code = rand(1, 999);
        $unik = $base_nominal + $random_code;
        $attempts++;
    } while (in_array($unik, $used_nominals) && $attempts < $max_attempts);

    if ($attempts >= $max_attempts) {
        echo json_encode(['success' => false, 'message' => 'Gagal mendapatkan nominal unik bersih']);
    } else {
        echo json_encode(['success' => true, 'unik_nominal' => $unik]);
    }
    exit;
}

if ($action == 'check') {
    $nominal_check = isset($_GET['nominal']) ? (int)$_GET['nominal'] : 0;
    $history = fetchIndopay();
    
    $status = 'pending';
    // Cek apakah nominal unik pengguna sudah masuk di riwayat Indopay
    if (is_array($history)) {
        foreach ($history as $trx) {
            if (isset($trx['nominal']) && (int)$trx['nominal'] == $nominal_check) {
                $status = 'success';
                break;
            }
        }
    }
    
    echo json_encode(['status' => $status]);
    exit;
}

echo json_encode(['success' => false, 'message' => 'Action tidak valid']);
?>