<?php
// FILE: data_pusat.php
// UPDATE: ID Link sama dengan akun lama, kode dibersihkan

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

// Sembunyikan error PHP di output agar JSON tetap valid
error_reporting(0);

// Tambah batas memori & waktu
ini_set('memory_limit', '512M');
set_time_limit(120);

// --- KONFIGURASI ID LINK ---
$id_link = "905ccd028329b0a"; // Menggunakan ID yang Anda konfirmasi
// --------------------------

$jenis = isset($_GET['jenis']) ? $_GET['jenis'] : '';
$cache_file = "cache_harga_masal.json";
$cache_time = 300; // Cache 5 Menit

function ambilData($url) {
    $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);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)');
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

if ($jenis == "semua") {
    // 1. Cek Cache (Jika ada dan masih < 5 menit, pakai cache)
    if (file_exists($cache_file) && (time() - filemtime($cache_file) < $cache_time)) {
        $cached = file_get_contents($cache_file);
        if (!empty($cached)) {
            echo $cached;
            exit;
        }
    }

    // 2. Ambil Data Baru
    $url_target = "https://okeconnect.com/harga/json?id=" . $id_link;
    $data_pusat = ambilData($url_target);
    
    // 3. Validasi & Simpan
    $json_test = json_decode($data_pusat);
    
    if ($data_pusat && strlen($data_pusat) > 100 && $json_test !== null) {
        // Simpan ke file cache
        @file_put_contents($cache_file, $data_pusat, LOCK_EX);
        echo $data_pusat;
    } else {
        // 4. Fallback ke Cache Lama (Jika server pusat gagal)
        if (file_exists($cache_file)) {
            echo file_get_contents($cache_file);
        } else {
            echo json_encode([
                "status" => "GAGAL", 
                "message" => "Gagal mengambil data harga. Cek koneksi atau ID Link."
            ]);
        }
    }
} else {
    // Ambil per produk (opsional)
    $url_target = "https://okeconnect.com/harga/json?id=" . $id_link . "&produk=" . urlencode($jenis);
    echo ambilData($url_target);
}
?>