<?php
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()) exit('Bad request');

$id=(int)($_POST['order_id']??0);
$st=db()->prepare("SELECT * FROM orders WHERE id=?");
$st->execute([$id]);
$o=$st->fetch();

if(!$o) exit('Order tiada');

if (strpos($o['package_name'], 'DOWNSELL') !== false) {
    header('Location: thank_you.php?order='.$id);
    exit;
}

$price=(float)setting('DOWNSELL_PRICE','5.00');

$new_amount = (float)$o['amount'] + $price;
$new_package_name = $o['package_name'] . ' + DOWNSELL';

$update_st = db()->prepare("UPDATE orders SET amount = ?, package_name = ? WHERE id = ?");
$update_st->execute([$new_amount, $new_package_name, $id]);

if ($o['payment_method'] === 'ToyyibPay') {
    // BATALKAN BIL LAMA SECARA AUTOMATIK
    if(!empty($o['bill_code'])) {
        toyyibpay_inactive_bill($o['bill_code']);
    }

    // CIPTA BIL BARU DENGAN JUMLAH TERKINI
    $updatedOrderRow = [ 
        'id' => $id, 'name' => $o['name'], 'email' => $o['email'], 
        'phone' => $o['phone'], 'package_name' => $new_package_name, 'amount' => $new_amount 
    ];
    $bill = toyyibpay_create_bill($updatedOrderRow);

    if($bill['ok']){
        // KEMAS KINI REKOD DENGAN KOD BIL YANG BARU
        $up=db()->prepare("UPDATE orders SET bill_code=? WHERE id=?"); 
        $up->execute([$bill['bill_code'], $id]);
    }
}

header('Location: thank_you.php?order='.$id.'&downsell_success=1');
exit;