<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

$step = isset($_POST['step']) ? intval($_POST['step']) : 0;

if ($step === 1) {
    // =========================
    // STEP 1: VERIFY INVOICE
    // =========================
    $invoice_no = mysqli_real_escape_string($con, $_POST['invoice_no'] ?? '');

    if (empty($invoice_no)) {
        echo json_encode(["success" => false, "message" => "Missing invoice number."]);
        exit;
    }

    $sql = "SELECT i.*, a.username AS customer 
            FROM invoice i 
            LEFT JOIN ahli a ON i.customer_id=a.id
            WHERE i.invoice_no='$invoice_no' AND i.shipping_method='courier'
            LIMIT 1";
    $res = mysqli_query($con, $sql);

    if (!$res || mysqli_num_rows($res) == 0) {
        echo json_encode(["success" => false, "message" => "Invoice not found."]);
        exit;
    }

    $row = mysqli_fetch_assoc($res);

    // Must be packed and waiting before shipping
    if ($row['packaging_status'] !== 'Packed' || $row['shipping_status'] !== 'Waiting') {
        echo json_encode([
            "success" => false,
            "message" => "Invoice not ready for shipping (must be Packed & Waiting)."
        ]);
        exit;
    }

    echo json_encode([
        "success" => true,
        "invoice_no" => $row['invoice_no'],
        "customer" => $row['customer'] ?? 'N/A'
    ]);
    exit;

} elseif ($step === 2) {
    // =========================
    // STEP 2: LINK TRACKING TAG + COURIER
    // =========================
    $invoice_no  = mysqli_real_escape_string($con, $_POST['invoice_no'] ?? '');
    $tracking_no = mysqli_real_escape_string($con, $_POST['tracking_no'] ?? '');
    $courier_id  = intval($_POST['courier_id'] ?? 0);

    if (empty($invoice_no) || empty($tracking_no) || $courier_id <= 0) {
        echo json_encode(["success" => false, "message" => "Missing invoice, tracking number, or courier."]);
        exit;
    }

    // Prevent duplicate tracking numbers
    $dup = mysqli_query($con, "SELECT invoice_no FROM invoice WHERE tracking_number='$tracking_no' AND shipping_method='courier' LIMIT 1");
    if ($dup && mysqli_num_rows($dup) > 0) {
        echo json_encode(["success" => false, "message" => "Duplicate tracking number found!"]);
        exit;
    }

    // Check invoice validity
    $check_sql = "SELECT i.*, a.username AS customer 
                  FROM invoice i 
                  LEFT JOIN ahli a ON i.customer_id=a.id
                  WHERE i.invoice_no='$invoice_no' 
                    AND i.packaging_status='Packed' 
                    AND i.shipping_status='Waiting'
                    AND i.shipping_method='courier'
                  LIMIT 1";
    $check = mysqli_query($con, $check_sql);

    if (!$check || mysqli_num_rows($check) == 0) {
        echo json_encode(["success" => false, "message" => "Invoice not valid or already shipped."]);
        exit;
    }

    $inv = mysqli_fetch_assoc($check);

    // Get courier info
    $courier_name = '';
    $courier_res = mysqli_query($con, "SELECT courier_name FROM courier WHERE id='$courier_id' LIMIT 1");
    if ($courier_res && mysqli_num_rows($courier_res) > 0) {
        $courier_row = mysqli_fetch_assoc($courier_res);
        $courier_name = $courier_row['courier_name'];
    }

    // Ensure it's a courier shipping method before updating
    if (strtolower($inv['shipping_method']) === 'courier') {
        // Update invoice - mark as shipped & in transit
        $update_sql = "
            UPDATE invoice 
            SET tracking_number ='$tracking_no', 
                courier_id      ='$courier_id',
                shipping_status ='Shipped', 
                delivery_status ='In Transit', 
                invoice_status  ='Completed',
                order_status    ='Completed',
                shipping_date   =NOW()
            WHERE invoice_no    ='$invoice_no'
        ";
    } else {
        echo json_encode(["success" => false, "message" => "Shipping method is not courier."]);
        exit;
    }

    if (mysqli_query($con, $update_sql)) {
        echo json_encode([
            "success" => true,
            "invoice_no" => $invoice_no,
            "tracking_no" => $tracking_no,
            "courier_name" => $courier_name,
            "customer" => $inv['customer'] ?? 'N/A',
            "packaging_status" => "Packed",
            "shipping_status" => "Shipped",
            "delivery_status" => "In Transit"
        ]);
    } else {
        echo json_encode(["success" => false, "message" => "Database update failed."]);
    }
    exit;

} else {
    echo json_encode(["success" => false, "message" => "Invalid step."]);
    exit;
}
?>
