<?php
// ============================================================
// FILE: ongkir.php — AJAX Endpoint Cek Ongkir (Binderbyte)
//
// GET  /ongkir.php?action=search&q=bekasi  → search lokasi
// GET  /ongkir.php?action=asal             → info kota asal + daftar kurir
// POST /ongkir.php (action=cek, origin_id, destination_id, berat, kurir) → ongkir
// ============================================================
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/rajaongkir.php';

header('Content-Type: application/json');
header('X-Content-Type-Options: nosniff');

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

// ── GET: search lokasi ────────────────────────────────────────
if ($action === 'search') {
    $q = trim($_GET['q'] ?? '');
    if (strlen($q) < 2) {
        echo json_encode(['success' => false, 'error' => 'Minimal 2 karakter.']);
        exit;
    }
    $data = bbSearchLocations($q);
    echo json_encode(['success' => !empty($data), 'data' => $data]);
    exit;
}

// ── POST: cek ongkir ──────────────────────────────────────────
if ($action === 'cek' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $originId     = trim($_POST['origin_id']      ?? KOTA_ASAL_ID);
    $destinId     = trim($_POST['destination_id'] ?? '');
    $berat        = (int)($_POST['berat']          ?? 0);
    $kurir        = strtolower(trim($_POST['kurir'] ?? 'jne'));

    if (!$destinId || !$berat) {
        echo json_encode(['success' => false, 'error' => 'destination_id dan berat wajib diisi.']);
        exit;
    }

    $kurirOk = array_keys(roGetKurirTersedia());
    if (!in_array($kurir, $kurirOk)) {
        echo json_encode(['success' => false, 'error' => "Kurir '$kurir' tidak tersedia."]);
        exit;
    }

    $result = roCekOngkir($originId, $destinId, $berat, $kurir);
    echo json_encode($result);
    exit;
}

// ── GET: info kota asal ───────────────────────────────────────
if ($action === 'asal') {
    echo json_encode([
        'success'      => true,
        'kota_id'      => KOTA_ASAL_ID,
        'kota_nama'    => KOTA_ASAL_NAMA,
        'kurir'        => roGetKurirTersedia(),
    ]);
    exit;
}

echo json_encode(['success' => false, 'error' => 'Action tidak dikenal.']);
