<?php
// ============================================================
// FILE: includes/rajaongkir.php — Helper Binderbyte Ongkir API
// (nama file dipertahankan agar tidak perlu ubah require di file lain)
// ============================================================

/**
 * Hit Binderbyte API dengan cURL.
 */
function bbRequest(string $endpoint, array $postData = []): array {
    $isPost = !empty($postData);
    $url    = BINDERBYTE_BASE_URL . '/' . ltrim($endpoint, '/');

    // Tambahkan api_key ke postData atau query string
    if ($isPost) {
        $postData['api_key'] = BINDERBYTE_API_KEY;
    } else {
        $sep = str_contains($url, '?') ? '&' : '?';
        $url .= $sep . 'api_key=' . BINDERBYTE_API_KEY;
    }

    $ch = curl_init($url);
    $opts = [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_FOLLOWLOCATION => true,
    ];
    if ($isPost) {
        $opts[CURLOPT_POST]       = true;
        $opts[CURLOPT_POSTFIELDS] = http_build_query($postData);
        $opts[CURLOPT_HTTPHEADER] = ['content-type: application/x-www-form-urlencoded'];
    }
    curl_setopt_array($ch, $opts);

    $resp = curl_exec($ch);
    $err  = curl_error($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($err) return ['success' => false, 'data' => null, 'error' => 'cURL: ' . $err];

    $json = json_decode($resp, true);
    if (!$json || ($json['code'] ?? '') !== '200') {
        $msg = $json['message'] ?? $json['messages'] ?? 'Unknown error';
        return ['success' => false, 'data' => null, 'error' => $msg];
    }

    return ['success' => true, 'data' => $json['data'] ?? $json['value'] ?? [], 'error' => ''];
}

/**
 * Search lokasi (kota/kecamatan/kelurahan) untuk ongkir.
 * Dipakai di ongkir.php untuk dropdown.
 */
function bbSearchLocations(string $search): array {
    $r = bbRequest('v1/locations?search=' . urlencode($search));
    return $r['success'] ? ($r['data'] ?? []) : [];
}

/**
 * Cek ongkir.
 * @param string $originId      ID lokasi asal (format: city_32.75)
 * @param string $destinationId ID lokasi tujuan
 * @param int    $beratGram     Berat dalam gram
 * @param string $kurir         Kode kurir: jne | jnt | sicepat | tiki | pos dll
 * @return array ['success'=>bool, 'services'=>array, 'error'=>string]
 */
function roCekOngkir(string $originId, string $destinationId, int $beratGram, string $kurir = 'jne'): array {
    $r = bbRequest('v1/cost', [
        'origin'      => $originId,
        'destination' => $destinationId,
        'weight'      => max(1, $beratGram),
        'courier'     => strtolower($kurir),
    ]);

    if (!$r['success']) {
        return ['success' => false, 'services' => [], 'error' => $r['error']];
    }

    $services = [];
    $results  = $r['data']['results'] ?? [];

    foreach ($results as $ekspedisi) {
        $kurirNama = $ekspedisi['name'] ?? strtoupper($kurir);
        $kurirCode = $ekspedisi['code'] ?? $kurir;
        foreach ($ekspedisi['costs'] as $c) {
            $harga = (int)(($c['price'] ?? 0) / 100); // Binderbyte price dalam sen, bagi 100 → rupiah
            if ($harga <= 0) continue;
            $services[] = [
                'kurir'       => $kurirNama,
                'kurir_code'  => $kurirCode,
                'service'     => $c['service']   ?? '',
                'description' => $c['type']      ?? $c['name'] ?? '',
                'cost'        => $harga,
                'etd'         => $c['estimated'] ?? '?',
            ];
        }
    }

    return ['success' => true, 'services' => $services, 'error' => ''];
}

/**
 * Hitung total berat keranjang dalam gram.
 */
function hitungBeratKeranjang(array $items): int {
    $totalGram = 0;
    foreach ($items as $it) {
        $beratPerUnit = (float)($it['berat_per_m'] ?? 1.0);
        $jumlah       = (float)($it['jumlah'] ?? 1);
        $totalGram   += (int)round($beratPerUnit * $jumlah * 1000);
    }
    return max(1, $totalGram);
}

/**
 * Daftar kurir tersedia di Binderbyte.
 */
function roGetKurirTersedia(): array {
    return [
        'jne'      => 'JNE',
        'jnt'      => 'J&T Express',
        'sicepat'  => 'SiCepat',
        'tiki'     => 'TIKI',
        'pos'      => 'POS Indonesia',
        'anteraja' => 'AnterAja',
        'lion'     => 'Lion Parcel',
    ];
}

// Fungsi lama (tidak dipakai tapi dijaga agar tidak ada error)
function roGetProvinsi(): array { return []; }
function roGetKota(int $provinsiId = 0): array { return []; }
