<?php
require_once __DIR__ . '/../include/db.php';

// ------------------------------
// VALIDATE REQUEST
// ------------------------------
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die("Invalid Request!");
}

if (!isset($_POST['id'])) {
    die("Order ID Missing!");
}

$order_id = intval($_POST['id']);

// ------------------------------
// RECEIVE ORDER FIELDS
// ------------------------------
$buyer_name  = $conn->real_escape_string($_POST['buyer_name']);
$style_no    = $conn->real_escape_string($_POST['style_no']);
$merchandiser = $conn->real_escape_string($_POST['merchandiser_name']);
$total_qty   = intval($_POST['total_qty']);
$remarks     = $conn->real_escape_string($_POST['remarks']);

// Measurements Arrays
$measureText = $_POST['measurement_text'];
$measureQty  = $_POST['measurement_qty'];

if (!is_array($measureText) || !is_array($measureQty)) {
    die("Measurements data missing!");
}

// ------------------------------
// UPDATE ORDERS TABLE
// ------------------------------
$sql = "UPDATE orders SET 
        buyer_name = ?, 
        style_no = ?, 
        merchandiser_name = ?, 
        total_qty = ?, 
        remarks = ?
        WHERE id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("sssisi", $buyer_name, $style_no, $merchandiser, $total_qty, $remarks, $order_id);

if (!$stmt->execute()) {
    die("Update Error: " . $stmt->error);
}

// ------------------------------
// DELETE OLD MEASUREMENTS
// ------------------------------
$conn->query("DELETE FROM order_measurements WHERE order_id = $order_id");

// ------------------------------
// INSERT NEW MEASUREMENTS
// ------------------------------
$insert = $conn->prepare("
    INSERT INTO order_measurements (order_id, measurement_text, total_qty) 
    VALUES (?, ?, ?)
");

foreach ($measureText as $i => $text) {

    $mText = trim($text);
    $mQty  = intval($measureQty[$i]);

    if ($mText === '' || $mQty <= 0) continue;

    $insert->bind_param("isi", $order_id, $mText, $mQty);
    $insert->execute();
}

// ------------------------------
// REDIRECT BACK TO VIEW PAGE
// ------------------------------
header("Location: view_order.php?id=" . $order_id);
exit;
?>
