<?php
header('Content-Type: application/json');
include "conn.php";
include "_functions.php";
date_default_timezone_set("Asia/Kuala_Lumpur");
$debug_log = __DIR__ . "/debug_log.txt";


$invoice_no     = $_POST['invoice_no']   ?? null;
$pay_amount     = $_POST['pay_amount']   ?? null;
$pay_balance    = $_POST['pay_balance']  ?? null;
$transfer_date  = $_POST['transfer_date'] ?? date('Y-m-d');
$transfer_time  = $_POST['transfer_time'] ?? date('H:i:s');

if (!$invoice_no || $pay_amount === null) {
    echo json_encode([
        "status" => "error",
        "message" => "Missing required data."
    ]);
    exit;
}

try {
    // sanitize
    $invoice_no  = mysqli_real_escape_string($con, $invoice_no);
    $pay_amount  = floatval($pay_amount);
    $pay_balance = floatval($pay_balance);

    // Update invoice
    $stmt = $con->prepare("
        UPDATE invoice 
        SET payment_status = 'Paid',
            packaging_status = 'Processing',
            transfer_date = ?,
            transfer_time = ?,
            payment_sum = JSON_OBJECT(
                'pay_amount', ?,
                'pay_balance', ?
            )
        WHERE invoice_no = ?
    ");
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $con->error);
    }

    $stmt->bind_param("ssdds", 
        $transfer_date, 
        $transfer_time, 
        $pay_amount, 
        $pay_balance, 
        $invoice_no
    );

    if (!$stmt->execute()) {
        throw new Exception("Failed to update invoice: " . $stmt->error);
    }

    $stmt->close();

    processPaidOrder($invoice_no);

    // ✅ Return JSON for AJAX
    echo json_encode([
        "status" => "success",
        "invoice" => $invoice_no
    ]);
    exit();

} catch (Exception $e) {
    echo json_encode([
        "status" => "error",
        "message" => $e->getMessage()
    ]);
}
$con->close();
