<?php
require_once __DIR__.'/inc/config.php';
require_once __DIR__.'/inc/db.php';
require_once __DIR__.'/inc/helpers.php';
require_once __DIR__.'/inc/http.php';

// Ambil data yang dihantar oleh ToyyibPay melalui POST
$billcode = $_POST['billcode'] ?? '';
$status = (string)($_POST['status'] ?? '');
$refno = $_POST['refno'] ?? '';
$amount = $_POST['amount'] ?? '';

// Henti jika tiada billcode
if(empty($billcode)){ 
  http_response_code(400); 
  exit('No billcode provided'); 
}

// Cari pesanan berdasarkan billcode
$st=db()->prepare("SELECT * FROM orders WHERE bill_code=? LIMIT 1");
$st->execute([$billcode]);
$o=$st->fetch();

if(!$o){ 
  http_response_code(404); 
  exit('Order not found for billcode: '.$billcode); 
}

// Jika bayaran berjaya (status = 1)
if($status === '1'){
  // Hanya kemas kini dan hantar notifikasi jika status masih 'Pending'
  if ($o['status'] === 'Pending') {
    // 1. Kemas kini status pesanan kepada 'Paid'
    $up=db()->prepare("UPDATE orders SET status='Paid' WHERE id=?");
    $up->execute([$o['id']]);

    // 2. Hantar Notifikasi WhatsApp (menggunakan templat umum)
    // Hantar kepada Pelanggan
    if (setting('WHATSAPP_NOTIF_CUSTOMER_ENABLED') == '1') {
        $customer_template = setting('WHATSAPP_NOTIF_CUSTOMER_TEMPLATE');
        $customer_message = str_replace(
            ['{nama}', '{id_pesanan}', '{jumlah}'],
            [$o['name'], $o['id'], money($o['amount'])],
            $customer_template
        );
        send_whatsapp($o['phone'], $customer_message);
    }
    // Hantar kepada Admin
    if (setting('WHATSAPP_NOTIF_ADMIN_ENABLED') == '1') {
        $admin_phone = setting('ADMIN_PHONE');
        if ($admin_phone) {
            $admin_template = setting('WHATSAPP_NOTIF_ADMIN_TEMPLATE');
            $admin_message = str_replace(
                ['{id_pesanan}', '{nama}', '{telefon}', '{pakej}', '{jumlah}', '{cara_bayaran}', '{alamat}'],
                [$o['id'], $o['name'], $o['phone'], $o['package_name'], money($o['amount']), $o['payment_method'], $o['address']],
                $admin_template
            );
            send_whatsapp($admin_phone, $admin_message);
        }
    }

    // 3. Kemas kini penggunaan kupon jika ada
    if(!empty($o['coupon_code'])){
      $cup=db()->prepare("UPDATE coupons SET used = used + 1 WHERE code=? AND active=1 AND (usage_limit IS NULL OR used < usage_limit)");
      $cup->execute([$o['coupon_code']]);
    }
  }
  echo 'OK';
} 
// Jika bayaran gagal (status = 3)
elseif($status === '3'){
  $up=db()->prepare("UPDATE orders SET status='Cancelled' WHERE id=?");
  $up->execute([$o['id']]);
  echo 'CANCELLED';
} 
// Status lain
else {
  echo 'PENDING/OTHER';
}