<?php
session_start();
if (!isset($_SESSION['username'])) {
    echo "Access denied";
    exit();
}
require_once "db.php";

if (!isset($_GET['id'])) {
    echo "Invalid request";
    exit();
}

$sale_id = intval($_GET['id']);

// Fetch sale
$stmt = $conn->prepare("SELECT * FROM sales WHERE sale_id = ?");
$stmt->bind_param("i", $sale_id);
$stmt->execute();
$sale = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$sale) {
    echo "Sale not found";
    exit();
}

// Fetch sale items
$stmt = $conn->prepare("SELECT * FROM sale_items WHERE sale_id = ?");
$stmt->bind_param("i", $sale_id);
$stmt->execute();
$items = $stmt->get_result();
$stmt->close();

// Fetch customers
$customers = $conn->query("SELECT customer_id, customer_name FROM customers ORDER BY customer_name ASC");
?>

<style>
.edit-modal-container {
  width: 100%;
  padding: 15px;
}

.edit-modal-container input, 
.edit-modal-container select {
  width: 100%;
  padding: 6px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.edit-modal-container .btn {
  padding: 7px 14px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  background: #2563eb;
  color: #fff;
}

.edit-modal-container .btn-danger {
  background: #dc2626;
}

.table-container {
  overflow-x: auto;
  margin-top: 10px;
}

.table-container table {
  width: 100%;
  border-collapse: collapse;
}

.table-container th, .table-container td {
  border: 1px solid #ddd;
  padding: 6px;
  text-align: left;
}

.summary {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-top: 12px;
}

.summary div {
  flex: 1;
  min-width: 150px;
}

.scroll-select {
  max-height: 200px;
  overflow-y: auto;
}

.searchable-select {
  position: relative;
}

.searchable-select input.search-box {
  width: 100%;
  padding: 6px;
  border: 1px solid #aaa;
  border-radius: 4px;
  margin-bottom: 5px;
}
</style>

<div class="edit-modal-container">
  <h3 style="margin-bottom:12px;">Edit Sale</h3>

  <form id="saleEditForm" method="POST" action="sale_update.php">
    <input type="hidden" name="sale_id" value="<?php echo $sale_id; ?>">
    <input type="hidden" id="deleted_item_ids" name="deleted_item_ids" value="">

    <div style="display:flex;gap:10px;flex-wrap:wrap;">
      <div style="flex:1;">
        <label>Customer</label>
        <div class="searchable-select">
          <input type="text" class="search-box" placeholder="Search customer...">
          <select name="customer_id" required class="scroll-select">
            <?php while($c = $customers->fetch_assoc()): ?>
              <option value="<?php echo $c['customer_id']; ?>" <?php if($sale['customer_id']==$c['customer_id']) echo "selected"; ?>>
                <?php echo htmlspecialchars($c['customer_name']); ?>
              </option>
            <?php endwhile; ?>
          </select>
        </div>
      </div>
      <div style="width:200px;">
        <label>Date</label>
        <input type="date" name="sale_date" required value="<?php echo htmlspecialchars($sale['sale_date']); ?>">
      </div>
    </div>

    <div class="table-container">
      <table id="editItemsTable">
        <thead>
          <tr>
            <th style="width:35%">Product</th>
            <th style="width:10%">Size</th>
            <th style="width:12%">Rate</th>
            <th style="width:10%">Qty</th>
            <th style="width:14%">Subtotal</th>
            <th style="width:10%">Action</th>
          </tr>
        </thead>
        <tbody>
          <?php while($item = $items->fetch_assoc()): ?>
          <tr>
            <td>
              <input type="hidden" name="item_id[]" value="<?php echo $item['sale_item_id']; ?>">
              <input type="text" name="product[]" required value="<?php echo htmlspecialchars($item['product']); ?>">
            </td>
            <td><input type="text" name="size[]" value="<?php echo htmlspecialchars($item['size']); ?>"></td>
            <td><input type="number" name="rate[]" class="rate" min="0" step="0.01" value="<?php echo $item['rate']; ?>"></td>
            <td><input type="number" name="qty[]" class="qty" min="0" value="<?php echo $item['qty']; ?>"></td>
            <td><input type="text" name="subtotal[]" class="subtotal" readonly value="<?php echo number_format($item['subtotal'], 2); ?>"></td>
            <td><button type="button" class="btn btn-danger" onclick="removeRow(this)">Remove</button></td>
          </tr>
          <?php endwhile; ?>
        </tbody>
      </table>
    </div>

    <div style="margin-top:10px;">
      <button type="button" class="btn" onclick="addRow()">+ Add Product</button>
    </div>

    <div class="summary">
      <div>Total: ৳ <input type="text" id="editTotal" name="total" readonly></div>
      <div>Paid: ৳ <input type="number" id="editPaid" name="paid" step="0.01" min="0" value="<?php echo $sale['paid']; ?>"></div>
      <div>Due: ৳ <input type="text" id="editDue" name="due" readonly></div>
    </div>

    <div style="margin-top:15px;">
      <button type="submit" class="btn">Update Sale</button>
    </div>
  </form>
</div>

<script>
(function(){
  const tbody = document.querySelector('#editItemsTable tbody');
  const deletedIds = [];

  function calculateTotals(){
    let total = 0;
    tbody.querySelectorAll('tr').forEach(row => {
      const rate = parseFloat(row.querySelector('.rate')?.value || 0);
      const qty = parseFloat(row.querySelector('.qty')?.value || 0);
      const subtotal = rate * qty;
      row.querySelector('.subtotal').value = subtotal.toFixed(2);
      total += subtotal;
    });
    document.getElementById('editTotal').value = total.toFixed(2);
    const paid = parseFloat(document.getElementById('editPaid').value || 0);
    const due = Math.max(total - paid, 0);
    document.getElementById('editDue').value = due.toFixed(2);
  }

  document.getElementById('editPaid').addEventListener('input', calculateTotals);
  tbody.addEventListener('input', e => {
    if (e.target.classList.contains('rate') || e.target.classList.contains('qty')) {
      calculateTotals();
    }
  });

  window.addRow = function() {
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td><input type="hidden" name="item_id[]" value=""><input type="text" name="product[]" required></td>
      <td><input type="text" name="size[]"></td>
      <td><input type="number" name="rate[]" class="rate" step="0.01" min="0" value="0"></td>
      <td><input type="number" name="qty[]" class="qty" min="0" value="0"></td>
      <td><input type="text" name="subtotal[]" class="subtotal" readonly value="0.00"></td>
      <td><button type="button" class="btn btn-danger" onclick="removeRow(this)">Remove</button></td>
    `;
    tbody.appendChild(tr);
  };

  window.removeRow = function(btn){
    const row = btn.closest('tr');
    const id = row.querySelector('input[name="item_id[]"]').value;
    if (id) deletedIds.push(id);
    document.getElementById('deleted_item_ids').value = deletedIds.join(',');
    row.remove();
    calculateTotals();
  };

  // Customer search filter
  const searchBox = document.querySelector('.search-box');
  const select = document.querySelector('select[name="customer_id"]');
  searchBox.addEventListener('input', () => {
    const filter = searchBox.value.toLowerCase();
    Array.from(select.options).forEach(opt => {
      opt.style.display = opt.text.toLowerCase().includes(filter) ? '' : 'none';
    });
  });

  calculateTotals();
})();
</script>
