<?php
// Include load.php untuk memuat file-file yang diperlukan
$page_title = 'Etalase Online';
require_once('includes/load.php');
page_require_level(3); // Memastikan level akses sesuai

// Variabel untuk pencarian
$search_query = "";
$search_option = "";

// Meng-handle pengiriman form pencarian
if (isset($_POST['search'])) {
    $search_query = $_POST['search_query'];
    $search_option = $_POST['search_option'];
    // Mencari produk online berdasarkan kriteria
    $online_products = search_online_products($search_query, $search_option);
} else {
    // Pengaturan pagination
    $per_page = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 200;
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    // Mengambil semua produk online tanpa pagination
    $online_products = get_all_online_products();
}

//sudah gunakan cron job per 1 menit api_update_stok_bundling.php
// // Mengambil produk bundling
// $bundling_products = get_bundling_products();

// // Memperbarui kuantitas produk berdasarkan bundling
// foreach ($bundling_products as $bundling_product) {
//     $bundling_code = $bundling_product['part_number'];
//     $bundling_quantity = $bundling_product['quantity'];
//     $bundling_details = get_bundling_details($bundling_code);

//     foreach ($bundling_details as $detail) {
//         $part_number = $detail['part_number'];
//         $quantity_to_deduct = $detail['quantity'] * $bundling_quantity;

//         // Mengambil kuantitas saat ini dari produk dengan part_number di online_products
//         $sql = "SELECT quantity FROM online_products WHERE part_number = '{$part_number}'";
//         $result = find_by_sql($sql);
//         if (!empty($result)) {
//             $current_quantity = $result[0]['quantity'];
//             $new_quantity = $current_quantity + $quantity_to_deduct;
//             // Memperbarui kuantitas di online_products
//             update_online_product_quantity_bundling($part_number, $new_quantity);
//         }
//     }

//     // Set kuantitas produk bundling menjadi 0 jika negatif
//     if ($bundling_quantity < 0) {
//         update_online_product_quantity_bundling($bundling_code, 0);
//     }
// }
?>

<?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">
        <div class="pull-left">
          <h2>Etalase Online</h2>
        </div>
        <div class="pull-right">
          <!-- Form Pencarian -->
          <form action="online_product.php" method="post" class="form-inline">
            <div class="form-group">
              <input type="text" class="form-control" name="search_query" placeholder="Cari"
                value="<?php echo htmlspecialchars($search_query); ?>">
            </div>
            <div class="form-group">
              <select class="form-control" name="search_option">
                <option value="name" <?php if ($search_option == 'name') echo 'selected'; ?>>Product Name</option>
                <option value="part_number" <?php if ($search_option == 'part_number') echo 'selected'; ?>>Part Number
                </option>
              </select>
            </div>
            <button type="submit" name="search" class="btn btn-primary">Cari</button>
          </form>

          <!-- Tombol Export ke Excel -->
          <button type="button" class="btn btn-success ml-2" id="exportExcelBtn">Export Excel</button>

          <!-- Tombol Menuju Stock Taking -->
          <a href="stock_taking_product_online.php" class="btn btn-info ml-2">Stock Taking</a>
        </div>
      </div>

      <div class="panel-body">
        <!-- Tabel Produk Online -->
        <div class="table-responsive">
          <table class="table table-bordered">
            <thead>
              <tr>
                <th class="text-center">#</th>
                <th>Part Number</th>
                <th>Name</th>
                <th class="text-center">In Stock</th>
                <th class="text-center">UoM</th>
                <th class="text-center">Unit Price</th>
                <th class="text-center">Location</th>
                <th class="text-center">Action</th> <!-- Kolom untuk aksi -->
              </tr>
            </thead>
            <tbody>
              <?php foreach ($online_products as $online_product) : ?>
              <tr>
                <td class="text-center"><?php echo count_id(); ?></td>
                <td>
                  <?php echo isset($online_product['part_number']) ? htmlspecialchars($online_product['part_number']) : 'N/A'; ?>
                </td>
                <td><?php echo remove_junk($online_product['name']); ?></td>
                <td class="text-center"><?php echo $online_product['quantity']; ?></td>
                <td class="text-center"><?php echo remove_junk($online_product['UoM']); ?></td>
                <td class="text-center"><?php echo remove_junk($online_product['buy_price']); ?></td>
                <td class="text-center"><?php echo remove_junk($online_product['loc_id']); ?></td>
                <td class="text-center">
                  <!-- Tombol Edit -->
                  <a href="edit_online_product.php?part_number=<?php echo urlencode($online_product['part_number']); ?>"
                    class="btn btn-warning btn-sm">Edit</a>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <!-- Akhir Tabel Produk Online -->
      </div>
    </div>
  </div>
</div>
<script>
document.getElementById('exportExcelBtn').addEventListener('click', function() {
  var wb = XLSX.utils.table_to_book(document.querySelector('.table'));
  var wbout = XLSX.write(wb, {
    bookType: 'xlsx',
    bookSST: true,
    type: 'binary'
  });

  function s2ab(s) {
    var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
  }

  saveAs(new Blob([s2ab(wbout)], {
    type: 'application/octet-stream'
  }), 'export.xlsx');
});
</script>

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