<?php
/**
 * callback.php - Versi Final (Urutan Teratur & Nominal Sinkron)
 */

$TELEGRAM_TOKEN = '8770697756:AAH8LDqchM9StZXoIy8noNHyWzEzdKlEXsQ';
$TELEGRAM_CHAT_ID = '-1003833945138';

$rawBody = file_get_contents("php://input");
$data = json_decode($rawBody, true);

if (!$data) {
    http_response_code(400);
    exit();
}

if (isset($data['status']) && ($data['status'] === 'PAID' || $data['status'] === 'SETTLED')) {
    
    // --- TAMBAHKAN JEDA 3 DETIK ---
    // Gunanya agar pesan dari checkout.php punya waktu untuk masuk duluan ke Telegram
    sleep(1); 

    $nama   = $data['customer_name'] ?? 'Pelanggan';
    $id     = $data['external_id'] ?? 'N/A';
    $total  = number_format($data['amount'], 0, ',', '.'); // Nominal otomatis dari Xendit
    $via    = $data['payment_method'] ?? 'Xendit';

    $pesanLunas = "✅ *PEMBAYARAN DITERIMA (LUNAS)*\n" .
                  "━━━━━━━━━━━━━━━\n" .
                  "👤 *Nama:* $nama\n" .
                  "🆔 *Order ID:* $id\n" .
                  "💰 *Total Lunas:* Rp $total\n" .
                  "💳 *Via:* $via\n" .
                  "━━━━━━━━━━━━━━━\n" .
                  "🚀 _Status: LUNAS. Silakan admin proses pengiriman!_";

    $urlTele = "https://api.telegram.org/bot$TELEGRAM_TOKEN/sendMessage";
    $payload = [
        'chat_id' => $TELEGRAM_CHAT_ID,
        'text' => $pesanLunas,
        'parse_mode' => 'Markdown'
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $urlTele);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    curl_close($ch);

    http_response_code(200);
    echo "OK";
}