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

$invoice_no = mysqli_real_escape_string($con, $_POST['invoice_no'] ?? '');

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

// 🔍 Fetch invoice details including shipping method and customer info
$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'
  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);

// 🧩 Extract needed values
$packaging_status = $row['packaging_status'];
$payment_status   = $row['payment_status'];
$shipping_method  = strtolower(trim($row['shipping_method']));
$customer         = $row['customer'];
$package_name     = $row['package_name'];

// ✅ Validate current status
if ($packaging_status === 'Packed') {
  echo json_encode(["success" => false, "message" => "Already packed!"]);
  exit;
}

if ($payment_status !== 'Paid') {
  echo json_encode(["success" => false, "message" => "Payment not cleared."]);
  exit;
}

// ✅ Proceed if currently Processing
if ($packaging_status === 'Processing') {

  if ($shipping_method === 'selfcollect') {
    // 🟢 SELF COLLECT — bypass shipping/delivery, mark completed
    $update = "
      UPDATE invoice 
      SET 
        packaging_status    = 'Packed',
        shipping_status     = 'Counter',
        delivery_status     = 'Handover',
        order_status        = 'Completed',
        invoice_status      = 'Completed'
      WHERE invoice_no      = '$invoice_no'
      LIMIT 1
    ";
    mysqli_query($con, $update);

    echo json_encode([
      "success"             => true,
      "message"             => "✅ Self-collect order marked as completed.",
      "invoice_no"          => $invoice_no,
      "customer"            => $customer,
      "package"             => $package_name,
      "packaging_status"    => "Packed",
      "order_status"        => "Completed",
      "shipping_method"     => $shipping_method
    ]);
    exit;

  } else {
    // 🚚 COURIER — move to shipping stage
    $update = "
      UPDATE invoice 
      SET 
        packaging_status    = 'Packed',
        shipping_status     = 'Waiting',
        delivery_status     = 'Pending',
        order_status        = 'Waiting'
      WHERE invoice_no      = '$invoice_no'
      LIMIT 1
    ";
    mysqli_query($con, $update);

    echo json_encode([
      "success"             => true,
      "message"             => "📦 Courier order ready for shipping.",
      "invoice_no"          => $invoice_no,
      "customer"            => $customer,
      "package"             => $package_name,
      "packaging_status"    => "Packed",
      "shipping_status"     => "Waiting",
      "delivery_status"     => "Pending",
      "order_status"        => "Waiting",
      "shipping_method"     => $shipping_method
    ]);
    exit;
  }
}

// 🧩 Fallback
echo json_encode(["success" => false, "message" => "Invalid or unexpected packaging status."]);
exit;
?>
