<?php
// FILE: api.php
// LOGIKA: SAMA DENGAN FILE LAMA YANG NORMAL (api (2).php)
// UPDATE: Hanya ganti ke Akun Baru & Format ReffID REF-Tujuan-6Digit

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
error_reporting(0);

// --- 1. KONFIGURASI AKUN BARU ---
$memberID = "OK2829570";      
$password = "wasalamL050";      
$pin      = "0502";          

// --- 2. TERIMA DATA ---
$input = json_decode(file_get_contents("php://input"), true);
$tujuan = isset($input['tujuan']) ? $input['tujuan'] : '';
$kode_produk = isset($input['kode_produk']) ? $input['kode_produk'] : '';

// Validasi sederhana biar tidak error log kosong
if(empty($tujuan) || empty($kode_produk)) {
    echo json_encode(['status' => 'GAGAL', 'message' => 'Data tidak lengkap']);
    exit;
}

// Buat RefID Unik (REF-no tujuan-6 digit angka random)
$refID = "REF-" . $tujuan . "-" . rand(100000, 999999);

// --- 3. SUSUN URL (Logic Lama) ---
$url = "https://h2h.okeconnect.com/trx?product=" . urlencode($kode_produk) . 
       "&dest=" . urlencode($tujuan) . 
       "&refID=" . $refID . 
       "&memberID=" . $memberID . 
       "&pin=" . $pin . 
       "&password=" . $password;

if (isset($input['qty']) && !empty($input['qty'])) {
    $url .= "&qty=" . urlencode($input['qty']);
}

// --- 4. EKSEKUSI KE SERVER PUSAT ---
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$response_text = curl_exec($ch);
curl_close($ch);

// Jika respon kosong
if (empty($response_text)) {
    $response_text = "Gagal: Tidak ada respon dari server pusat.";
}

// --- 5. LOGGING (Sesuai file lama) ---
$waktu = date("Y-m-d H:i:s");
$log_msg = "[$waktu] Req: $kode_produk|$tujuan -> Respon: $response_text\n";
@file_put_contents('debug_api_keluar.txt', $log_msg, FILE_APPEND);

// --- 6. LOGIKA STATUS ---
$status = "PENDING"; 
$pesan = $response_text; 

if (stripos($response_text, 'GAGAL') !== false || stripos($response_text, 'Salah') !== false) {
    $status = "GAGAL";
} 
elseif (stripos($response_text, 'SUKSES') !== false || stripos($response_text, 'SN:') !== false || stripos($response_text, 'SN :') !== false) {
    $status = "BERHASIL"; 
}

// --- 7. OUTPUT JSON ---
echo json_encode([
    'status' => $status,
    'message' => $pesan,
    'refID' => $refID,
    'raw_response' => $response_text
]);
?>