<?php
/**
 * checkout.php - Backend Nadhief Herbal (Xendit Edition)
 * Versi: Final Update (Ongkir Dinamis & Notifikasi Lunas)
 */
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

$inputJSON = file_get_contents('php://input');
$request = json_decode($inputJSON, true);

if (!$request) {
    echo json_encode(['success' => false, 'message' => 'Data input tidak terbaca oleh server.']);
    exit;
}

// --- KONFIGURASI RAHASIA ---
$API_KEY_COCKPIT = 'API-df9da796f43d1241c36bcd39f85970223850134c';
$BASE_URL_COCKPIT = 'https://www.senatorabadi.web.id/ecommerce_herbal/admin';
$TELEGRAM_TOKEN = '8770697756:AAH8LDqchM9StZXoIy8noNHyWzEzdKlEXsQ';
$TELEGRAM_CHAT_ID = '-1003833945138';

// KUNCI XENDIT
$X_KEY = 'xnd_development_7Q4N2SM0ciucUsVqeESRwOOiVzAJQsiEKSK4qyLrzxcqL17hKiohMv3KL1vrgtk';

// --- AMBIL DATA DARI FRONTEND ---
$nama       = $request['nama'];
$wa         = $request['wa'];
$kota       = $request['kota'];
$alamat     = $request['alamat'];
$cart       = $request['cart'];
$ongkir     = (int)$request['ongkir'];
$kurir      = $request['kurir'] ?? 'J&T (Standard)';
$subtotal   = (int)$request['subtotal'];
$grandTotal = $subtotal + $ongkir;

$daftarBarangTeks = "";

// Fungsi Bantuan API cURL
function kirimRequest($url, $method, $data = null, $headers = ['Content-Type: application/json']) {
    $curl = curl_init();
    $options = [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_SSL_VERIFYPEER => false 
    ];
    if ($data) { $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 ['error' => $err];
    return json_decode($response, true);
}

try {
    // 1. BUAT INVOICE XENDIT
    $external_id = 'NADHIEF-' . time();
    $xendit_payload = [
        'external_id' => (string)$external_id,
        'amount'      => (int)$grandTotal,
        'description' => 'Pesanan Nadhief Herbal: ' . $nama,
        'customer'    => [
            'given_names'   => (string)$nama,
            'mobile_number' => (string)$wa
        ],
        'success_redirect_url' => 'https://www.senatorabadi.web.id/ecommerce_herbal/',
        'failure_redirect_url' => 'https://www.senatorabadi.web.id/ecommerce_herbal/'
    ];

    $xendit_headers = [
        'Content-Type: application/json',
        'Authorization: Basic ' . base64_encode($X_KEY . ':')
    ];

    $x_res = kirimRequest('https://api.xendit.co/v2/invoices', 'POST', $xendit_payload, $xendit_headers);

    if (!isset($x_res['invoice_url'])) {
        $msg = isset($x_res['message']) ? $x_res['message'] : 'Gagal terhubung ke Xendit';
        throw new Exception($msg);
    }

    $url_bayar = $x_res['invoice_url'];

    // 2. POTONG STOK DI COCKPIT & SUSUN TEKS BARANG
    foreach ($cart as $item) {
        $qty = (int)$item['qty'];
        $current = isset($item['stok']) ? (int)$item['stok'] : 0;
        $newStok = ($current - $qty < 0) ? 0 : $current - $qty;

        $upData = ['data' => ['_id' => $item['_id'], 'stok' => $newStok]];
        kirimRequest("$BASE_URL_COCKPIT/api/content/item/produk?api_key=$API_KEY_COCKPIT", 'POST', $upData);
        $daftarBarangTeks .= "- " . $item['nama_produk'] . " (" . $qty . "x)\n";
    }

    // 3. SIMPAN KE KOLEKSI PESANAN COCKPIT
    $catatan = $daftarBarangTeks . "\nKurir: " . $kurir . "\nOngkir: Rp " . number_format($ongkir, 0, ',', '.') . "\nAlamat: " . $alamat . " (" . $kota . ")\nInvoice: " . $url_bayar;
    $orderData = [
        'data' => [
            'nama_pembeli' => (string)$nama,
            'daftar_barang' => (string)$catatan,
            'total_harga'   => (int)$grandTotal,
            'tanggal'       => date('d/m/Y H:i:s')
        ]
    ];
    kirimRequest("$BASE_URL_COCKPIT/api/content/item/pesanan?api_key=$API_KEY_COCKPIT", 'POST', $orderData);

    // 4. NOTIFIKASI TELEGRAM (UPDATE KE LUNAS & RINCIAN LENGKAP)
    $pesanTele = "✅ *PESANAN MASUK (LUNAS)*\n" .
                 "━━━━━━━━━━━━━━━\n" .
                 "👤 *Nama:* $nama\n" .
                 "📱 *WhatsApp:* $wa\n" .
                 "🏠 *Alamat:* $alamat, $kota\n" .
                 "━━━━━━━━━━━━━━━\n" .
                 "*Rincian Barang:*\n$daftarBarangTeks\n" .
                 "🚚 *Ekspedisi:* $kurir\n" .
                 "💰 *Ongkos Kirim:* Rp " . number_format($ongkir, 0, ',', '.') . "\n" .
                 "💵 *Total Bayar:* Rp " . number_format($grandTotal, 0, ',', '.') . "\n" .
                 "━━━━━━━━━━━━━━━\n" .
                 "🔗 *Link Invoice:* [Klik di Sini]($url_bayar)\n\n" .
                 "🚀 _Status: LUNAS. Mohon segera diproses oleh Admin!_";

    kirimRequest("https://api.telegram.org/bot$TELEGRAM_TOKEN/sendMessage", 'POST', [
        'chat_id' => $TELEGRAM_CHAT_ID,
        'text' => $pesanTele,
        'parse_mode' => 'Markdown'
    ]);

    // KIRIM BALIK KE FRONTEND
    echo json_encode(['success' => true, 'invoice_url' => $url_bayar]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}