<?php
date_default_timezone_set('Asia/Kuala_Lumpur');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

if($_SERVER['REQUEST_METHOD']!=='POST' || !csrf_verify()) { http_response_code(405); exit('Method Not Allowed'); }
if(!rate_limit('order',5)) { exit('Terlalu kerap.'); }

$name=trim($_POST['name']??''); 
$email=trim($_POST['email']??''); 
$phone=trim($_POST['phone']??''); 
$address=trim($_POST['address']??'');
$package_id=(int)($_POST['package_id']??0); 
$payment=$_POST['payment_method']??'ToyyibPay'; 
$order_bump=!empty($_POST['order_bump'])?1:0; 
$coupon=strtoupper(trim($_POST['coupon']??''));
$purchase_purpose = trim($_POST['purchase_purpose'] ?? 'Tidak Dinyatakan');
$ab_variant = $_COOKIE['ab'] ?? 'unknown';

if (empty($name) || empty($phone) || empty($address) || empty($package_id)) { exit('Maklumat wajib tidak lengkap.'); }
if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) { exit('Format emel tidak sah.'); }
$phone = preg_replace('/[^0-9\+]/', '', $phone);
if (strlen($phone) < 9) { exit('Format nombor telefon tidak sah.'); }



$st=db()->prepare("SELECT * FROM packages WHERE id=? AND active=1"); $st->execute([$package_id]); $pkg=$st->fetch();
if(!$pkg) exit('Pakej tidak sah.');

$bump=(float)setting('ORDER_BUMP_PRICE','5.00');
$amount=(float)$pkg['price'] + ($order_bump?$bump:0.0);
$discount=0.0;
if($coupon){ /* ... kod kupon sedia ada ... */ }

$cod_fee = 0.0;
if ($payment === 'COD') {
    $base_amount_for_cod = $amount;
    $percentage_fee = round($base_amount_for_cod * 0.04, 2);
    $cod_fee = max(7.00, $percentage_fee);
    $amount += $cod_fee;
}

$transaction_fee = 0.0;
if ($payment === 'ToyyibPay') {
    $transaction_fee = 1.00;
    $amount += $transaction_fee;
}

$status = 'Pending';
$utm=$_SESSION['utm']??[];
$now = date('Y-m-d H:i:s');

$ins=db()->prepare("INSERT INTO orders(created_at,name,email,phone,address,package_id,package_name,payment_method,amount,order_bump,order_bump_price,status,coupon_code,coupon_discount,utm_source,utm_medium,utm_campaign,utm_content,utm_term,affiliate,ref,cod_fee,transaction_fee,purchase_purpose, ab_variant) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
$ins->execute([$now,$name,$email,$phone,$address,$package_id,$pkg['name'],$payment,$amount,$order_bump,$bump,$status,$coupon,$discount,$utm['utm_source']??'',$utm['utm_medium']??'',$utm['utm_campaign']??'',$utm['utm_content']??'',$utm['utm_term']??'',$utm['aff']??'',$utm['ref']??'',$cod_fee,$transaction_fee,$purchase_purpose,$ab_variant]);$id=(int)db()->lastInsertId();
$_SESSION['order_id']=$id; $_SESSION['purchase_value']=$amount;

if($payment==='ToyyibPay'){
  $orderRow=[ 
      'id'=>$id, 
      'name'=>$name, 
      'email'=>$email, 
      'phone'=>$phone, 
      'package_name'=>$pkg['name'], 
      'amount'=>$amount 
  ];
  $bill = toyyibpay_create_bill($orderRow);

  if($bill['ok']){
    // Jika bil berjaya dicipta, simpan bill_code
    $up=db()->prepare("UPDATE orders SET bill_code=? WHERE id=?"); 
    $up->execute([$bill['bill_code'], $id]);

    // **INI BAHAGIAN PENTING:** Hantar pelanggan ke halaman terima kasih DAHULU
    header('Location: thank_you.php?order='.$id); 
    exit;

  } else {
    // Jika gagal cipta bil, hantar ke thank_you page sebagai fallback
    header('Location: thank_you.php?order='.$id.'&pay=manual'); 
    exit;
  }
} else {
  // Untuk bayaran COD dan Manual, hantar ke thank_you page
  header('Location: thank_you.php?order='.$id);
  exit;
}