<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once("../php/db_connect.php");

if (!isset($_SESSION["user_id"])) {
    echo "<script>window.location='index.php';</script>";
    exit();
}

$shop_id = (int)$_SESSION["user_id"];

function h($value) {
    return htmlspecialchars($value ?? "", ENT_QUOTES, "UTF-8");
}

function statusBadge($status) {
    $status = strtolower($status ?? "");

    if ($status === "pending") return "bg-warning-subtle text-warning-emphasis";
    if ($status === "accepted") return "bg-info-subtle text-info";
    if ($status === "in_progress") return "bg-primary-subtle text-primary";
    if ($status === "completed") return "bg-success-subtle text-success";
    if ($status === "cancelled") return "bg-danger-subtle text-danger";
    if ($status === "outsourced") return "bg-info-subtle text-info";

    return "bg-secondary-subtle text-secondary";
}

function paymentBadge($status) {
    $status = strtolower($status ?? "");

    if ($status === "paid") return "bg-success-subtle text-success";
    if ($status === "partial") return "bg-warning-subtle text-warning-emphasis";
    if ($status === "unpaid") return "bg-danger-subtle text-danger";

    return "bg-secondary-subtle text-secondary";
}

function formatDateOnly($date) {
    if (empty($date) || $date === "0000-00-00") {
        return "N/A";
    }

    return date("M d, Y", strtotime($date));
}

/* =========================
   LOAD ACTIVE ORDERS
========================= */
$stmt = $conn->prepare("
    SELECT 
        o.*,
        oi.service_type AS oi_service_type,
        oi.sub_type AS oi_sub_type,
        oi.size AS oi_size,
        oi.quantity AS oi_quantity
    FROM orders o
    LEFT JOIN order_items oi
        ON oi.id = (
            SELECT oi2.id
            FROM order_items oi2
            WHERE oi2.order_id = o.id
            ORDER BY oi2.id ASC
            LIMIT 1
        )
    WHERE o.shop_id = ?
    AND o.status NOT IN ('completed', 'outsourced', 'cancelled')
    AND NOT EXISTS (
        SELECT 1
        FROM outsourced_jobs j
        WHERE j.order_id = o.id
    )
    ORDER BY o.created_at DESC
");
$stmt->bind_param("i", $shop_id);
$stmt->execute();
$orders = $stmt->get_result();

/* =========================
   LOAD COMPLETED ORDERS
========================= */
$stmt2 = $conn->prepare("
    SELECT 
        o.*,
        oi.service_type AS oi_service_type,
        oi.sub_type AS oi_sub_type,
        oi.size AS oi_size,
        oi.quantity AS oi_quantity
    FROM orders o
    LEFT JOIN order_items oi
        ON oi.id = (
            SELECT oi2.id
            FROM order_items oi2
            WHERE oi2.order_id = o.id
            ORDER BY oi2.id ASC
            LIMIT 1
        )
    WHERE o.shop_id = ? 
    AND o.status = 'completed'
    ORDER BY o.created_at DESC
");
$stmt2->bind_param("i", $shop_id);
$stmt2->execute();
$previousOrders = $stmt2->get_result();

/* =========================
   LOAD SERVICE TYPES
========================= */
$typeStmt = $conn->prepare("
    SELECT type_name
    FROM service_type_options
    WHERE owner_shop_id = ? 
    AND status = 'active'
    ORDER BY type_name ASC
");
$typeStmt->bind_param("i", $shop_id);
$typeStmt->execute();
$serviceTypes = $typeStmt->get_result();

/* =========================
   LOAD ACTIVE SERVICES + VARIANTS
   This connects order form to your service sizes/prices.
========================= */
$subtypeSet = [];
$variantMap = [];

$serviceStmt = $conn->prepare("
    SELECT 
        s.id,
        s.service_type,
        s.service_name,
        s.size AS base_size,
        s.price AS base_price,
        v.size AS variant_size,
        v.price AS variant_price
    FROM services s
    LEFT JOIN service_variants v
        ON s.id = v.service_id
        AND v.is_available = 1
    WHERE s.owner_shop_id = ?
    AND s.status = 'active'
    ORDER BY s.service_type ASC, s.service_name ASC
");
$serviceStmt->bind_param("i", $shop_id);
$serviceStmt->execute();
$serviceResult = $serviceStmt->get_result();

while ($row = $serviceResult->fetch_assoc()) {
    $type = trim($row["service_type"] ?? "");
    $name = trim($row["service_name"] ?? "");

    if ($type === "" || $name === "") {
        continue;
    }

    if (!isset($subtypeSet[$type])) {
        $subtypeSet[$type] = [];
    }

    $subtypeSet[$type][$name] = true;

    if (!isset($variantMap[$type])) {
        $variantMap[$type] = [];
    }

    if (!isset($variantMap[$type][$name])) {
        $variantMap[$type][$name] = [];
    }

    if (!empty($row["variant_size"])) {
        $variantMap[$type][$name][] = [
            "size" => $row["variant_size"],
            "price" => number_format((float)$row["variant_price"], 2, ".", "")
        ];
    } elseif (!empty($row["base_price"])) {
        $variantMap[$type][$name][] = [
            "size" => !empty($row["base_size"]) ? $row["base_size"] : "Standard",
            "price" => number_format((float)$row["base_price"], 2, ".", "")
        ];
    }
}

$subtypeMap = [];

foreach ($subtypeSet as $type => $names) {
    $subtypeMap[$type] = array_keys($names);
}

/* =========================
   CREATE FINAL ORDER
========================= */
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["create_final_order"])) {
    $customer_name = trim($_POST["customer_name"] ?? "");
    $customer_email = trim($_POST["customer_email"] ?? "");
    $customer_mobile = trim($_POST["customer_mobile"] ?? "");
    $due_date = trim($_POST["due_date"] ?? "");
    $estimated_delivery = trim($_POST["estimated_delivery"] ?? "");
    $payment_status = trim($_POST["payment_status"] ?? "unpaid");
    $notes = trim($_POST["notes"] ?? "");
    $items = json_decode($_POST["order_items_json"] ?? "[]", true);

    if ($customer_name === "" || $customer_mobile === "") {
        echo "<script>alert('Customer name and contact number are required.'); window.history.back();</script>";
        exit;
    }

    if (empty($items)) {
        echo "<script>alert('Please add at least one order item.'); window.history.back();</script>";
        exit;
    }

    $design_file = null;

    if (!empty($_FILES["design_file"]["name"])) {
        $upload_dir = "../uploads/orders/";

        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }

        $file_name = $_FILES["design_file"]["name"];
        $file_tmp = $_FILES["design_file"]["tmp_name"];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        $allowed = ["jpg", "jpeg", "png", "pdf", "doc", "docx"];

        if (!in_array($file_ext, $allowed)) {
            echo "<script>alert('Invalid file type.'); window.history.back();</script>";
            exit;
        }

        $design_file = "order_" . $shop_id . "_" . time() . "." . $file_ext;
        $target = $upload_dir . $design_file;

        if (!move_uploaded_file($file_tmp, $target)) {
            echo "<script>alert('Design file upload failed.'); window.history.back();</script>";
            exit;
        }
    }

    $customer_id = null;

    if (!empty($customer_email) || !empty($customer_mobile)) {
        $findCustomer = $conn->prepare("
            SELECT id
            FROM users
            WHERE email = ? OR mobile_number = ?
            LIMIT 1
        ");
        $findCustomer->bind_param("ss", $customer_email, $customer_mobile);
        $findCustomer->execute();
        $customerResult = $findCustomer->get_result();

        if ($customerRow = $customerResult->fetch_assoc()) {
            $customer_id = (int)$customerRow["id"];
        }
    }

    $order_code = "ORD-" . rand(100000000, 999999999);
    $order_date = date("Y-m-d");
    $status = "pending";

    $total_quantity = 0;
    $unique_types = [];
    $item_count = count($items);

    foreach ($items as $item) {
        $total_quantity += (int)($item["quantity"] ?? 0);

        $stype = trim($item["service_type"] ?? "");
        if ($stype !== "") {
            $unique_types[$stype] = true;
        }
    }

    $service_type_for_order = count($unique_types) === 1
        ? array_key_first($unique_types)
        : "Multiple Services";

    $item_name_for_order = $item_count > 1
        ? $item_count . " items"
        : trim($items[0]["service_name"] ?? "N/A");

    $size_for_order = $item_count === 1
        ? trim($items[0]["size"] ?? "")
        : "See details";

    $insertOrder = $conn->prepare("
        INSERT INTO orders (
            order_code,
            customer_id,
            shop_id,
            service_type,
            item_name,
            customer_name,
            customer_email,
            customer_mobile,
            quantity,
            size,
            order_date,
            due_date,
            estimated_delivery,
            status,
            payment_status,
            notes,
            design_file
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    if (!$insertOrder) {
        die("Prepare failed: " . $conn->error);
    }

    $insertOrder->bind_param(
        "siisssssissssssss",
        $order_code,
        $customer_id,
        $shop_id,
        $service_type_for_order,
        $item_name_for_order,
        $customer_name,
        $customer_email,
        $customer_mobile,
        $total_quantity,
        $size_for_order,
        $order_date,
        $due_date,
        $estimated_delivery,
        $status,
        $payment_status,
        $notes,
        $design_file
    );

    if (!$insertOrder->execute()) {
        die("Execute failed: " . $insertOrder->error);
    }

    $order_id = $insertOrder->insert_id;

    foreach ($items as $item) {
        $stmtItem = $conn->prepare("
            INSERT INTO order_items (
                order_id, 
                service_type, 
                sub_type, 
                quantity, 
                size
            ) VALUES (?, ?, ?, ?, ?)
        ");

        $service_type = trim($item["service_type"] ?? "");
        $service_name = trim($item["service_name"] ?? "");
        $quantity = (int)($item["quantity"] ?? 0);
        $size = trim($item["size"] ?? "");

        $stmtItem->bind_param(
            "issis",
            $order_id,
            $service_type,
            $service_name,
            $quantity,
            $size
        );

        $stmtItem->execute();
    }

    echo "<script>window.location='admin.php?page=orders&message=created';</script>";
    exit;
}

function order_display_values(array $row): array
{
    $serviceType = trim($row["service_type"] ?? "");
    if ($serviceType === "") {
        $serviceType = trim($row["oi_service_type"] ?? "");
    }

    $subType = trim($row["oi_sub_type"] ?? "");
    $itemName = trim($row["item_name"] ?? "");

    if ($itemName === "" && $subType !== "") {
        $itemName = $subType;
    }

    $quantity = (int)($row["quantity"] ?? 0);
    if ($quantity <= 0) {
        $quantity = (int)($row["oi_quantity"] ?? 0);
    }

    $size = trim($row["size"] ?? "");
    if ($size === "") {
        $size = trim($row["oi_size"] ?? "");
    }

    return [
        "service_type" => $serviceType !== "" ? $serviceType : "N/A",
        "item_name" => $itemName !== "" ? $itemName : "N/A",
        "quantity" => $quantity > 0 ? $quantity : 0,
        "size" => $size !== "" ? $size : "N/A",
        "due_date" => formatDateOnly($row["due_date"] ?? "")
    ];
}

$message = $_GET["message"] ?? "";
?>
<div class="modal fade" id="orderSuccessModal" tabindex="-1" aria-labelledby="orderSuccessModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content border-0 rounded-4 shadow">
      <div class="modal-body text-center py-4">
        <div class="mb-3">
          <i class="fa-solid fa-circle-check fa-3x text-success"></i>
        </div>
        <h5 class="fw-bold mb-1" id="successModalTitle">Order Created!</h5>
<p class="mb-0" id="successModalText">Order has been successfully created.</p>
        <button type="button" class="btn btn-success mt-3" data-bs-dismiss="modal">OK</button>
      </div>
    </div>
  </div>
</div>


<div class="container-fluid px-4 py-4 order-page">

    <div class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-4">
        <div>
            <h1 class="fw-bold mb-1">Order Management</h1>
            <p class="text-muted mb-0">Create, monitor, update, and outsource customer orders.</p>
        </div>
    </div>

<?php if ($message === "created"): ?>
<script>
document.addEventListener("DOMContentLoaded", function () {
    var successModal = new bootstrap.Modal(document.getElementById('orderSuccessModal'));
    successModal.show();

    // Auto-close after 3 seconds (3000ms)
    setTimeout(function() {
        successModal.hide();
    }, 3000);
});
</script>
<?php endif; ?>

<?php if (isset($_GET['update']) && $_GET['update'] === 'success'): ?>
<script>
document.addEventListener("DOMContentLoaded", function () {
    var successModal = new bootstrap.Modal(document.getElementById('orderSuccessModal'));
    
    // Update the modal text
    document.getElementById('successModalTitle').textContent = "Order Updated!";
    document.getElementById('successModalText').textContent = "Order status updated successfully.";
    
    successModal.show();

    // Auto-close after 3 seconds
    setTimeout(function() {
        successModal.hide();
    }, 3000);
});
</script>
<?php endif; ?>



    <div class="row g-4 align-items-start">

        <!-- LEFT SIDE: CREATE ORDER -->
        <div class="col-xl-4 col-lg-5">

            <form method="POST" enctype="multipart/form-data" id="createOrderForm">

                <div class="card border-0 shadow-sm rounded-4 mb-4">
                    <div class="card-header bg-white border-0 px-4 pt-4 pb-2">
                        <h4 class="fw-bold mb-1">Create Order</h4>
                        <p class="text-muted small mb-0">Enter customer details and add one or more items.</p>
                    </div>

                    <div class="card-body px-4 pb-4">

                        <div class="mb-3">
                            <label class="form-label fw-semibold">Customer Full Name</label>
                            <input type="text" name="customer_name" class="form-control" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-semibold">Email</label>
                            <input type="email" name="customer_email" class="form-control">
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-semibold">Contact Number</label>
                            <input type="text" name="customer_mobile" class="form-control" required>
                        </div>

                        <hr>

                        <div class="mb-3">
                            <label class="form-label fw-semibold">Service Type</label>
                            <select name="service_type" id="service_type" class="form-select">
                                <option value="">Select Service Type</option>
                                <?php while ($type = $serviceTypes->fetch_assoc()): ?>
                                    <option value="<?php echo h($type["type_name"]); ?>">
                                        <?php echo h($type["type_name"]); ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-semibold">Sub Type</label>
                            <select name="item_name" id="item_name" class="form-select">
                                <option value="">Select Sub Type</option>
                            </select>
                        </div>

                        <div class="mb-3" id="size-group" style="display:none;">
                            <label class="form-label fw-semibold" id="size-label">Size / Option</label>
                            <div class="size-options" id="size-options"></div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-semibold">Quantity</label>
                            <input type="number" name="quantity" class="form-control" min="1" value="1">
                        </div>

                       

                        <hr>

                        <div class="mb-3">
                            <label class="form-label fw-semibold">Due Date</label>
                            <input type="date" name="due_date" class="form-control" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-semibold">Estimated Delivery</label>
                            <input type="date" name="estimated_delivery" class="form-control">
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-semibold">Payment Status</label>
                            <select name="payment_status" class="form-select">
                                <option value="unpaid">Unpaid</option>
                                <option value="partial">Partial</option>
                                <option value="paid">Paid</option>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-semibold">Design / Reference File</label>
                            <input type="file" name="design_file" class="form-control" accept=".jpg,.jpeg,.png,.pdf,.doc,.docx">
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-semibold">Notes</label>
                            <textarea name="notes" class="form-control" rows="3"></textarea>
                        </div>

                        <div class="d-grid">
                            <button type="button" id="add-item-btn" class="btn btn-info text-white">
                                <i class="fa-solid fa-plus me-1"></i> Add Item
                            </button>
                        </div>

                    </div>
                </div>

                <!-- CURRENT ORDER ITEMS -->
                <div class="card border-0 shadow-sm rounded-4">
                    <div class="card-header bg-white border-0 px-4 pt-4 pb-2">
                        <h4 class="fw-bold mb-1">Current Order Items</h4>
                        <p class="text-muted small mb-0">Review items before creating the order.</p>
                    </div>

                    <div class="card-body px-4 pb-4">
                        <div id="admin-order-items-empty" class="empty-state">
                            <i class="fa-solid fa-box-open"></i>
                            <p class="mb-0">No items added yet.</p>
                        </div>

                        <div id="admin-order-items-list" style="display:none;"></div>

                        <div id="admin-order-items-footer" style="display:none;">
                            <div class="summary-box">
                                <span>Total Quantity</span>
                                <strong id="admin-total-items">0</strong>
                            </div>

                            <input type="hidden" name="order_items_json" id="order_items_json">

                            <button type="submit" name="create_final_order" class="btn btn-primary w-100 mt-3">
                                Create Order
                            </button>
                        </div>
                    </div>
                </div>

            </form>

        </div>

        <!-- RIGHT SIDE: TABLES -->
        <div class="col-xl-8 col-lg-7">

            <!-- CURRENT ORDERS -->
            <div class="card border-0 shadow-sm rounded-4 mb-4">
                <div class="card-header bg-white border-0 px-4 pt-4 pb-2">
                    <h4 class="fw-bold mb-1">Current Orders</h4>
                    <p class="text-muted small mb-0">Active orders that are not yet completed.</p>
                </div>

                <div class="card-body px-4 pb-4">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle custom-table">
                            <thead>
                                <tr>
                                    <th>Order ID</th>
                                    <th>Customer</th>
                                    <th>Service</th>
                                    <th>Item</th>
                                    <th>Qty</th>
                                    <th>Size</th>
                                    <th>Due</th>
                                    <th>Payment</th>
                                    <th>Status Update</th>
                                    <th>Action</th>
                                </tr>
                            </thead>

                            <tbody>
                                <?php if ($orders && $orders->num_rows > 0): ?>
                                    <?php while ($row = $orders->fetch_assoc()): ?>
                                        <?php $display = order_display_values($row); ?>

                                        <tr>
                                            <td class="fw-semibold"><?php echo h($row["order_code"] ?? "N/A"); ?></td>
                                            <td><?php echo h($row["customer_name"] ?? "N/A"); ?></td>
                                            <td><?php echo h($display["service_type"]); ?></td>
                                            <td><?php echo h($display["item_name"]); ?></td>
                                            <td><?php echo (int)$display["quantity"]; ?></td>
                                            <td><?php echo h($display["size"]); ?></td>
                                            <td><?php echo h($display["due_date"]); ?></td>
                                            <td>
                                                <span class="badge rounded-pill <?php echo paymentBadge($row["payment_status"] ?? ""); ?>">
                                                    <?php echo h(ucfirst($row["payment_status"] ?? "N/A")); ?>
                                                </span>
                                            </td>

                                            <td>
                                                <form method="POST" action="update-order-status.php" class="status-update-form">
                                                    <input type="hidden" name="order_id" value="<?php echo (int)$row["id"]; ?>">

                                                    <select name="status" class="form-select form-select-sm mb-1">
                                                        <option value="pending" <?php echo ($row["status"] ?? "") === "pending" ? "selected" : ""; ?>>Pending</option>
                                                        <option value="accepted" <?php echo ($row["status"] ?? "") === "accepted" ? "selected" : ""; ?>>Accepted</option>
                                                        <option value="in_progress" <?php echo ($row["status"] ?? "") === "in_progress" ? "selected" : ""; ?>>In Progress</option>
                                                        <option value="completed" <?php echo ($row["status"] ?? "") === "completed" ? "selected" : ""; ?>>Completed</option>
                                                        <option value="cancelled" <?php echo ($row["status"] ?? "") === "cancelled" ? "selected" : ""; ?>>Cancelled</option>
                                                    </select>

                                                    <select name="payment_status" class="form-select form-select-sm mb-1">
                                                        <option value="unpaid" <?php echo ($row["payment_status"] ?? "") === "unpaid" ? "selected" : ""; ?>>Unpaid</option>
                                                        <option value="partial" <?php echo ($row["payment_status"] ?? "") === "partial" ? "selected" : ""; ?>>Partial</option>
                                                        <option value="paid" <?php echo ($row["payment_status"] ?? "") === "paid" ? "selected" : ""; ?>>Paid</option>
                                                    </select>

                                                    <button type="submit" class="btn btn-sm btn-success w-100">
                                                        Update
                                                    </button>
                                                </form>
                                            </td>

                                            <td>
                                                <div class="d-flex flex-column gap-1">
                                                    <a href="admin.php?page=order-details&id=<?php echo (int)$row["id"]; ?>" class="btn btn-sm btn-outline-primary">
                                                        View
                                                    </a>

                                                    <a href="admin.php?page=outsourcing-hub&order_id=<?php echo (int)$row["id"]; ?>" class="btn btn-sm btn-info text-white">
                                                        Outsource
                                                    </a>
                                                </div>
                                            </td>
                                        </tr>

                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="10">
                                            <div class="empty-state">
                                                <i class="fa-solid fa-clipboard-list"></i>
                                                <p class="mb-0">No current orders found.</p>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- PREVIOUS ORDERS -->
            <div class="card border-0 shadow-sm rounded-4">
                <div class="card-header bg-white border-0 px-4 pt-4 pb-2">
                    <h4 class="fw-bold mb-1">Previous Orders</h4>
                    <p class="text-muted small mb-0">Completed orders history.</p>
                </div>

                <div class="card-body px-4 pb-4">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle custom-table">
                            <thead>
                                <tr>
                                    <th>Order ID</th>
                                    <th>Customer</th>
                                    <th>Service</th>
                                    <th>Item</th>
                                    <th>Qty</th>
                                    <th>Size</th>
                                    <th>Date</th>
                                    <th>Payment</th>
                                    <th>Status</th>
                                </tr>
                            </thead>

                            <tbody>
                                <?php if ($previousOrders && $previousOrders->num_rows > 0): ?>
                                    <?php while ($row = $previousOrders->fetch_assoc()): ?>
                                        <?php $display = order_display_values($row); ?>

                                        <tr>
                                            <td class="fw-semibold"><?php echo h($row["order_code"] ?? "N/A"); ?></td>
                                            <td><?php echo h($row["customer_name"] ?? "N/A"); ?></td>
                                            <td><?php echo h($display["service_type"]); ?></td>
                                            <td><?php echo h($display["item_name"]); ?></td>
                                            <td><?php echo (int)$display["quantity"]; ?></td>
                                            <td><?php echo h($display["size"]); ?></td>
                                            <td><?php echo formatDateOnly($row["order_date"] ?? ""); ?></td>
                                            <td>
                                                <span class="badge rounded-pill <?php echo paymentBadge($row["payment_status"] ?? ""); ?>">
                                                    <?php echo h(ucfirst($row["payment_status"] ?? "N/A")); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="badge rounded-pill <?php echo statusBadge($row["status"] ?? ""); ?>">
                                                    <?php echo h(ucfirst($row["status"] ?? "N/A")); ?>
                                                </span>
                                            </td>
                                        </tr>

                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="9">
                                            <div class="empty-state">
                                                <i class="fa-solid fa-clock-rotate-left"></i>
                                                <p class="mb-0">No previous orders found.</p>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

        </div>

    </div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const serviceTypeSelect = document.getElementById("service_type");
    const itemNameSelect = document.getElementById("item_name");
    const sizeGroup = document.getElementById("size-group");
    const sizeOptions = document.getElementById("size-options");

    const addItemBtn = document.getElementById("add-item-btn");
    const itemList = document.getElementById("admin-order-items-list");
    const emptyBox = document.getElementById("admin-order-items-empty");
    const footer = document.getElementById("admin-order-items-footer");
    const totalItemsText = document.getElementById("admin-total-items");
    const orderItemsJson = document.getElementById("order_items_json");

    const subtypeMap = <?php echo json_encode($subtypeMap); ?>;
    const variantMap = <?php echo json_encode($variantMap); ?>;

    let orderItems = [];

    function peso(value) {
        const num = parseFloat(value || 0);
        return "₱" + num.toFixed(2);
    }

    function populateSubtypes() {
        const selectedType = serviceTypeSelect.value;

        itemNameSelect.innerHTML = '<option value="">Select Sub Type</option>';
        sizeOptions.innerHTML = "";
        sizeGroup.style.display = "none";

        if (!selectedType || !subtypeMap[selectedType]) {
            return;
        }

        subtypeMap[selectedType].forEach(function (name) {
            const option = document.createElement("option");
            option.value = name;
            option.textContent = name;
            itemNameSelect.appendChild(option);
        });
    }

    function renderSizeOptions() {
        const selectedType = serviceTypeSelect.value;
        const selectedItem = itemNameSelect.value;

        sizeOptions.innerHTML = "";

        if (
            !selectedType ||
            !selectedItem ||
            !variantMap[selectedType] ||
            !variantMap[selectedType][selectedItem]
        ) {
            sizeGroup.style.display = "none";
            return;
        }

        const variants = variantMap[selectedType][selectedItem];

        variants.forEach(function (variant) {
            const label = document.createElement("label");
            label.className = "size-box";

            label.innerHTML = `
                <input 
                    type="radio" 
                    name="size" 
                    value="${variant.size}" 
                    data-price="${variant.price}"
                >
                <span>
                    <strong>${variant.size}</strong>
                    <small>${peso(variant.price)}</small>
                </span>
            `;

            sizeOptions.appendChild(label);
        });

        sizeGroup.style.display = "block";
    }

    serviceTypeSelect.addEventListener("change", populateSubtypes);
    itemNameSelect.addEventListener("change", renderSizeOptions);

    addItemBtn.addEventListener("click", function () {
        const customerName = document.querySelector('[name="customer_name"]').value.trim();
        const customerMobile = document.querySelector('[name="customer_mobile"]').value.trim();
        const serviceType = serviceTypeSelect.value.trim();
        const subType = itemNameSelect.value.trim();
        const quantity = parseInt(document.querySelector('[name="quantity"]').value || "0", 10);
        const sizeInput = document.querySelector('input[name="size"]:checked');

        const size = sizeInput ? sizeInput.value.trim() : "";
        const price = sizeInput ? parseFloat(sizeInput.getAttribute("data-price") || "0") : 0;

        if (!customerName || !customerMobile || !serviceType || !subType || quantity <= 0) {
            alert("Please fill in customer name, contact number, service type, sub type, and quantity.");
            return;
        }

        if (sizeGroup.style.display !== "none" && !sizeInput) {
            alert("Please select a size or option.");
            return;
        }

        const item = {
            service_type: serviceType,
            service_name: subType,
            quantity: quantity,
            size: size,
            price: price
        };

        orderItems.push(item);
        renderItems();

        serviceTypeSelect.selectedIndex = 0;
        itemNameSelect.innerHTML = '<option value="">Select Sub Type</option>';
        document.querySelector('[name="quantity"]').value = 1;
        sizeOptions.innerHTML = "";
        sizeGroup.style.display = "none";
    });

    function renderItems() {
        if (orderItems.length === 0) {
            emptyBox.style.display = "block";
            itemList.style.display = "none";
            footer.style.display = "none";
            orderItemsJson.value = "";
            return;
        }

        emptyBox.style.display = "none";
        itemList.style.display = "block";
        footer.style.display = "block";

        let totalQty = 0;
        itemList.innerHTML = "";

        orderItems.forEach(function (item, index) {
            totalQty += parseInt(item.quantity || 0, 10);

            const total = item.price > 0 ? item.price * item.quantity : 0;

            const row = document.createElement("div");
            row.className = "order-item-card";

            row.innerHTML = `
                <div>
                    <h6 class="fw-bold mb-1">${item.service_name}</h6>
                    <p class="text-muted small mb-1">${item.service_type}</p>
                    <p class="mb-1">Qty: <strong>${item.quantity}</strong></p>
                    <p class="mb-1">Size: <strong>${item.size || "N/A"}</strong></p>
                    ${item.price > 0 ? `<p class="mb-0">Price: <strong>${peso(item.price)}</strong> | Total: <strong>${peso(total)}</strong></p>` : ""}
                </div>

                <button type="button" class="btn btn-sm btn-outline-danger remove-item-btn" data-index="${index}">
                    Remove
                </button>
            `;

            itemList.appendChild(row);
        });

        totalItemsText.textContent = totalQty;
        orderItemsJson.value = JSON.stringify(orderItems);

        document.querySelectorAll(".remove-item-btn").forEach(function (button) {
            button.addEventListener("click", function () {
                const index = parseInt(this.getAttribute("data-index"), 10);
                orderItems.splice(index, 1);
                renderItems();
            });
        });
    }
});
</script>

<style>
.order-page {
    background: #f6f8fb;
    min-height: 100vh;
}

.card {
    overflow: hidden;
}

.form-control,
.form-select {
    border-radius: 10px;
    padding: 10px 12px;
}

.size-options {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.size-box {
    cursor: pointer;
}

.size-box input {
    display: none;
}

.size-box span {
    min-width: 92px;
    padding: 10px 12px;
    border: 1px solid #d1d5db;
    border-radius: 12px;
    display: flex;
    flex-direction: column;
    align-items: center;
    background: #fff;
    transition: 0.2s;
}

.size-box small {
    font-size: 12px;
    color: #6b7280;
}

.size-box input:checked + span {
    border-color: #0ea5e9;
    background: #e0f2fe;
    color: #075985;
}

.order-item-card {
    border: 1px solid #e5e7eb;
    border-radius: 14px;
    padding: 14px;
    margin-bottom: 10px;
    background: #fff;
    display: flex;
    justify-content: space-between;
    gap: 12px;
}

.summary-box {
    background: #f8fafc;
    border-radius: 12px;
    padding: 12px 14px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.custom-table thead th {
    background: #f8fafc;
    color: #111827;
    font-size: 13px;
    font-weight: 700;
    border-bottom: 1px solid #e5e7eb;
    padding: 14px;
    white-space: nowrap;
}

.custom-table tbody td {
    padding: 14px;
    border-bottom: 1px solid #f0f0f0;
    font-size: 13px;
}

.status-update-form {
    min-width: 135px;
}

.empty-state {
    padding: 35px 10px;
    text-align: center;
    color: #6b7280;
}

.empty-state i {
    font-size: 32px;
    margin-bottom: 10px;
    color: #9ca3af;
}

@media (max-width: 992px) {
    .order-page {
        padding: 18px !important;
    }
}
</style>