<!DOCTYPE html>
<html lang="en">
   <head>
      <!-- Required meta tags -->
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <title>Pipscart</title>
      <!-- plugins:css -->
      <link rel="stylesheet" href="assets/vendors/mdi/css/materialdesignicons.min.css">
      <link rel="stylesheet" href="assets/vendors/ti-icons/css/themify-icons.css">
      <link rel="stylesheet" href="assets/vendors/css/vendor.bundle.base.css">
      <link rel="stylesheet" href="assets/vendors/font-awesome/css/font-awesome.min.css">
      <!-- endinject -->
      <!-- Plugin css for this page -->
      <link rel="stylesheet" href="assets/vendors/font-awesome/css/font-awesome.min.css" />
      <link rel="stylesheet" href="assets/vendors/bootstrap-datepicker/bootstrap-datepicker.min.css">
      <!-- End plugin css for this page -->
      <!-- inject:css -->
      <!-- endinject -->
      <!-- Layout styles -->
      <link rel="stylesheet" href="assets/css/style.css">
      <style>
         .product-card {
         width: 100%;
         position: relative;
         background: white;
         border-radius: 20px;
         box-shadow: 0 10px 40px rgba(0, 0, 0, 0.08);
         overflow: hidden;
         transition: transform 0.4s ease, box-shadow 0.4s ease;
         font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
         margin: 15px auto;
         }
         .product-card:hover {
         transform: translateY(-10px);
         box-shadow: 0 20px 50px rgba(0, 0, 0, 0.15);
         }
         .product-badge {
         position: absolute;
         top: 15px;
         right: 15px;
         background: linear-gradient(45deg, #18181B, #27272A);
         color: white;
         padding: 6px 12px;
         font-size: 12px;
         font-weight: 600;
         letter-spacing: 1px;
         text-transform: uppercase;
         border-radius: 12px;
         z-index: 10;
         box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
         }
         .product-tilt-effect {
         overflow: hidden;
         transform-style: preserve-3d;
         perspective: 1000px;
         }
         .product-image {
  height: 240px;
  overflow: hidden;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}
/* blurred background */
.product-image::before {
  content: "";
  position: absolute;
  inset: 0;
  background: inherit; /* will inherit inline background from PHP */
  background-size: cover;
  background-position: center;
  filter: blur(20px);
  transform: scale(1.1); /* prevents blur edges */
  z-index: 0;
}

         .item-code {
  position: absolute;
  top: 10px;
  right: 10px;
  background: black;
  color: white;
  padding: 4px 8px;
  font-size: 12px;
  font-weight: bold;
  border-radius: 4px;
  opacity: 0.85;
  z-index: 2;
}
         .product-image img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  position: relative;
  z-index: 1;
  transition: transform 0.8s cubic-bezier(0.19, 1, 0.22, 1);
}
        .product-card:hover .product-image img {
  transform: scale(1.05);
}
         .product-info {
         padding: 25px;
         position: relative;
         }
         .product-category {
         font-size: 12px;
         font-weight: 600;
         letter-spacing: 1px;
         text-transform: uppercase;
         color: #71717A;
         margin-bottom: 8px;
         }
         .product-title {
         font-size: 15px;
         /*          font-weight: 700; */
         color: #18181B;
         margin: 0 0 12px 0;
         letter-spacing: -0.5px;
         line-height: 1.2;
         }
         .product-description p {
         font-size: 14px;
         color: #52525B;
         line-height: 1.5;
         margin-bottom: 15px;
         }
         .product-features {
         display: flex;
         flex-wrap: wrap;
         gap: 8px;
         margin-bottom: 20px;
         }
         .feature {
         font-size: 11px;
         background-color: #F4F4F5;
         color: #71717A;
         padding: 4px 10px;
         border-radius: 12px;
         font-weight: 500;
         }
         .product-bottom {
         display: block;
         justify-content: space-between;
         align-items: center;
         margin-bottom: 15px;
         gap: 10px;
         }
         .product-price {
         display: flex;
         flex-direction: column;
         }
         .price-was {
         font-size: 14px;
         text-decoration: line-through;
         color: #A1A1AA;
         margin-bottom: 2px;
         }
         .price-now {
         font-size: 18px;
         font-weight: 700;
         color: #18181B;
         }
         .product-button {
         background: linear-gradient(45deg, #18181B, #27272A);
         color: white;
         border: none;
         border-radius: 12px;
         padding: 10px 18px;
         font-size: 14px;
         font-weight: 600;
         cursor: pointer;
         display: flex;
         align-items: center;
         gap: 8px;
         transition: all 0.3s ease;
         box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
         position: relative;
         overflow: hidden;
         }
         .product-button::before {
         content: '';
         position: absolute;
         top: 0;
         left: -100%;
         width: 100%;
         height: 100%;
         background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
         transition: all 0.6s ease;
         }
         .product-button:hover {
         background: linear-gradient(45deg, #27272A, #3F3F46);
         transform: translateY(-3px);
         box-shadow: 0 10px 20px rgba(0, 0, 0, 0.15);
         }
         .product-button:hover::before {
         left: 100%;
         }
         .button-icon {
         transition: transform 0.3s ease;
         }
         .product-button:hover .button-icon {
         transform: rotate(-10deg) scale(1.1);
         }
         .product-meta {
         display: flex;
         justify-content: space-between;
         align-items: center;
         border-top: 1px solid #F4F4F5;
         padding-top: 15px;
         }
         .product-rating {
         display: flex;
         align-items: center;
         gap: 2px;
         }
         .rating-count {
         margin-left: 8px;
         font-size: 12px;
         color: #71717A;
         }
         .product-stock {
         font-size: 12px;
         font-weight: 600;
         color: #22C55E;
         }
         @media (max-width: 400px) {
         .product-card {
         width: 90%;
         }
         .product-title {
         font-size: 18px;
         }
         .product-image {
         height: 200px;
         }
         .product-bottom {
         flex-direction: column;
         align-items: flex-start;
         gap: 15px;
         }
         .product-price {
         margin-bottom: 5px;
         }
         .product-button {
         width: 100%;
         justify-content: center;
         }
         }
         /* Search Bar Styling */
         #productSearch {
         width: 100%;
         padding: 9px 14px;
         margin-bottom: 20px;
         font-size: 14px;
         border: 1px solid #E4E4E7;
         border-radius: 12px;
         outline: none;
         background-color: #FAFAFA;
         transition: all 0.3s ease;
         font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
         }
         #productSearch:focus {
         border-color: #18181B;
         background-color: #FFFFFF;
         box-shadow: 0 4px 12px rgba(0,0,0,0.05);
         }
         /* Backdrop overlay */
         .overlay_bg_c9 {
         display: none;
         position: fixed;
         top: 0;
         left: 0;
         width: 100%;
         height: 100%;
         background-color: rgba(0,0,0,0.5);
         z-index: 1030; /* below sidebar */
         }
         /* Sidebar styles */
         .sideBox_t3 {
         height: 100%;
         width: 0;
         position: fixed;
         top: 0;
         right: 0; /* change to left:0 for left sidebar */
         background-color:white;
         overflow-x: hidden;
         transition: 0.4s;
         padding-top: 60px;
         color: black;
         z-index: 1030; /* above backdrop */
         }
         .sideBox_t3 a {
         padding: 16px 28px 16px 16px;
         text-decoration: none;
         color: black;
         /*   display: block; */
         display: flex
         ;
         align-items: center;
         justify-content: end;
         width: 100%;
         }
         .btnClose_w1 {
         position: absolute;
         top: 10px;
         left: 10px;
         font-size: 24px;
         color: white;
         }
         .row {
         --bs-gutter-x: 10px;
         --bs-gutter-y: 0;
         display: flex
         ;
         flex-wrap: wrap;
         margin-top: calc(-1 * var(--bs-gutter-y));
         margin-right: calc(-0.5 * var(--bs-gutter-x));
         margin-left: calc(-0.5 * var(--bs-gutter-x));
         }
      </style>
      <style>
         .qtyWidget_x1 {
         display: inline-flex;
         align-items: center;
         gap: 6px;
         border-radius: 8px;
         overflow: hidden;
         font-family: system-ui, sans-serif;
         background: #fff;
         border: 1px solid rgba(0,0,0,0.1);
         box-shadow: 0 2px 6px rgba(0,0,0,0.05);
         width:100%;
         }
         .qtyBtn_x1 {
         border: none;
         padding: 8px 10px;
         cursor: pointer;
         background: transparent;
         font-size: 18px;
         line-height: 1;
         user-select: none;
         transition: background 0.12s;
         width:33.33%;
         }
         .qtyBtn_x1:hover { background: rgba(0,0,0,0.05); }
         .qtyBtn_x1:active { transform: translateY(1px); }
         .qtyInput_x1 {
         width: 33.33%;
         text-align: center;
         border: none;
         padding: 8px 6px;
         font-size: 14px;
         }
         .cart-badge {
         position: absolute;
         top: -8px;
         right: -8px;
         background: red;
         color: white;
         border-radius: 50%;
         padding: 2px 6px;
         font-size: 12px;
         font-weight: bold;
         line-height: 1;
         }
         .itemBox_9a {
         display: flex;
         justify-content: space-between;
         align-items:center;
         border-bottom: 1px solid #ddd;
         padding: 15px;
         max-width: 400px;
         font-family: Arial, sans-serif;
         position: relative;
         }
         .itemDetails_9a {
         flex: 1;
         margin-right: 10px;
         }
         .itemDetails_9a h4 {
         margin: 0;
         font-size: 14px;
         font-weight: 600;
         color: #000;
         }
         .itemDetails_9a p {
         font-size: 13px;
         color: #555;
         margin: 5px 0 0;
         }
         .itemImgWrap_9a {
         position: relative;
         }
         .itemImgWrap_9a img {
         width: 70px;
         height: auto;
         border-radius: 4px;
         }
         .closeIcon_9a {
         position: absolute;
         top: -5px;
         right: -5px;
         background: #fff;
         border: 1px solid #ccc;
         border-radius: 50%;
         width: 18px;
         height: 18px;
         display: flex;
         justify-content: center;
         align-items: center;
         font-size: 12px;
         cursor: pointer;
         }
         .closeIcon_9a:hover {
         background: #f5f5f5;
         }
      </style>
      <style>
         .btn_xk92 {
         cursor: pointer;
         font-weight: 700;
         transition: all 0.2s;
         padding: 10px 20px;
         border-radius: 100px;
         background:black;
         color: white;
         border: 1px solid transparent;
         display: flex;
         align-items: center;
         font-size: 15px;
         justify-content: space-between;
         }
         .btn_xk92:hover {
         background: #323232;
         }
         .btn_xk92 > .svg_mn57 {
         width: 34px;
         margin-left: 10px;
         transition: transform 0.3s ease-in-out;
         }
         .btn_xk92:hover .svg_mn57 {
         transform: translateX(5px);
         }
         .btn_xk92:active {
         transform: scale(0.95);
         }
         .sticky-right-panel {
         position: sticky;
         top: 0; /* keeps it visible when scrolling */
         height: 100vh; /* full viewport height */
         overflow-y: auto; /* allow table to scroll if too tall */
         /*   background: white; /* prevents transparency bleed */ */
         z-index: 10;
         }
         .scrollable-left-panel {
         max-height: 100vh;
         overflow-y: scroll;
         scrollbar-width: none; /* Firefox */
         -ms-overflow-style: none; /* Internet Explorer / Edge */
         }
         .scrollable-left-panel::-webkit-scrollbar {
         display: none; /* Chrome, Safari, Opera */
         }
      </style>
      <!-- End layout styles -->
      <!-- <link rel="shortcut icon" href="assets/images/favicon.png" /> -->
   </head>
   <body>
      <div class="container-scroller">
         <!-- partial:partials/_navbar.html -->
         <!-- partial:partials/_navbar.html -->
         <?php
         include "config.php"; // make sure this has your DB connection
            $title = "Php Header Footer";
            include "header.php";
            ?>
         <!-- partial -->
         <div class="container-fluid page-body-wrapper">
            <!-- partial:partials/_sidebar.html -->
            <?php
               $title = "Php Header Footer";
               include "sidebar.php";
               ?>
            <!-- partial -->
            <style>
                .productSearch1 {
    width: 100%!important;
    padding: 10px 14px!important;
    margin-bottom: 20p!importantx;
    font-size: 14px!important;
    border: 1px solid #E4E4E7!important;
    border-radius: 12px!important;
    outline: none!important;
    background-color: #FAFAFA!important;
    transition: all 0.3s ease!important;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif!important;
}
/* For single select height fix */
.select2-container .select2-selection--single {
    min-height: 38px !important;
    height: 38px !important;
    padding: 4px 8px !important;
    border: 1px solid #ced4da !important; /* Bootstrap border */
    border-radius: 4px !important;        /* Bootstrap radius */
}

/* Text alignment inside */
.select2-container--default .select2-selection--single .select2-selection__rendered {
    line-height: 28px !important;
}

/* Dropdown arrow alignment */
.select2-container--default .select2-selection--single .select2-selection__arrow {
    height: 36px !important;
    right: 8px !important;
}

            </style>
            <!-- partial -->
<?php 
include "config.php";

$order_id = isset($_GET['edit_order_id']) ? $_GET['edit_order_id'] : null;

// Fetch order details if editing
$order = null;
$cart = []; // Initialize cart
if ($order_id) {
    $stmt = $con->prepare("SELECT * FROM orders WHERE id = ?");
    $stmt->bind_param("i", $order_id);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    // Fetch order items if editing
    $stmt = $con->prepare("SELECT * FROM order_items WHERE order_id = ?");
    $stmt->bind_param("i", $order_id);
    $stmt->execute();
    $order_items = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    // Initialize cart with existing order items
    foreach ($order_items as $item) {
        $cart[] = [
            'id' => $item['product_id'],
            'name' => $item['product_name'],
            'price' => $item['price'],
            'quantity' => $item['quantity'],
            'remarks' => $item['remarks'] ?? ''
        ];
    }
}
?>

<div class="main-panel">
    <div class="content-wrapper">
        <div class="row">
            <div class="col-md-3">
                <h4 class="card-title"><?= $order_id ? 'Edit Order' : 'Create Order' ?></h4>
            </div>
            <div class="col-md-3">
                <div class="d-flex g-3" style="gap: 10px;">
                    <input type="text" id="productSearch" placeholder="Search Product Name/Category">
                </div>
            </div>
            <div class="col-md-3">
                <select id="categoryFilter" class="form-control productSearch1">
                    <option value="">All Categories</option>
                    <?php
                    $catQuery = "SELECT * FROM tbl_categories ORDER BY category_name ASC";
                    $catResult = mysqli_query($con, $catQuery);
                    if ($catResult && mysqli_num_rows($catResult) > 0) {
                        while ($cat = mysqli_fetch_assoc($catResult)) {
                            echo '<option value="' . $cat['id'] . '">' . htmlspecialchars($cat['category_name']) . '</option>';
                        }
                    }
                    ?>
                </select>
            </div>
            <!-- jQuery (required) -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<!-- Select2 CSS -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

<!-- Select2 JS -->
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>


<div class="col-md-3">
    <div class="d-flex g-3" style="gap: 10px;">
        <select id="customerSelect" class="form-control productSearch1">
            <option value="" selected disabled>Select Customer</option>
            <?php
            $query = "SELECT id, company_name, contact_person FROM tbl_customers ORDER BY company_name ASC";
            $result = mysqli_query($con, $query);
            if ($result && mysqli_num_rows($result) > 0) {
                while ($row = mysqli_fetch_assoc($result)) {
                    echo '<option value="' . $row['id'] . '">' 
                            . htmlspecialchars($row['company_name']) 
                            . ' - ' 
                            . htmlspecialchars($row['contact_person']) 
                         . '</option>';
                }
            }
            ?>
        </select>
    </div>
</div>



        </div>

        <!-- Cart Items -->
        <div class="row">
            <div class="col-md-8 scrollable-left-panel">
                <div class="row">
                    <div class="col-md-12">
                        <div class="row" id="productsContainer">
                            <!-- Products will be loaded here -->
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-4 sticky-right-panel">
                <div class="table-responsive mt-3">
                    <table class="table table-bordered table-striped" id="cartTable">
                        <thead class="thead">
                            <tr>
                                <th>#</th>
                                <th>P.Name</th>
                                <th>Rate</th>
                                <th>Qty</th>
                                <th>T.Amt</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody id="cartItemsTable">
                            <!-- Cart items will be dynamically added here -->
                            <?php if ($order_id): ?>
                                <?php foreach ($cart as $index => $item): ?>
                                    <tr data-row-id="<?= $item['id'] ?>">
                                        <td><?= $index + 1 ?></td>
                                        <td><?= htmlspecialchars($item['name']) ?></td>
                                        <td>
                                            <input type="number" min="0" step="0.01"
                                                   class="rate-input"
                                                   style="max-width:100px;border:none;"
                                                   data-id="<?= $item['id'] ?>"
                                                   value="<?= htmlspecialchars($item['price']) ?>">
                                        </td>
                                        <td>
                                            <input type="number"
                                                   class="qty-input"
                                                   style="max-width:50px;border:none;"
                                                   data-id="<?= $item['id'] ?>"
                                                   value="<?= htmlspecialchars($item['quantity']) ?>">
                                        </td>
                                        <td class="line-total" data-id="<?= $item['id'] ?>">
                                            <?= number_format($item['price'] * $item['quantity'], 2) ?>
                                        </td>
                                        <td class="text-nowrap">
                                            <button type="button" class="btn btn-link p-0 me-2 edit-remarks" data-id="<?= $item['id'] ?>" data-remarks="<?= htmlspecialchars($item['remarks']) ?>" title="Edit Remarks">
                                                <i class="fa fa-comment<?= $item['remarks'] ? ' text-primary' : ' text-muted' ?>"></i>
                                            </button>
                                            <button type="button" class="btn btn-link p-0 remove-row" data-id="<?= $item['id'] ?>" title="Remove">
                                                <i class="fa fa-trash text-danger"></i>
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                <form>
                    <textarea placeholder="Order Note" id="orderNote" class="form-control mt-2"><?= $order_id ? htmlspecialchars($order['note']) : '' ?></textarea>
                </form>
                <div class="d-flex justify-content-between mt-3">
                    <button class="btn btn-success w-50" style="padding: 0; height: 40px;" onclick="generateOrder()">Order Form</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Remarks Modal -->
<div class="modal fade" id="remarksModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Remarks</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <textarea id="remarksText" class="form-control" placeholder="Enter remarks for this product" rows="3"></textarea>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="saveRemarks">Save Remarks</button>
            </div>
        </div>
    </div>
</div>



<script>let cart = [];
let offset = 0;
const productsPerPage = 20;
let isLoading = false; // Flag to prevent multiple fetches
let currentCategoryFilter = '';
let currentSearchFilter = '';

document.addEventListener('DOMContentLoaded', function() {
    const editOrderId = <?= json_encode($order_id) ?>;
    if (editOrderId) {
        cart = <?= json_encode($cart) ?>;
        updateCartDisplay();
    } else {
        loadCartFromLocalStorage();
    }
    // Initial load without filters
    resetAndLoadProducts();
});

// Load cart from localStorage
function loadCartFromLocalStorage() {
    const storedCart = localStorage.getItem('cart');
    if (storedCart) {
        cart = JSON.parse(storedCart);
        updateCartDisplay();
    }
}

// Reset offset and products container, then load products with current filters
function resetAndLoadProducts() {
    offset = 0;
    const productsContainer = document.getElementById('productsContainer');
    productsContainer.innerHTML = '';
    loadMoreProductsWithFilter(currentCategoryFilter, currentSearchFilter);
}

// Infinite scroll inside panel
document.querySelector('.scrollable-left-panel').addEventListener('scroll', function() {
    if (this.scrollTop + this.clientHeight >= this.scrollHeight - 50 && !isLoading) {
        loadMoreProductsWithFilter(currentCategoryFilter, currentSearchFilter);
    }
});

// Filter inputs event listeners
document.getElementById("productSearch").addEventListener("keyup", function() {
    currentSearchFilter = this.value.toLowerCase().trim();
    resetAndLoadProducts();
});
document.getElementById("categoryFilter").addEventListener("change", function() {
    currentCategoryFilter = this.value;
    resetAndLoadProducts();
});

// Fetch products with filters and pagination
function loadMoreProductsWithFilter(category, search) {
    if (isLoading) return;
    isLoading = true;

    const params = new URLSearchParams({
        offset: offset,
        limit: productsPerPage,
    });
    if (category) params.append('category', category);
    if (search) params.append('search', search);

    fetch(`fetch_products.php?${params.toString()}`)
        .then(response => {
            if (!response.ok) throw new Error('Network response was not ok');
            return response.json();
        })
        .then(data => {
            if (data.length > 0) {
                appendProductsToDOM(data);
                offset += productsPerPage;
            } else if (offset === 0) {
                // No products found on first load
                document.getElementById('productsContainer').innerHTML = '<p>No products found.</p>';
            }
            isLoading = false;
        })
        .catch(error => {
            console.error('Fetch error:', error);
            isLoading = false;
        });
}

// Append products HTML to container
function appendProductsToDOM(products) {
    const productsContainer = document.getElementById('productsContainer');
    products.forEach(product => {
        // Use product.category_id for data-category attribute (adjust per your DB)
        const productHTML = `
            <div class="col-md-4 product-item" data-category="${product.category_id || ''}" data-product-id="${product.id}">
                <div class="product-card">
                    <div class="product-image">
                        <img src="uploads/${product.product_img || 'default.png'}" alt="${product.item_name}">
                        <div class="item-code">CODE: ${product.p_code || ''}</div>
                    </div>
                    <div class="product-info">
                        <div class="product-category">${product.category_name || ''}</div>
                        <h2 class="product-title">${product.item_name}</h2>
                        <div class="product-stock d-flex justify-content-between">
                            <span style="color:${product.stock <= 0 ? 'red' : 'darkgreen'}">
                                Stock: ${product.stock || 0}
                            </span>
                            <span>I.Code: ${product.item_code || ''}</span>
                        </div>
                        <div class="product-bottom">
                            <div class="product-price">
                                <span class="price-now">${product.price}</span>
                            </div>
                            <div class="qtyWidget_x1" data-min="1" data-step="1">
                                <button type="button" class="qtyBtn_x1 qtyBtn--minus_x1">−</button>
                                <input class="qtyInput_x1" type="text" value="1" data-product-id="${product.id}" />
                                <button type="button" class="qtyBtn_x1 qtyBtn--plus_x1">+</button>
                            </div>
                            <button class="product-button w-100 d-flex justify-content-center" 
                                    onclick="addToCart(${product.id}, '${escapeQuotes(product.item_name)}', ${product.price})">
                                <span class="button-text">Add to Cart</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>`;
        productsContainer.insertAdjacentHTML('beforeend', productHTML);
    });
    initializeQtyWidgets();
}


async function generateOrder() {
    const customerId = document.getElementById("customerSelect").value;
    const orderNote = (document.getElementById("orderNote")?.value || "").trim();
    if (!customerId) {
        alert("Please select a customer before generating the order.");
        return;
    }
    if (cart.length === 0) {
        alert("Your cart is empty!");
        return;
    }

    try {
        // Save order with remarks
        const orderResponse = await fetch("saveorder.php", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
                customer_id: customerId,
                order_note: orderNote,
                order_id: <?= json_encode($order_id) ?>,
                cart: cart.map(it => ({
                    id: it.id,
                    name: it.name,
                    price: parseFloat(it.price), // ✅ numeric value
                    quantity: Number(it.quantity),
                    remarks: it.remarks || ''
                }))
            })
        });

        const orderData = await orderResponse.json();
                if (!orderData.success) throw new Error("Failed to save order: " + (orderData.message || "Unknown error"));

        cart = [];
        localStorage.removeItem('cart'); // Clear local storage
        updateCartDisplay();
        window.location.href = "order-form.php?order_id=" + orderData.order_id;
    } catch (error) {
        alert("Error: " + error.message);
    }
}

// Remarks modal handling
document.getElementById('saveRemarks').addEventListener('click', function() {
    const remarks = document.getElementById('remarksText').value.trim();
    if (currentRemarksProductId !== null) {
        const item = cart.find(item => item.id === currentRemarksProductId);
        if (item) {
            item.remarks = remarks;
            updateCartDisplay();
            saveCartToLocalStorage(); // Save cart to localStorage
        }
    }

    const modal = bootstrap.Modal.getInstance(document.getElementById('remarksModal'));
    modal.hide();
    document.getElementById('remarksText').value = '';
    currentRemarksProductId = null;
});

document.getElementById('remarksModal').addEventListener('hidden.bs.modal', function() {
    document.getElementById('remarksText').value = '';
    currentRemarksProductId = null;
});

// Initialize quantity widgets
function initializeQtyWidgets() {
    document.querySelectorAll('.qtyWidget_x1').forEach(widget => {
        const input = widget.querySelector('.qtyInput_x1');
        const btnPlus = widget.querySelector('.qtyBtn--plus_x1');
        const btnMinus = widget.querySelector('.qtyBtn--minus_x1');

        const MIN = Number(widget.dataset.min) || 1;
        const MAX = widget.dataset.max ? Number(widget.dataset.max) : Infinity;
        const STEP = Number(widget.dataset.step) || 1;

        function clamp(val) { if (isNaN(val)) val = MIN; return Math.min(MAX, Math.max(MIN, val)); }
        function setValue(val) { input.value = clamp(val); }
        function step(delta) { setValue(Number(input.value || 0) + delta * STEP); }

        btnPlus.addEventListener('click', e => { e.preventDefault(); step(1); });
        btnMinus.addEventListener('click', e => { e.preventDefault(); step(-1); });

        input.addEventListener('input', () => { input.value = input.value.replace(/[^0-9]/g, ''); });
        input.addEventListener('blur', () => { setValue(Number(input.value || MIN)); });
        input.addEventListener('keydown', e => {
            if (e.key === 'ArrowUp') { e.preventDefault(); step(1); }
            if (e.key === 'ArrowDown') { e.preventDefault(); step(-1); }
        });
        setValue(Number(input.value || MIN));
    });
}

// Utility to escape single quotes in product names for onclick attribute
function escapeQuotes(str) {
    return str.replace(/'/g, "\\'");
}

// Add product to cart
function addToCart(productId, productName, productPrice) {
    const qtyInput = document.querySelector(`input[data-product-id="${productId}"]`);
    const quantity = parseInt(qtyInput.value) || 1;

    const idx = cart.findIndex(item => item.id === productId);
    if (idx > -1) {
        cart[idx].quantity += quantity;
    } else {
        cart.push({
            id: productId,
            name: productName,
            price: Number(productPrice),
            quantity: quantity,
            remarks: ''
        });
    }
    updateCartDisplay();
    qtyInput.value = 1;
    saveCartToLocalStorage();
}

function saveCartToLocalStorage() {
    localStorage.setItem('cart', JSON.stringify(cart));
}

function updateCartDisplay() {
    const cartItemsTable = document.getElementById('cartItemsTable');
    cartItemsTable.innerHTML = '';

    let totalAmount = 0;

    cart.forEach((item, index) => {
        const lineTotal = item.price * item.quantity;
        totalAmount += lineTotal;

        cartItemsTable.innerHTML += `
            <tr data-row-id="${item.id}">
                <td>${index + 1}</td>
                <td>${item.name}</td>
                <td>
                    <input type="number" min="0" step="0.01"
                           class="rate-input"
                           style="max-width:100px;border:none;"
                           data-id="${item.id}"
                           value="${item.price}">
                </td>
                <td>
                    <input type="number"
                           class="qty-input"
                           style="max-width:50px;border:none;"
                           data-id="${item.id}"
                           value="${item.quantity}">
                </td>
                <td class="line-total" data-id="${item.id}">${lineTotal.toFixed(2)}</td>
                <td class="text-nowrap">
                    <button type="button" class="btn btn-link p-0 me-2 edit-remarks" data-id="${item.id}" data-remarks="${item.remarks || ''}" title="Edit Remarks">
                        <i class="fa fa-comment${item.remarks ? ' text-primary' : ' text-muted'}"></i>
                    </button>
                    <button type="button" class="btn btn-link p-0 remove-row" data-id="${item.id}" title="Remove">
                        <i class="fa fa-trash text-danger"></i>
                    </button>
                </td>
            </tr>
        `;
    });

    cartItemsTable.innerHTML += `
        <tr>
            <td colspan="4" class="text-end"><strong>Total</strong></td>
            <td id="grandTotalCell"><strong>${totalAmount.toFixed(2)}</strong></td>
            <td></td>
        </tr>
    `;

    wireRowEvents();
}

function wireRowEvents() {
    document.querySelectorAll('.rate-input').forEach(inp => {
        inp.addEventListener('input', e => {
            const id = Number(inp.dataset.id);
            const item = cart.find(x => x.id === id);
            if (!item) return;
            item.price = Number(inp.value);
            recalcLine(id);
            saveCartToLocalStorage();
        });
    });

    document.querySelectorAll('.qty-input').forEach(inp => {
        inp.addEventListener('input', e => {
            const id = Number(inp.dataset.id);
            const item = cart.find(x => x.id === id);
            if (!item) return;

            const val = inp.value.trim();
            if (val === "") return;

            const q = Math.max(1, parseInt(val));
            item.quantity = q;
            inp.value = q;
            recalcLine(id);
            saveCartToLocalStorage();
        });

        inp.addEventListener('blur', e => {
            const id = Number(inp.dataset.id);
            const item = cart.find(x => x.id === id);
            if (!item) return;

            const q = Math.max(1, parseInt(inp.value) || 1);
            item.quantity = q;
            inp.value = q;
            recalcLine(id);
            saveCartToLocalStorage();
        });
    });

    document.querySelectorAll('.edit-remarks').forEach(btn => {
        btn.addEventListener('click', e => {
            const id = Number(btn.dataset.id);
            const item = cart.find(x => x.id === id);
            if (item) {
                currentRemarksProductId = id;
                document.getElementById('remarksText').value = item.remarks || '';
                const modal = new bootstrap.Modal(document.getElementById('remarksModal'));
                modal.show();
            }
        });
    });

    document.querySelectorAll('.remove-row').forEach(btn => {
        btn.addEventListener('click', e => {
            removeFromCart(Number(btn.dataset.id));
        });
    });
}

function recalcLine(id) {
    const item = cart.find(x => x.id === id);
    if (!item) return;

    const lt = (item.price * Number(item.quantity || 0)).toFixed(2);

    const cell = document.querySelector(`.line-total[data-id="${id}"]`);
    if (cell) cell.textContent = lt;

    recalcTotals();
}

function recalcTotals() {
    let total = 0;
    cart.forEach(it => total += it.price * Number(it.quantity || 0));

    const totalCell = document.getElementById("grandTotalCell");
    if (totalCell) {
        totalCell.innerHTML = `<strong>${total.toFixed(2)}</strong>`;
    }
}

function removeFromCart(productId) {
    cart = cart.filter(item => item.id !== productId);
    updateCartDisplay();
    saveCartToLocalStorage();
}
</script>

</div>
<!-- content-wrapper ends -->
<!-- partial:partials/_footer.html -->
<?php
    $title = "Php Header Footer";
    include "footer.php";
?>
<!-- partial -->
</div>
<!-- container-scroller -->
      <!-- plugins:js -->
      <script src="assets/vendors/js/vendor.bundle.base.js"></script>
      <!-- endinject -->
      <!-- Plugin js for this page -->
      <script src="assets/vendors/chart.js/chart.umd.js"></script>
      <script src="assets/vendors/bootstrap-datepicker/bootstrap-datepicker.min.js"></script>
      <!-- End plugin js for this page -->
      <!-- inject:js -->
      <script src="assets/js/off-canvas.js"></script>
      <script src="assets/js/misc.js"></script>
      <script src="assets/js/settings.js"></script>
      <script src="assets/js/todolist.js"></script>
      <script src="assets/js/jquery.cookie.js"></script>
      <!-- endinject -->
      <!-- Custom js for this page -->
      <script src="assets/js/dashboard.js"></script>
      <!-- End custom js for this page -->
      
      
            <script src="assets/js/misc.js"></script>
      <script src="assets/js/settings.js"></script>
      <script src="assets/js/todolist.js"></script>
      <script src="assets/js/jquery.cookie.js"></script>
      <!-- endinject -->
      <!-- Custom js for this page -->
      <script src="assets/js/dashboard.js"></script>
      <!-- End custom js for this page -->
      <!-- jQuery (required for Select2) -->
      <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
      <!-- Select2 JS -->
      <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
      <script>
         $(document).ready(function() {
            $('#customerSelect').select2({
               placeholder: "Select Customer",
               allowClear: true,
               width: '100%'
            });
         });
      </script>
      
   </body>
</html>
