<?php
$apiKey = 'jMzHW8mT19778da42547e2c3cpVMAAwk'; 
require_once 'config.php';  

if (isset($_GET['kotatujuan']) && isset($_GET['kodecust'])) {
    $destination = $_GET['kotatujuan']; 
    $kodecust = $_GET['kodecust']; 
} else {
    echo "Error: Parameter kotatujuan dan kodecust diperlukan.";
    exit;
}

$no = isset($_GET['no']) ? (int)$_GET['no'] : 0;

$query = "SELECT ckodekecamatan as kotaasal FROM tbsetup LIMIT 1";  
$result = mysqli_query($conn, $query);

if ($result && mysqli_num_rows($result) > 0) {
    $row = mysqli_fetch_assoc($result);
    $origin = $row['kotaasal'];
} else {
    echo "Error: Tidak ada data kota asal ditemukan.";
    exit;
}

$query = "
    SELECT 
        SUM(((b.nberat * 1000) / b.nIsi) * k.nQty) AS total_berat
    FROM 
        tbkeranjang k
    JOIN 
        tbbarang b ON k.cKodeBrg = b.cKode
    WHERE 
        k.cKodeMember = '$kodecust'
";
$result = mysqli_query($conn, $query);

if ($result && mysqli_num_rows($result) > 0) { 
    $row = mysqli_fetch_assoc($result);
    $totalBerat = $row['total_berat'];
} else {
    $totalBerat = 0; 
}

if ($totalBerat == 0) {
    echo "Error: Total berat adalah 0. Tidak dapat melanjutkan proses.";
    exit; 
}

$query = "SELECT ckode, cnama FROM tbkurir where lstatus = '1'";
$result = mysqli_query($conn, $query);

if (!$result) {
    echo "Error: Query kurir gagal.";
    exit;
}

$url = "https://rajaongkir.komerce.id/api/v1/calculate/district/domestic-cost";
$allServiceData = [];
$no_urut = 1; 

while ($row = mysqli_fetch_assoc($result)) {
    $courier = $row['ckode'];

    $postData = http_build_query([
        'origin' => $origin, 
        'destination' => $destination,
        'weight' => $totalBerat,  
        'courier' => $courier
    ]);

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postData,
        CURLOPT_HTTPHEADER => [
            'Key: ' . $apiKey,
            'Content-Type: application/x-www-form-urlencoded'
        ],
    ]);

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        echo 'Error: ' . curl_error($ch);
    } else {
        $data = json_decode($response, true);

        if (isset($data['data']) && !empty($data['data'])) {
            foreach ($data['data'] as $serviceData) {
                $formattedCost = 'Rp ' . number_format($serviceData['cost'], 0, ',', '.');

                $allServiceData[] = [
                    'no' => $no_urut++,
                    'name' => $serviceData['name'],
                    'code' => $serviceData['code'],
                    'service' => $serviceData['service'],
                    'description' => $serviceData['description'],
                    'cost' => $formattedCost,
                    'etd' => $serviceData['etd']
                ];
            }
        }
    }

    curl_close($ch);
}

mysqli_close($conn);

if ($no > 0 && isset($allServiceData[$no - 1])) {
    echo json_encode([$allServiceData[$no - 1]], JSON_PRETTY_PRINT);
} else {
    echo json_encode($allServiceData, JSON_PRETTY_PRINT);
}
