<?php
require_once('includes/load.php');
page_require_level(3);

$bundling_code = isset($_GET['bundling_code']) ? urldecode(remove_junk($db->escape($_GET['bundling_code']))) : '';

if (empty($bundling_code)) {
  echo '<p class="text-danger">Missing bundling code.</p>';
  exit;
}

// Fungsi untuk mendapatkan detail paket bundling berdasarkan bundling_code
function get_bundling_details_views($bundling_code)
{
  global $db;
  $sql  = "SELECT pb.id, pb.part_number, pb.quantity, pb.date_active, p.name
             FROM paket_bundling pb
             LEFT JOIN products p ON p.part_number = pb.part_number
             WHERE pb.bundling_code = '{$bundling_code}'";
  return find_by_sql($sql);
}

// Mendapatkan detail bundling
$bundling_details = get_bundling_details_views($bundling_code);

global $db;
$products = find_by_sql('SELECT part_number, name FROM products');
$product_json = json_encode(array_column($products, 'name', 'part_number'));
?>

<?php if ($bundling_details): ?>
  <form id="save-bundling-form" method="POST">
    <input type="hidden" name="bundling_code" value="<?= htmlspecialchars($bundling_code) ?>">

    <table class="table table-bordered" id="bundling-table">
      <thead>
        <tr>
          <th>Part Number</th>
          <th>Quantity</th>
          <th>Date Active</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($bundling_details as $detail): ?>
          <tr data-id="<?= $detail['id'] ?>">
            <td>
              <select name="part_number[]" class="form-control select2-new">
                <option value="">-- Select Part Number --</option>
                <?php foreach ($products as $product): ?>
                  <option value="<?= $product['part_number'] ?>" <?= $product['part_number'] == $detail['part_number'] ? 'selected' : '' ?>>
                    <?= $product['part_number'] ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </td>
            <td>
              <input type="number" class="form-control" name="quantity[]" value="<?= (int)$detail['quantity'] ?>" min="1" />
            </td>
            <td>
              <input type="date" class="form-control" name="date_active[]" value="<?= htmlspecialchars($detail['date_active']) ?>" />
            </td>
            <td>
              <button type="button" class="btn btn-danger btn-remove-row">Delete</button>
            </td>
            <input type="hidden" name="id[]" value="<?= $detail['id'] ?? '' ?>">
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  <?php else: ?>
    <form id="save-bundling-form" method="POST">
      <input type="hidden" name="bundling_code" value="<?= htmlspecialchars($bundling_code) ?>">

      <p class="text-warning">No details found for this bundling code.</p>

      <table class="table table-bordered" id="bundling-table">
        <thead>
          <tr>
            <th>Part Number</th>
            <th>Quantity</th>
            <th>Date Active</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
    <?php endif; ?>

    <!-- Template row (hidden) -->
    <table style="display:none;">
      <tbody>
        <tr class="template-row">
          <td>
            <select name="part_number[]" class="form-control select2-new">
              <option value="">-- Select Part Number --</option>
              <?php foreach ($products as $product): ?>
                <option value="<?= htmlspecialchars($product['part_number']) ?>">
                  <?= htmlspecialchars($product['part_number']) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </td>
          <td><input type="number" class="form-control" name="quantity[]" min="1" /></td>
          <td><input type="date" class="form-control" name="date_active[]" /></td>
          <td><button type="button" class="btn btn-danger btn-remove-row">Delete</button></td>
        </tr>
      </tbody>
    </table>

    <div class="d-flex gap-2 mt-3">
      <button type="button" class="btn btn-secondary" id="add-row">+ Add Row</button>
      <button type="submit" class="btn btn-primary">Save All</button>
    </div>
    </form>

    <script>
      window.partNameMap = <?= $product_json ?>;

      // Add new row
      $('#add-row').click(function() {
        const $row = $('.template-row').clone().removeClass('template-row').show();

        // Cleanup old Select2 UI
        const $select = $row.find('select.select2-new');
        $select
          .val('')
          .removeAttr('data-select2-id tabindex aria-hidden')
          .removeClass('select2-hidden-accessible')
          .next('.select2').remove();

        // Initialize with correct parent (inside modal!)
        $select.select2({
          dropdownParent: $('#bundlingDetailsModal'),
          width: '100%'
        });

        $('#bundling-table tbody').append($row);
      });


      // Bootbox delete confirmation
      $(document).on('click', '.btn-remove-row', function() {
        const $row = $(this).closest('tr');
        const itemId = $row.data('id');
        const partNumber = $row.find('select[name="part_number[]"]').val() || '(unsaved)';

        if (itemId) {
          bootbox.confirm({
            title: "Confirm Delete",
            message: `Are you sure you want to delete part number <strong>${partNumber}</strong>?`,
            buttons: {
              confirm: {
                label: 'Yes',
                className: 'btn-danger'
              },
              cancel: {
                label: 'Cancel',
                className: 'btn-secondary'
              }
            },
            callback: function(result) {
              if (result) {
                $.ajax({
                  url: 'delete_bundling_detail.php',
                  method: 'POST',
                  data: {
                    id: itemId
                  },
                  success: function(res) {
                    try {
                      const response = JSON.parse(res);
                      if (response.success) {
                        $row.remove();
                      } else {
                        bootbox.alert("Failed to delete item.");
                      }
                    } catch (e) {
                      bootbox.alert("Unexpected error.");
                    }
                  },
                  error: function() {
                    bootbox.alert("AJAX error occurred.");
                  }
                });
              }
            }
          });
        } else {
          // Unsaved row: just remove
          $row.remove();
        }
      });

      // Handle form submission via AJAX
      $('#save-bundling-form').on('submit', function(e) {
        e.preventDefault();
        const formData = new FormData(this);

        $.ajax({
          url: 'save_bundling_details.php',
          method: 'POST',
          data: formData,
          processData: false,
          contentType: false,
          success: function(res) {
            try {
              const response = JSON.parse(res);
              if (response.success) {
                bootbox.alert("Saved successfully!", function() {
                  // Optionally reload the modal or refresh data
                  $('#bundlingDetailsModal').modal('hide');
                });
              } else {
                bootbox.alert("Failed to save: " + (response.error || 'Unknown error'));
              }
            } catch (e) {
              bootbox.alert("Unexpected error.");
            }
          },
          error: function() {
            bootbox.alert("AJAX error while saving.");
          }
        });
      });
    </script>