<?php
// ics_proxy.php - Proxy untuk ICS Server (FINAL FIX REFF ID WAKTU)
// Mematikan display error agar tidak merusak format JSON response
ini_set('display_errors', 0);
date_default_timezone_set('Asia/Jakarta'); // Memastikan waktu selalu WIB
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Handle Preflight Request (OPTIONS)
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

// KONFIGURASI API ICS
$apiKey = "7274410f84b7e2810795810e879a4e0be8779c451d55e90e29d9bc174547ff77";
$baseUrl = "https://api.ics-store.my.id/api";

$action = $_GET['action'] ?? '';

/**
 * Fungsi Helper untuk Request ke API ICS
 */
function callAPI($method, $url, $data = null, $token) {
    $curl = curl_init();
    
    $headers = [
        "Authorization: Bearer $token",
        "Content-Type: application/json",
        "Accept: application/json"
    ];

    $options = [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => 0
    ];

    if ($data && ($method == 'POST' || $method == 'PUT')) {
        $options[CURLOPT_POSTFIELDS] = json_encode($data);
    }

    curl_setopt_array($curl, $options);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) {
        return json_encode([
            'success' => false, 
            'message' => "cURL Error: $err"
        ]);
    }
    
    return $response;
}

// --- LOGIKA UTAMA ---

if ($action == 'list') {
    echo callAPI('GET', "$baseUrl/reseller/products", null, $apiKey);
} 

elseif ($action == 'trx') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        echo json_encode(['success' => false, 'message' => 'Invalid JSON Input']);
        exit;
    }

    // --- GENERATE REFF ID BARU (ICS-TUJUAN-BULANJAMMENIT) ---
    $dest = $input['dest'] ?? '';
    // date('mHi') -> m: Bulan (01-12), H: Jam (00-23), i: Menit (00-59)
    $refid_baru = "ICS-" . $dest . "-" . date('mHi');

    $payload = [
        "product_code"  => $input['code'] ?? '',
        "dest_number"   => $dest,
        "ref_id_custom" => $refid_baru 
    ];

    if (empty($payload['product_code']) || empty($payload['dest_number'])) {
        echo json_encode(['success' => false, 'message' => 'Parameter code atau dest kosong']);
        exit;
    }

    echo callAPI('POST', "$baseUrl/reseller/trx", $payload, $apiKey);
} 

elseif ($action == 'profile') {
    echo callAPI('GET', "$baseUrl/reseller/profile", null, $apiKey);
}

elseif ($action == 'status') {
    $refid = $_GET['refid'] ?? '';
    if ($refid) {
        // Encode URL untuk memastikan ID tetap utuh saat diteruskan ke API Pusat
        $safeRefId = urlencode($refid);
        echo callAPI('GET', "$baseUrl/reseller/trx/$safeRefId", null, $apiKey);
    } else {
        echo json_encode(['success' => false, 'message' => 'RefID required']);
    }
}

else {
    echo json_encode(['success' => false, 'message' => 'Action invalid']);
}
?>