<?php
header('Content-Type: text/html; charset=utf-8');
ob_start();
require "conn.php"; // $con = mysqli_connect(...);
include "_functions.php";
date_default_timezone_set("Asia/Kuala_Lumpur");
$debug_log = __DIR__ . "/debug_log.txt";

try {
    $invoice_no    = $_POST['invoice_no'] ?? '';
    $transfer_date = $_POST['transfer_date'] ?? null;
    $transfer_time = $_POST['transfer_time'] ?? null;

    if (!$invoice_no) throw new Exception("Missing invoice number.");

    $con->begin_transaction();

    // 1. Get invoice data
    $stmt = $con->prepare("SELECT * FROM invoice WHERE invoice_no = ?");
    $stmt->bind_param("s", $invoice_no);
    $stmt->execute();
    $invoiceResult = $stmt->get_result();
    if (!$invoiceData = $invoiceResult->fetch_assoc()) {
        throw new Exception("Invoice not found.");
    }
    $stmt->close();

    // 2. Get username + customer detail from ahli
    $username = null;
    $stmt = $con->prepare("SELECT * 
                           FROM ahli WHERE id = ? OR username = ?");
    $stmt->bind_param("is", $invoiceData['customer_id'], $invoiceData['customer_id']);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($row = $res->fetch_assoc()) {
        $username = $row['username'];
        $customer_detail = [
            "nama"    => $row['nama'],
            "telefon" => $row['telefon'],
            "email"   => $row['email'],
            "alamat"  => $row['alamat'],
            "bandar"  => $row['bandar'],
            "poskod"  => $row['poskod'],
            "negeri"  => $row['negeri'],
            "negara"  => $row['negara']
        ];
    } else {
        $username = $invoiceData['customer_id']; // fallback
        $customer_detail = [];
    }
    $stmt->close();

    // 3. Update invoice table → mark as paid
    $stmt = $con->prepare("UPDATE invoice 
        SET payment_status = 'Paid', packaging_status = 'Processing', transfer_date = ?, transfer_time = ? 
        WHERE invoice_no = ?");
    $stmt->bind_param("sss", $transfer_date, $transfer_time, $invoice_no);
    if (!$stmt->execute()) throw new Exception("Failed to update invoice: " . $stmt->error);
    $stmt->close();

    // 4. Items JSON
    $items = $invoiceData['package_desc']; // copy directly



    // 5. Copy values from invoice table
    $receipt_no     = $invoice_no; // same as invoice
    $discount       = $invoiceData['discount'] ?? 0;
    $shipping       = $invoiceData['shipping_fee'] ?? 0;
    $tax            = $invoiceData['tax'] ?? 0;
    $grand_total    = $invoiceData['grand_total'] ?? 0;
    $payment_status = 'Paid';
    $payment_method = $invoiceData['payment_method'];

    // 5. Compute subtotal
    $subtotal = $invoiceData['grand_total'] 
              - $invoiceData['shipping_fee'] 
              - $invoiceData['tax'] 
              + $invoiceData['discount'];
 
    // 6. JSON fields
    $shipping_detail = json_encode([
        "name"     => $invoiceData['ship_name'],
        "address"  => $invoiceData['ship_address'],
        "postcode" => $invoiceData['ship_postcode'],
        "city"     => $invoiceData['ship_city'],
        "state"    => $invoiceData['ship_state'],
        "phone"    => $invoiceData['ship_phone'],
        "email"    => $invoiceData['ship_email']
    ]);

    $payment_detail = json_encode([
        "method"        => $invoiceData['payment_method'],
        "status"        => "PAID",
        "transfer_date" => $transfer_date,
        "transfer_time" => $transfer_time
    ]);

    $packaging_detail = json_encode([]);
    $customer_detail  = json_encode($customer_detail);

    // 7. Insert or Update sales
    $stmt = $con->prepare("SELECT id FROM sales WHERE invoice_no = ?");
    $stmt->bind_param("s", $invoice_no);
    $stmt->execute();
    $salesResult = $stmt->get_result();

    if ($row = $salesResult->fetch_assoc()) {
        // Update
        $stmt->close();
        $sql = "UPDATE sales SET 
            receipt_no=?, username=?, subtotal=?, discount=?, shipping=?, tax=?, grand_total=?, items=?, payment_status=?, payment_method=?, 
            customer_detail=?, shipping_detail=?, packaging_detail=?, payment_detail=? 
            WHERE invoice_no=?";
        $stmt = $con->prepare($sql);
        $stmt->bind_param(
            "ssddddsssssssss",
            $receipt_no,
            $username,
            $subtotal,
            $discount,
            $shipping,
            $tax,
            $grand_total,
            $items,
            $payment_status,
            $payment_method,
            $customer_detail,
            $shipping_detail,
            $packaging_detail,
            $payment_detail,
            $invoice_no
        );
        if (!$stmt->execute()) throw new Exception("Failed to update sales: " . $stmt->error);
    } else {
        // Insert
        $stmt->close();
        $sql = "INSERT INTO sales
            (invoice_no, receipt_no, username, subtotal, discount, shipping, tax, grand_total, items, payment_status, payment_method, 
            customer_detail, shipping_detail, packaging_detail, payment_detail) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $con->prepare($sql);
        $stmt->bind_param(
            "sssddddssssssss",
            $invoice_no,
            $receipt_no,
            $username,
            $subtotal,
            $discount,
            $shipping,
            $tax,
            $grand_total,
            $items,
            $payment_status,
            $payment_method,
            $customer_detail,
            $shipping_detail,
            $packaging_detail,
            $payment_detail
        );
        if (!$stmt->execute()) throw new Exception("Failed to insert sales: " . $stmt->error);
    }

    $stmt->close();
    
    processPaidOrder($invoice_no);

    $con->commit();
    ob_end_clean();

    // ✅ Redirect to pay_list.php after success
    header("Location: pay_list.php");
    exit();

} catch (Exception $e) {
    $con->rollback();
    $debug_output = ob_get_contents();
    ob_end_clean();
    if ($debug_output) file_put_contents($debug_log, $debug_output . "\n", FILE_APPEND);
    file_put_contents($debug_log, $e->getMessage() . "\n", FILE_APPEND);

    echo "<script>alert('Error: " . addslashes($e->getMessage()) . "');window.location='pay_list.php';</script>";
}
?>
