<?php
header('Content-Type: application/json');
include "conn.php";

$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();

    // ✅ 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();
