<?php
$page_title = 'All Group';
require_once('includes/load.php');
require 'vendor/autoload.php'; // Autoload PHPSpreadsheet

$startDate = isset($_GET['startDate']) ? $_GET['startDate'] : '';
$endDate = isset($_GET['endDate']) ? $_GET['endDate'] : '';
$shopId = isset($_GET['shop']) ? $_GET['shop'] : '';
$invoice = isset($_GET['invoice']) ? $_GET['invoice'] : '';
$username = isset($_GET['username']) ? $_GET['username'] : '';

// Base SQL query
$sql = "select p.id, part_number as sku, name, quantity as qty, buy_price as price from products p WHERE 1=1";

// Execute the query
$data = $db->query($sql);

?>
<?php include_once('layouts/header.php'); ?>

<div class="row">
  <div class="col-md-12">
    <?php echo display_msg($msg); ?>
  </div>
</div>
<div class="row">
  <div class="col-md-12">
    <div class="panel panel-default">
      <div class="panel-heading clearfix">
        <strong>
          <span class="glyphicon glyphicon-th"></span>
          <span>List Product - <?php echo !empty($_GET['wh_id']) ? getWarehouseByID($_GET['wh_id']) : ""; ?></span>
        </strong>
      </div>
      <div class="panel-body">
        <div id="filter" style="margin-bottom: 10px;">
          <?php
          $user = current_user();
          $conditionsStr = "";
          if ($user['user_level'] != 1 && $user['user_level'] != 2) {
            $conditionsStr = " where user_level = " . $user['user_level'];
          }
          $query = "SELECT zipcode, warehouse_id, warehouse_name, btn_class, user_level FROM warehouse{$conditionsStr}";
          $result = $db->query($query);
          if ($result) {
            while ($row = $result->fetch_assoc()) {
              echo "<a href='?wh_id={$row['warehouse_id']}' class='btn btn-sm {$row['btn_class']} mr-2'>{$row['warehouse_name']}</a>";
            }
          }
          ?>
        </div>
        <table id="orderTable" class="table table-bordered" style="width:100%;">
          <thead>
            <tr>
              <th class="text-center" style="width: 50px;">#</th>
              <th>Part Number</th>
              <th>Name</th>
              <th>Price</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            <?php
            $no = 1;
            foreach ($data as $row): ?>
              <tr>
                <td><?php echo $no++; ?></td>
                <td><?php echo $row['sku']; ?></td>
                <td><?php echo $row['name']; ?></td>
                <td><?php echo $row['price']; ?></td>
                <td>
                  <button class="btn btn-sm btn-warning open-modal" data-product-sku="<?php echo $row['sku']; ?>"
                    data-toggle="modal" data-target="#orderItemsModal">History</button>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<!-- modal detail order item -->
<div class="modal fade" id="orderItemsModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-fullscreen">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="orderItemsModalLabel">History - <span id="sku_modal"></span></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"
          style="right: 15px;top: 15px;position:absolute">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="form-group">
          <label for="warehouseFilter">Inventory</label>
          <select id="warehouseFilter" class="form-control">
            <option value="">All Inventory</option>
            <?php
            // Menampilkan etalase
            $query = "SELECT warehouse_id, tables, warehouse_name FROM warehouse";
            $result = $db->query($query);
            while ($row = $result->fetch_assoc()) {
              if (!empty($row['tables'])) { // Pastikan value tidak kosong
                echo "<option value='" . htmlspecialchars($row['tables']) . "' data-name='" . htmlspecialchars($row['warehouse_name'] . ' Etalase') . "'>Etalase " . htmlspecialchars($row['warehouse_name']) . "</option>";
              }
            }
            // Menampilkan utama
            $query = "SELECT warehouse_id, tables_wh, warehouse_name FROM warehouse";
            $result = $db->query($query);
            while ($row = $result->fetch_assoc()) {
              if (!empty($row['tables_wh'])) { // Pastikan value tidak kosong
                echo "<option value='" . htmlspecialchars($row['tables_wh']) . "'>Utama " . htmlspecialchars($row['warehouse_name']) . "</option>";
              }
            }
            ?>
          </select>
        </div>

        <div class="form-group">
          <label for="categoryFilter">Category</label>
          <select id="categoryFilter" class="form-control">
            <option value="">All Categories</option>
            <option value="MOVE">MOVE</option>
            <option value="SALE">SALE</option>
            <option value="COUNT">COUNT</option>
            <option value="OTHER">OTHER</option>
          </select>
        </div>
        <table class="table table-bordered" id="historyTable">
          <thead>
            <tr>
              <th>No</th>
              <th>Part Number</th>
              <th>Warehouse</th>
              <th>Status</th>
              <th>Qty Change</th>
              <th>Prev Qty</th>
              <th>New Qty</th>
              <th>Reason</th>
              <th>Category</th>
              <th>Created By</th>
              <th>Created At</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
<script>
  $(document).ready(function() {
    // Initialize DataTable with options to disable sorting on the filter row
    var table = $('#orderTable').DataTable({
      "paging": true,
      "pageLength": 1000, // Default rows per page
      "lengthMenu": [
        [10, 100, 1000, -1],
        [10, 100, 1000, "All"]
      ],
      "searching": true,
      "info": true
    });
    $('#checkAll').on('change', function() {
      const isChecked = this.checked;
      // Select/Deselect all checkboxes in the DataTable
      table.$('.order-checkbox').prop('checked', isChecked);
    });

    // Sync the "Select All" checkbox with individual checkboxes
    $('#orderTable tbody').on('change', '.order-checkbox', function() {
      if ($('.order-checkbox:checked').length === $('.order-checkbox').length) {
        $('#checkAll').prop('checked', true);
      } else {
        $('#checkAll').prop('checked', false);
      }
    });

    $('.open-modal').on('click', function() {
      var partNumber = $(this).data('product-sku');
      $('#sku_modal').text(partNumber);
      // Destroy existing DataTable if it exists
      if ($.fn.dataTable.isDataTable('#historyTable')) {
        $('#historyTable').DataTable().clear().destroy();
      }
      // Initialize DataTable
      var table = $('#historyTable').DataTable({
        ajax: {
          url: `api_get_stock_history.php?part_number=${partNumber}&warehouse_id=<?php echo !empty($_GET['wh_id']) ? $_GET['wh_id'] : 0; ?>`,
          dataSrc: 'data',
          data: function(d) {
            d.page = (d.start / d.length) + 1; // Calculate page number
            d.length = d.length; // Data length
            d.warehouse = $('#warehouseFilter').val(); // Get warehouse filter value
            d.category = $('#categoryFilter').val(); // Get category filter value
          }
        },
        serverSide: true,
        processing: true,
        autoWidth: false,
        columns: [{
            data: null,
            render: function(data, type, row, meta) {
              return meta.row + meta.settings._iDisplayStart + 1;
            }
          },
          {
            data: 'part_number'
          },
          {
            data: 'warehouse'
          },
          {
            data: 'status'
          },
          {
            data: 'qty_change'
          },
          {
            data: 'prev_qty'
          },
          {
            data: 'new_qty'
          },
          {
            data: 'reason'
          },
          {
            data: 'category'
          },
          {
            data: 'created_by'
          },
          {
            data: 'created_at'
          }
        ]
      });
      $('#warehouseFilter, #categoryFilter').on('change', function() {
        table.ajax.reload(); // Reload the DataTable with the new filter values
      });
    });
  });
</script>
<?php include_once('layouts/footer.php'); ?>