<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <title>Stock Management System</title>
      <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">
      <link rel="stylesheet" href="assets/vendors/bootstrap-datepicker/bootstrap-datepicker.min.css">
      <link rel="stylesheet" href="assets/css/style.css">
      <link rel="shortcut icon" href="assets/images/favicon.png" />
      <style>
         .hover-preview-container {
         position: relative;
         display: inline-block;
         }
         .table th img, .table td img {
         width: 36px;
         height: 36px;
         border-radius: 0!important;
         }
         .hover-image {
         display: none;
         position: absolute;
         bottom: 100%;
         left: 0;
         margin-bottom: 10px;
         width: 200px;
         border: 1px solid #ccc;
         background: #fff;
         box-shadow: 0 0 10px rgba(0,0,0,0.2);
         z-index: 1000;
         }
         .hover-preview-container:hover .hover-image {
         display: block;
         }
         .search-print-container {
         display: flex;
         justify-content: space-between;
         align-items: center;
         margin-bottom: 20px;
         }
         .filter-container {
         display: flex;
         flex-grow: 1;
         margin-right: 15px;
         }
         .filter-container .form-select {
         margin-right: 10px;
         min-width: 150px;
         }
         .no-results {
         text-align: center;
         padding: 20px;
         color: #666;
         font-style: italic;
         }
         .file-input-container {
         position: relative;
         overflow: hidden;
         }
         .file-input-container input[type="file"] {
         position: absolute;
         font-size: 100px;
         opacity: 0;
         right: 0;
         top: 0;
         }
         .custom-file-upload {
         border: 1px solid #ccc;
         display: inline-block;
         padding: 6px 12px;
         cursor: pointer;
         background-color: #f8f9fa;
         border-radius: 4px;
         }
      </style>
   </head>
   <body>
      <div class="container-scroller">
         <?php $title = "Php Header Footer"; include "header.php"; ?>
         <div class="container-fluid page-body-wrapper">
            <?php $title = "Php Header Footer"; include "sidebar.php"; ?>
            <div class="main-panel">
               <div class="content-wrapper">
                  <?php
                     include 'config.php';
                     
                     // CREATE (Insert) Operation
                     if (isset($_POST['add_stock'])) {
                         $category = $_POST['category'];
                         $item_name = $_POST['item_name'];
                         $description = $_POST['description'];
                         $p_code = trim($_POST['p_code']);
                         $stock = $_POST['stock'];
                         $product_color = $_POST['product_color'];
                         $price = $_POST['price'];
                         $tax = $_POST['tax'];
                         $net_amt = $_POST['net_amt'];
                         $unit_amt = $_POST['unit_amt'];
                         $unit = $_POST['unit'];
                         $status = $_POST['status'];
                         $item_code = $_POST['item_code'];
                         $reorder_level = $_POST['reorder_level'];
                     
                         // Check unique product code
                         $check = mysqli_query($con, "SELECT id FROM tbl_stock_items WHERE p_code='$p_code'");
                         if (mysqli_num_rows($check) > 0) {
                             echo "<script>
                                 alert('Product Code already exists!');
                                 window.location.href = '".$_SERVER['PHP_SELF']."';
                             </script>";
                             exit();
                         }
                         
                         // Handle image upload with strict 50KB size check
                         $product_img = '';
                         if (!empty($_FILES['product_img']['name'])) {
                             if ($_FILES['product_img']['size'] > 51200) {
                                 echo "<script>
                                     alert('Image size must be less than 50KB!');
                                     window.location.href = '".$_SERVER['PHP_SELF']."';
                                 </script>";
                                 exit();
                             }
                             
                             $target_dir = "uploads/";
                             $product_img = time() . "_" . basename($_FILES["product_img"]["name"]);
                             
                             // Validate file is an image
                             $check = getimagesize($_FILES["product_img"]["tmp_name"]);
                             if($check === false) {
                                 echo "<script>
                                     alert('File is not an image!');
                                     window.location.href = '".$_SERVER['PHP_SELF']."';
                                 </script>";
                                 exit();
                             }
                             
                             // Move uploaded file
                             if (!move_uploaded_file($_FILES["product_img"]["tmp_name"], $target_dir . $product_img)) {
                                 echo "<script>
                                     alert('Error uploading image!');
                                     window.location.href = '".$_SERVER['PHP_SELF']."';
                                 </script>";
                                 exit();
                             }
                         }
                       
                         // Insert record
                         $insert_result = mysqli_query($con, "INSERT INTO tbl_stock_items (reorder_level,item_code,category, item_name, description, p_code, stock, product_img, product_color, price, tax, net_amt, unit_amt, unit, status)
                         VALUES ('$reorder_level','$item_code','$category', '$item_name', '$description', '$p_code', '$stock', '$product_img', '$product_color', '$price', '$tax', '$net_amt', '$unit_amt', '$unit', '$status')");
                         
                         if ($insert_result) {
                             echo "<script>
                                 alert('Product added successfully!');
                                 window.location.href = '".$_SERVER['PHP_SELF']."';
                             </script>";
                             exit();
                         } else {
                             echo "<script>
                                 alert('Error adding product!');
                               
                             </script>";
                             exit();
                         }
                     }
                     
                     // UPDATE Operation
                     if (isset($_POST['update_stock'])) {
                         $id = $_POST['id'];
                         $category = $_POST['category'];
                         $item_name = $_POST['item_name'];
                         $description = $_POST['description'];
                         $p_code = trim($_POST['p_code']);
                         $stock = $_POST['stock'];
                         $product_color = $_POST['product_color'];
                         $price = $_POST['price'];
                         $tax = $_POST['tax'];
                         $net_amt = $_POST['net_amt'];
                         $unit_amt=$_POST['unit_amt'];
                         $unit=$_POST['unit'];
                         $status=$_POST['status'];
                         $item_code = $_POST['item_code'];
                         $reorder_level = $_POST['reorder_level'];
                     
                         // Check unique product code except current row
                         $check = mysqli_query($con, "SELECT id FROM tbl_stock_items WHERE p_code='$p_code' AND id!=$id");
                         if (mysqli_num_rows($check) > 0) {
                             echo "<script>
                                 alert('Product Code already exists!');
                                 window.location.href = '".$_SERVER['PHP_SELF']."';
                             </script>";
                             exit();
                         }
                         
                         // Handle image upload with strict 50KB size check
                         $update_img = '';
                         if (!empty($_FILES['product_img']['name'])) {
                             if ($_FILES['product_img']['size'] > 51200) {
                                 echo "<script>
                                     alert('Image size must be less than 50KB!');
                                     window.location.href = '".$_SERVER['PHP_SELF']."';
                                 </script>";
                                 exit();
                             }
                             
                             $target_dir = "uploads/";
                             $update_img = time() . "_" . basename($_FILES["product_img"]["name"]);
                             
                             // Validate file is an image
                             $check = getimagesize($_FILES["product_img"]["tmp_name"]);
                             if($check === false) {
                                 echo "<script>
                                     alert('File is not an image!');
                                     window.location.href = '".$_SERVER['PHP_SELF']."';
                                 </script>";
                                 exit();
                             }
                             // ✅ Check height & width
                              $width  = $check[0];
                              $height = $check[1];
                              if ($width != 240 || $height != 240) {
                                 echo "<script>
                                       alert('Image dimensions must be exactly 240x240 pixels!');
                                       window.location.href = '".$_SERVER['PHP_SELF']."';
                                 </script>";
                                 exit();
                              }
                             // Move uploaded file
                             if (!move_uploaded_file($_FILES["product_img"]["tmp_name"], $target_dir . $update_img)) {
                                 echo "<script>
                                     alert('Error uploading image!');
                                     window.location.href = '".$_SERVER['PHP_SELF']."';
                                 </script>";
                                 exit();
                             }
                             
                             // Update image field
                             mysqli_query($con, "UPDATE tbl_stock_items SET product_img='$update_img' WHERE id=$id");
                         }
                        
                         // Update other fields
                         $update_result = mysqli_query($con, "UPDATE tbl_stock_items SET 
                             category='$category', 
                             item_name='$item_name', 
                             description='$description', 
                             p_code='$p_code', 
                             stock='$stock', 
                             product_color='$product_color', 
                             price='$price', 
                             tax='$tax', 
                             net_amt='$net_amt',
                             unit_amt='$unit_amt', 
                             unit='$unit', 
                             status='$status' ,
                             item_code = '$item_code',
                             reorder_level = '$reorder_level'
                             
                             
                             WHERE id=$id");
                         
                         if ($update_result) {
                             echo "<script>
                                 alert('Product updated successfully!');
                                 window.location.href = '".$_SERVER['PHP_SELF']."';
                             </script>";
                             exit();
                         } else {
                             echo "<script>
                                 alert('Error updating product!');
                                 window.location.href = '".$_SERVER['PHP_SELF']."';
                             </script>";
                             exit();
                         }
                     }
                     
                     // DELETE Operation
                     if (isset($_GET['delete'])) {
                         $id = intval($_GET['delete']);
                         $delete_result = mysqli_query($con, "DELETE FROM tbl_stock_items WHERE id=$id");
                         
                         if ($delete_result) {
                             echo "<script>
                                 alert('Product deleted successfully!');
                                 window.location.href = '".$_SERVER['PHP_SELF']."';
                             </script>";
                             exit();
                         } else {
                             echo "<script>
                                 alert('Error deleting product!');
                                 window.location.href = '".$_SERVER['PHP_SELF']."';
                             </script>";
                             exit();
                         }
                     }
                     
                     // PAGINATION and FILTERING
                     $limit = 15; // rows per page
                     $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
                     $offset = ($page - 1) * $limit;
                     
                     // Build WHERE conditions based on filters
                     $where_conditions = [];
                     
                     if (!empty($_POST['category'])) {
                         $where_conditions[] = "s.category = " . intval($_POST['category']);
                     }
                     if (!empty($_POST['product'])) {
                         $where_conditions[] = "s.item_name = '" . mysqli_real_escape_string($con, $_POST['product']) . "'";
                     }
                     if (!empty($_POST['color'])) {
                         $where_conditions[] = "s.product_color = '" . mysqli_real_escape_string($con, $_POST['color']) . "'";
                     }
                     
                     $where_clause = empty($where_conditions) ? "" : "WHERE " . implode(" AND ", $where_conditions);
                     
                     // Get total records count
                     $total_records_query = "SELECT COUNT(*) AS total FROM tbl_stock_items s $where_clause";
                     $total_records = mysqli_fetch_assoc(mysqli_query($con, $total_records_query))['total'];
                     $total_pages = ceil($total_records / $limit);
                     
                     // Get stock items with category names
                     $stocks_query = "
                         SELECT s.*, c.category_name 
                         FROM tbl_stock_items s
                         LEFT JOIN tbl_categories c ON s.category = c.id
                         $where_clause
                         ORDER BY s.id DESC 
                         LIMIT $offset, $limit
                     ";
                     $stocks = mysqli_query($con, $stocks_query);
                     ?>
                  <div class="row g-1">
                     <!-- Add/Edit Form -->
                     <div class="col-md-4">
                        <div class="card">
                           <div class="card-body">
                              <h4 class="card-title">Add Stock</h4>
                              <form method="post" enctype="multipart/form-data" id="stockForm">
                                 <input type="hidden" name="id" id="edit_id">
                                 <div class="form-group">
                                    <div class="form-floating">
                                       <!-- Category -->
                                        <select name="category" id="edit_category" class="form-select" required>
                                        <option value="" selected disabled>Select Category</option>
                                        <?php
                                        $result = mysqli_query($con, "SELECT id, category_name FROM tbl_categories ORDER BY category_name ASC");
                                        while ($row = mysqli_fetch_assoc($result)) {
                                            echo "<option value='{$row['id']}'>{$row['category_name']}</option>";
                                        }
                                        ?>
                                        </select>
                                       <label for="floatingPassword">Category</label>
                                    </div>
                                 </div>
                                 <div class="form-group">
                                    <div class="form-floating">
                                       <input type="text" name="item_code" id="edit_item_code" class="form-control" placeholder="Item Name" required>
                                       <label for="floatingPassword">Item Code</label>
                                    </div>
                                 </div>
                                 <div class="form-group">
                                    <div class="form-floating">
                                       <input type="text" name="item_name" id="edit_item_name" class="form-control" placeholder="Item Name" required>
                                       <label for="floatingPassword">Item Name</label>
                                    </div>
                                 </div>
                                 <div class="form-group">
                                    <div class="form-floating">
                                       <textarea name="description" id="edit_description" class="form-control" rows="4" placeholder="Description"></textarea>
                                       <label for="floatingPassword">Description</label>
                                    </div>
                                 </div>
                                 <div class="row g-1">
                                    <div class="col-md-4">
                                       <div class="form-floating">
                                          <input type="text" name="p_code" id="edit_p_code" class="form-control" placeholder="P.Code" required>
                                          <label for="floatingPassword">P.Code</label>
                                       </div>
                                    </div>
                                    <div class="col-md-4">
                                       <div class="form-floating">
                                          <input type="number" name="stock" id="edit_stock" class="form-control" placeholder="Stock">
                                          <label for="floatingPassword">Stock</label>
                                       </div>
                                    </div>
                                    <div class="col-md-4">
                                       <div class="form-floating">
                                          <input type="text" name="product_color" id="edit_product_color" class="form-control" placeholder="P.Color">
                                          <label for="floatingPassword">P.Color</label>
                                       </div>
                                    </div>
                                 </div>
                                 <div class="form-group mt-3 d-flex">
                                    <div class="d-block w-100">
                                       <div class="d-flex align-items-center" style="gap:10px;">
                                       <label for="product_img" class="custom-file-upload" style="width:60%;text-align:center;">
                                    <i class="fa fa-upload"></i> Upload Image
                                    </label>
                                    <span id="fileName"></span></div>
                                    <div class="file-input-container">
                                       <input type="file" name="product_img" id="product_img" class="form-control" accept="image/*" onchange="validateImageSize(this)">
                                    </div>
                                    <small class="text-danger">* Maximum file size: 50KB</small>
                                    </div>
                                    
                                 <div id="previewBox" style="margin-top:10px; display:none;">
                                    <img id="previewImage" src="" alt="Preview" 
                                    style="width:40px; height:40px; border:1px solid #ccc; border-radius:4px; object-fit:cover;">
                                 </div>
                                 </div><!-- Preview Section -->

                                 <!-- <div id="previewBox" style="margin-top:10px; display:none;">
                                    <img id="previewImage" src="" alt="Preview" style="width:80px; height:80px; border:1px solid #ccc; border-radius:4px; object-fit:cover;">
                                 </div> -->
                                 <div class="row g-1">
                                    <div class="col-md-4">
                                       <div class="form-floating">
                                          <input type="number" step="0.01" name="price" id="edit_price" class="form-control" placeholder="Price">
                                          <label for="floatingPassword">Price</label>
                                       </div>
                                    </div>
                                    <div class="col-md-4">
                                       <div class="form-floating">
                                          <input type="number" step="0.01" name="tax" id="edit_tax" class="form-control" placeholder="Tax %">
                                          <label for="floatingPassword">Tax</label>
                                       </div>
                                    </div>
                                    <div class="col-md-4">
                                       <div class="form-floating">
                                          <input type="number" step="0.01" name="net_amt" id="edit_net_amt" class="form-control" placeholder="Net Amt">
                                          <label for="floatingPassword">Net Amt</label>
                                       </div>
                                    </div>
                                 </div>
                                 <div class="row g-1 mt-3">
                                    <div class="col-md-6">
                                       <div class="form-floating">
                                          <!-- Unit -->
                                        <select name="unit" id="edit_unit" class="form-select" required>
                                        <option value="" selected>All Categories</option>
                                        <option value="mm">mm - Millimeter</option>
                                        <option value="cm">cm - Centimeter</option>
                                        <option value="m">m - Meter</option>
                                        <option value="kg">kg - Kilogram</option>
                                        <option value="g">g - Gram</option>
                                        <option value="ltr">ltr - Litre</option>
                                        <option value="pcs">pcs - Pieces</option>
                                        </select>
                                         <label for="floatingPassword">Select Unit</label>
                                       </div>
                                    </div>
                                    <div class="col-md-6">
                                       <div class="form-floating">
                                          <input type="number" step="0.01" name="unit_amt" id="edit_unit_amt" class="form-control" placeholder="unit_amt">
                                          <label for="floatingPassword">
                                              Unit Amt
                                          </label>
                                       </div> 
                                    </div>
                                    
                                 </div>
                                 <div class="row g-1 mt-3">
                                    <div class="col-md-6">
                                       <div class="form-floating">
                                          <input type="number" step="0.01" name="reorder_level" id="edit_reorder_level" class="form-control" placeholder="unit_amt">
                                          <label for="floatingPassword">
                                             Reorder Level
                                          </label>
                                       </div> 
                                    </div>
                                    <div class="col-md-6">
                                       <div class="form-floating">
                                          <!-- Status -->
                                            <select name="status" id="edit_status" class="form-select" required>
                                            <option value="Enable">Enable</option>
                                            <option value="Disable">Disable</option>
                                            </select>
                                          <label for="floatingPassword">Status</label>
                                       </div>
                                    </div>
                                 </div>
                                 <button type="submit" name="add_stock" id="add_btn" class="btn btn-gradient-primary w-100 mt-4">Submit</button>
                                 <button type="submit" name="update_stock" id="update_btn" class="btn btn-warning w-100" style="display:none;">Update</button>
                              </form>
                           </div>
                        </div>
                     </div>
                     <!-- Stock Table -->
                     <div class="col-md-8">
                        <div class="card">
                           <div class="card-body">
                              <h4 class="card-title">Stock</h4>
                              <!-- Search and Print Section -->
                              <form method="POST" action="" class="search-print-container">
                                 <div class="filter-container">
                                    <!-- Category -->
                                    <select name="category" id="category" class="form-select">
                                       <option value="" selected>All Categories</option>
                                       <?php
                                          $result = mysqli_query($con, "SELECT id, category_name FROM tbl_categories ORDER BY category_name ASC");
                                          while ($row = mysqli_fetch_assoc($result)) {
                                              $selected = (!empty($_POST['category']) && $_POST['category'] == $row['id']) ? 'selected' : '';
                                              echo "<option value='{$row['id']}' $selected>{$row['category_name']}</option>";
                                          }
                                          ?>
                                    </select>
                                    <!-- Product -->
                                    <select name="product" id="product" class="form-select">
                                       <option value="" selected>All Products</option>
                                       <?php
                                          $query1 = mysqli_query($con, "SELECT DISTINCT item_name FROM tbl_stock_items ORDER BY item_name ASC");
                                          while ($row1 = mysqli_fetch_assoc($query1)) {
                                              $selected = (!empty($_POST['product']) && $_POST['product'] == $row1['item_name']) ? 'selected' : '';
                                              echo "<option value='{$row1['item_name']}' $selected>{$row1['item_name']}</option>";
                                          }
                                          ?>
                                    </select>
                                    <!-- Colour -->
                                    <select name="color" id="color" class="form-select">
                                       <option value="" selected>All Colors</option>
                                       <?php
                                          $query2 = mysqli_query($con, "SELECT DISTINCT product_color FROM tbl_stock_items ORDER BY product_color ASC");
                                          while ($row2 = mysqli_fetch_assoc($query2)) {
                                              $selected = (!empty($_POST['color']) && $_POST['color'] == $row2['product_color']) ? 'selected' : '';
                                              echo "<option value='{$row2['product_color']}' $selected>{$row2['product_color']}</option>";
                                          }
                                          ?>
                                    </select>
                                 </div>
                                 <div class="buttons-container">
                                    <button type="submit" class="btn btn-gradient-primary" title="Search">
                                    <i class="fa fa-search"></i>
                                    </button>
                                    <button type="button" class="btn btn-danger" title="Print" onclick="printSelectedItems()">
                                    <i class="fa fa-print"></i>
                                    </button>
                                    <!--<button type="reset" class="btn btn-secondary" title="Reset" onclick="resetFilters()">-->
                                    <!--    <i class="fa fa-refresh"></i>-->
                                    <!--</button>-->
                                 </div>
                              </form>
                              <div class="table-responsive">
                                 <table class="table" id="stockTable">
                                    <thead>
                                       <tr>
                                          <th>I.Code</th>
                                          <th>Category</th>
                                          <th>I.Name</th>
                                          <th class="d-none">Description</th>
                                          <th>P.Code</th>
                                          <th>Stock</th>
                                          <th>P.Img</th>
                                          <th>P.Color</th>
                                          <!-- <th>U.Type</th> -->
                                          <th>Unit</th>
                                          <th>Status</th>
                                          <th>Price</th>
                                          <th>Tax%</th>
                                          <th>Amt</th>
                                          <th>Action</th>
                                       </tr>
                                    </thead>
                                    <tbody>
                                       <?php 
                                          if (mysqli_num_rows($stocks) > 0) {
                                              while ($row = mysqli_fetch_assoc($stocks)) { 
                                          ?>
                                       <tr>
                                          <td><?php echo $row['item_code']; ?></td>
                                          <td><?php echo $row['category_name']; ?></td>
                                          <td><?php echo $row['item_name']; ?></td>
                                          <td class="d-none"><?php echo $row['description']; ?></td>
                                          <td><?php echo $row['p_code']; ?></td>
                                          <td><?php echo $row['stock']; ?></td>
                                          <td>
                                             <?php if ($row['product_img']) { ?>
                                             <div class="hover-preview-container">
                                                <img src="uploads/<?php echo $row['product_img']; ?>" width="40">
                                                <img src="uploads/<?php echo $row['product_img']; ?>" class="hover-image">
                                             </div>
                                             <?php } ?>
                                          </td>
                                          <!-- <td>KG</td> -->
                                          <td><?php echo $row['product_color']; ?></td>
                                          <td><?php echo $row['unit_amt']. $row['unit'];?></td>

                                          <td><?php echo $row['status']; ?></td>
                                          <td><?php echo $row['price']; ?></td>
                                          <td><?php echo $row['tax']; ?></td>
                                          <td><?php echo $row['net_amt']; ?></td>
                                          <td>
                                             <a href="javascript:void(0)" onclick="editStock(<?php echo htmlspecialchars(json_encode($row), ENT_QUOTES, 'UTF-8'); ?>)" class="text-warning" title="Edit"><i class="fa fa-edit"></i></a>
                                             <a href="?delete=<?php echo $row['id']; ?>" onclick="return confirm('Delete this item?')" class="text-danger" title="Delete"><i class="mdi mdi-delete"></i></a>
                                          </td>
                                       </tr>
                                       <?php 
                                          } 
                                          } else {
                                          echo '<tr><td colspan="12" class="no-results">No stock items found matching your criteria</td></tr>';
                                          }
                                          ?>
                                    </tbody>
                                 </table>
                              </div>
                              <!-- Pagination -->
                              <nav>
                                 <ul class="pagination justify-content-center mt-2">
                                    <?php if ($total_pages > 1): ?>
                                    <?php if ($page > 1): ?>
                                    <li class="page-item">
                                       <a class="page-link" href="?page=<?php echo $page-1; ?><?php echo !empty($_POST) ? '&' . http_build_query($_POST) : ''; ?>" aria-label="Previous">
                                       <span aria-hidden="true">&laquo;</span>
                                       </a>
                                    </li>
                                    <?php endif; ?>
                                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                    <li class="page-item <?php if($i == $page) echo 'active'; ?>">
                                       <a class="page-link" href="?page=<?php echo $i; ?><?php echo !empty($_POST) ? '&' . http_build_query($_POST) : ''; ?>"><?php echo $i; ?></a>
                                    </li>
                                    <?php endfor; ?>
                                    <?php if ($page < $total_pages): ?>
                                    <li class="page-item">
                                       <a class="page-link" href="?page=<?php echo $page+1; ?><?php echo !empty($_POST) ? '&' . http_build_query($_POST) : ''; ?>" aria-label="Next">
                                       <span aria-hidden="true">&raquo;</span>
                                       </a>
                                    </li>
                                    <?php endif; ?>
                                    <?php endif; ?>
                                 </ul>
                              </nav>
                           </div>
                        </div>
                     </div>
                  </div>
                  <script>
                     // Edit Function
                     function editStock(data) {
                         document.getElementById("edit_id").value = data.id;
                         document.getElementById("edit_category").value = data.category;
                         document.getElementById("edit_item_name").value = data.item_name;
                         document.getElementById("edit_description").value = data.description;
                         document.getElementById("edit_p_code").value = data.p_code;
                         document.getElementById("edit_stock").value = data.stock;
                         document.getElementById("edit_product_color").value = data.product_color;
                         document.getElementById("edit_price").value = data.price;
                         document.getElementById("edit_tax").value = data.tax;
                         document.getElementById("edit_net_amt").value = data.net_amt;
                         document.getElementById("edit_unit").value = data.unit;
                          document.getElementById("edit_item_name").value = data.item_name;
                           document.getElementById("edit_reorder_level").value = data.reorder_level;
                        document.getElementById("edit_unit_amt").value = data.unit_amt;
                        document.getElementById("edit_item_code").value = data.item_code;
                         document.getElementById("edit_status").value = data.status;
                         document.getElementById("add_btn").style.display = "none";
                         document.getElementById("update_btn").style.display = "block";
                         window.scrollTo({ top: 0, behavior: 'smooth' });
                     }
                     
                     // Print Selected Items
                     function printSelectedItems() {
                         var category = document.getElementById('category').value;
                         var product = document.getElementById('product').value;
                         var color = document.getElementById('color').value;
                         
                         var url = 'stock-register-category-print.php?';
                         if (category) url += 'category=' + category;
                         if (product) url += '&product=' + product;
                         if (color) url += '&color=' + color;
                         
                         window.open(url);
                     }
                     
                     // Reset Filters
                     function resetFilters() {
                         document.querySelector('form.search-print-container').reset();
                         document.querySelector('form.search-print-container').submit();
                     }
                     
                     function validateImageSize(input) {
                        if (input.files && input.files[0]) {
                           const file = input.files[0];
                           const fileSize = file.size; // in bytes
                           const maxSize = 51200; // 50KB

                           if (fileSize > maxSize) {
                                 alert('Image size must be less than 50KB');
                                 input.value = ''; // Clear file input
                                 document.getElementById('fileName').textContent = '';
                                 return false;
                           }

                           // ✅ Check dimensions
                           const img = new Image();
                           img.src = URL.createObjectURL(file);
                           img.onload = function() {
                                 const width = img.width;
                                 const height = img.height;

                                 if (width !== 240 || height !== 240) {
                                 alert('Image dimensions must be exactly 240x240 pixels');
                                 input.value = '';
                                 document.getElementById('fileName').textContent = '';
                                 document.getElementById('previewBox').style.display = 'none';
                                 return false;
                              } else {
                                 document.getElementById('fileName').textContent = file.name;

                                 // ✅ Show preview
                                 const reader = new FileReader();
                                 reader.onload = function(e) {
                                    document.getElementById('previewImage').src = e.target.result;
                                    document.getElementById('previewBox').style.display = 'block';
                                 };
                                 reader.readAsDataURL(file);

                                 return true;
                              }
                           };
                        }
                        return true;
                     }
                     
                     // Show filename for uploaded file
                     document.getElementById('product_img').addEventListener('change', function(e) {
                         if (this.files && this.files[0]) {
                             document.getElementById('fileName').textContent = this.files[0].name;
                         } else {
                             document.getElementById('fileName').textContent = '';
                         }
                     });
                     
                     // Form validation before submission
                     document.getElementById('stockForm').addEventListener('submit', function(e) {
                         const fileInput = document.getElementById('product_img');
                         if (fileInput.files && fileInput.files[0]) {
                             if (!validateImageSize(fileInput)) {
                                 e.preventDefault();
                                 return false;
                             }
                         }
                         return true;
                     });
                  </script>
               </div>
               <?php $title = "Php Header Footer"; include "footer.php"; ?>
            </div>
         </div>
      </div>
      <!-- plugins:js -->
      <script src="assets/vendors/js/vendor.bundle.base.js"></script>
      <!-- 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>
      <!-- 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>
   </body>
</html>