<?php
$page_title = 'Stok Opname Etalase';
require_once('includes/load.php');


if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['inventory'])) {
  global $db;

  // Mulai transaksi
  $db->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);

  try {
    // Menyimpan informasi umum
    $inventory = $_POST['inventory'];
    $id_inventory = $_POST['id_inventory'];
    $name_inventory = $_POST['name_inventory'];
    $reason = isset($_POST['reason']) ? $_POST['reason'] : 'No reason in stok opname';

    // Memproses setiap baris data produk
    $part_numbers = $_POST['part_number'];
    $quantities = $_POST['quantity'];
    $statuses = $_POST['status'];

    // Loop setiap baris yang diisi
    for ($i = 0; $i < count($part_numbers); $i++) {
      $part_number = $part_numbers[$i];
      $quantity = (int)$quantities[$i];
      $status = $statuses[$i];

      // Memperbarui stok
      if ($status == 'IN') {
        $sql = "UPDATE {$inventory} SET quantity = quantity + {$quantity} WHERE part_number = '{$part_number}'";
      } else {
        $sql = "UPDATE {$inventory} SET quantity = quantity - {$quantity} WHERE part_number = '{$part_number}'";
      }

      // Eksekusi query
      if (!$db->query($sql)) {
        throw new Exception("Error updating inventory: " . $db->error);
      }
      $user = current_user();
      $created_by = $user['name'] ?? "System";
      // Menyimpan riwayat stok
      $historyQuery = "INSERT INTO stock_history (part_number, warehouse, status, qty_change, prev_qty, new_qty, transfer_id, from_warehouse_id, to_warehouse_id, reason, category, created_by)
                           VALUES (
                               '{$part_number}', 
                               '{$name_inventory}', 
                               '{$status}', 
                               {$quantity}, 
                               (SELECT quantity FROM {$inventory} WHERE part_number = '{$part_number}'), 
                               (SELECT quantity + {$quantity} FROM {$inventory} WHERE part_number = '{$part_number}'), 
                               4, 
                               '{$id_inventory}', 
                               '0', 
                               '{$reason}', 
                               'COUNT', 
                               '{$created_by}'
                           )";

      // Eksekusi insert riwayat
      if (!$db->query($historyQuery)) {
        throw new Exception("Error inserting stock history: " . $db->error);
      }
    }

    // Commit transaksi
    $db->commit();
    $session->msg('s', "Stok Opname berhasil untuk semua part number!!");
  } catch (Exception $e) {
    // Rollback transaksi jika ada yang salah
    $db->rollback();
    $session->msg('d', "Transaksi gagal: " . $e->getMessage());
  }

  redirect('management_stok.php', false);
}

?>
<?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>
          Stok Opname
        </strong>
      </div>
      <div class="panel-body">
        <form method="POST" action="" class="form-horizontal">
          <div class="form-group">
            <label for="inventory" class="col-sm-2 control-label">Inventory:</label>
            <div class="col-sm-10">
              <input type="hidden" value="" id="id_inventory" name="id_inventory">
              <input type="hidden" value="" id="name_inventory" name="name_inventory">
              <select name="inventory" id="inventoryID" class="form-control" onchange="updateHiddenInput()">
                <option value="">Pilih 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') . "' data-id='" . $row['warehouse_id'] . "'>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']) . "' data-name='" . htmlspecialchars($row['warehouse_name']) . "' data-id='" . $row['warehouse_id'] . "'>Utama " . htmlspecialchars($row['warehouse_name']) . "</option>";
                  }
                }
                ?>
              </select>
            </div>
          </div>
          <div class="form-group">
            <label for="reason" class="col-sm-2 control-label">Alasan:</label>
            <div class="col-sm-10">
              <textarea class="form-control" name="reason"></textarea>
            </div>
          </div>
          <button type="button" class="btn btn-success" id="addRow">+</button>


          <table class="table table-bordered table-striped" id="inventoryTable">
            <thead>
              <tr class="active">
                <th style="width: 400px;">Part Number</th>
                <th>Status</th>
                <th>Quantity</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>
                  <select name="part_number[]" class="form-control part_number box" required>
                    <option value="">Pilih Part Number</option>
                  </select>
                </td>
                <td>
                  <select name="status[]" class="form-control" required>
                    <option value="IN">+</option>
                    <option value="OUT">-</option>
                  </select>
                </td>
                <td>
                  <input type="number" class="form-control" name="quantity[]" required>
                </td>
                <td>
                  <button type="button" class="btn btn-danger remove-row">Hapus</button>
                </td>
              </tr>
            </tbody>
          </table>

          <button type="submit" class="btn btn-primary ml-1">Submit</button>
        </form>
      </div>
    </div>
  </div>
</div>


<script>
  // JavaScript for adding and removing rows
  document.getElementById('addRow').addEventListener('click', function() {
    var table = document.getElementById('inventoryTable').getElementsByTagName('tbody')[0];
    var newRow = table.insertRow(table.rows.length);

    // Part Number Column
    var cell1 = newRow.insertCell(0);
    cell1.innerHTML = '<select name="part_number[]" class="form-control part_number box" required>' +
      '<option value="">Pilih Part Number</option>' +
      '</select>';

    // Status Column
    var cell2 = newRow.insertCell(1);
    cell2.innerHTML = '<select name="status[]" class="form-control" required>' +
      '<option value="IN">+</option>' +
      '<option value="OUT">-</option>' +
      '</select>';

    // Quantity Column
    var cell3 = newRow.insertCell(2);
    cell3.innerHTML = '<input type="number" class="form-control" name="quantity[]" required>';

    // Action Column
    var cell4 = newRow.insertCell(3);
    cell4.innerHTML = '<button type="button" class="btn btn-danger remove-row">Hapus</button>';

    // Add event listener for the delete button
    newRow.querySelector('.remove-row').addEventListener('click', function() {
      table.deleteRow(newRow.rowIndex - 1);
    });

    // Initialize dynamic select for new row
    initializeDinamisSelect2($(cell1).find('.part_number'), {
      placeholder: 'Select a PartNumber',
      url: 'api-product-all.php', // Endpoint to fetch products
      idField: 'part_number',
      textField: 'part_number',
    });
  });

  // Event listener for existing remove buttons
  document.querySelectorAll('.remove-row').forEach(function(button) {
    button.addEventListener('click', function() {
      var row = this.closest('tr');
      row.parentNode.removeChild(row);
    });
  });

  function updateHiddenInput() {
    var selectElement = document.getElementById('inventoryID');
    var selectedOption = selectElement.options[selectElement.selectedIndex];
    var hiddenInput = document.getElementById('name_inventory');
    var IDInventory = document.getElementById('id_inventory');
    hiddenInput.value = selectedOption.getAttribute('data-name');
    IDInventory.value = selectedOption.getAttribute('data-id');
  }

  $(document).ready(function() {
    initializeDinamisSelect2($('.part_number'), {
      placeholder: 'Select a PartNumber',
      url: 'api-product-all.php', // Endpoint to fetch products
      idField: 'part_number',
      textField: 'part_number',
    });
  });
</script>

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