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

if (!isset($_GET['id'])) exit('Invalid purchase ID');
$purchase_id = intval($_GET['id']);

// Fetch purchase
$stmt = $conn->prepare("SELECT * FROM purchases WHERE purchase_id=?");
$stmt->bind_param("i",$purchase_id);
$stmt->execute();
$purchase = $stmt->get_result()->fetch_assoc();
if (!$purchase) exit('Purchase not found');

// Fetch suppliers
$suppliers = $conn->query("SELECT supplier_id, supplier_name FROM suppliers ORDER BY supplier_name ASC");

// Fetch purchase items
$stmtItems = $conn->prepare("SELECT * FROM purchase_items WHERE purchase_id=?");
$stmtItems->bind_param("i",$purchase_id);
$stmtItems->execute();
$items = $stmtItems->get_result();
?>
<style>

table{width:100%;border-collapse:collapse;margin-bottom:12px;}
table th, table td{border:1px solid #e6edf3;padding:8px;text-align:left;}
input[type="text"], input[type="number"], select{width:100%;padding:6px;border:1px solid #ccc;border-radius:4px;}
select{
  padding: 11px;
}

.summary{display:flex;gap:12px;flex-wrap:wrap;margin-top:8px;}
.summary div{flex:1;min-width:120px;}
</style>

<div class="modal-header">
  <h3>Edit Purchase</h3>
</div>
<div class="modal-body">
<form id="editPurchaseForm" method="post" action="purchase_update.php">
<input type="hidden" name="purchase_id" value="<?php echo $purchase_id;?>">

<div class="form-row">
  <div class="form-group">
    <label>Supplier</label>
    <select name="supplier" required>
      <?php while($s = $suppliers->fetch_assoc()): ?>
      <option value="<?php echo $s['supplier_id'];?>" <?php if($purchase['supplier_id']==$s['supplier_id']) echo "selected";?>><?php echo htmlspecialchars($s['supplier_name']);?></option>
      <?php endwhile;?>
    </select>
  </div>
  <div class="form-group">
    <label>Purchase Date</label>
    <input type="date" name="purchase_date" value="<?php echo $purchase['purchase_date'];?>" required>
  </div>
</div>

<table id="editItemsTable">
<thead>
<tr>
<th>Product</th>
<th>Size</th>
<th>Rate</th>
<th>Qty</th>
<th>Subtotal</th>
</tr>
</thead>
<tbody>
<?php while($item = $items->fetch_assoc()): ?>
<tr>
<td><input type="text" name="product[]" value="<?php echo htmlspecialchars($item['product']);?>" required></td>
<td><input type="text" name="size[]" value="<?php echo htmlspecialchars($item['size']);?>"></td>
<td><input type="number" name="rate[]" class="rate" step="0.01" min="0" 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 $item['subtotal'];?>"></td>
</tr>
<?php endwhile;?>
</tbody>
</table>

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

<div class="edit-purchase-modal-submit-btn">
<button type="submit" class="btn">Save Purchase</button>
</div>
</form>
</div>

<script>
// Calculate totals and due live
function calculateEditTotals() {
    let total = 0;

    // Loop through each product row
    document.querySelectorAll('#editItemsTable tbody tr').forEach(row => {
        const rateEl = row.querySelector('.rate');
        const qtyEl  = row.querySelector('.qty');
        const subEl  = row.querySelector('.subtotal');

        const rate = parseFloat(rateEl.value) || 0;
        const qty  = parseInt(qtyEl.value) || 0;
        const subtotal = rate * qty;

        // Update subtotal in the row
        subEl.value = subtotal.toFixed(2);
        total += subtotal;
    });

    // Update total
    document.getElementById('editTotal').value = total.toFixed(2);

    // Calculate due based on paid
    const paid = parseFloat(document.getElementById('editPaid').value) || 0;
    let due = total - paid;
    if(due < 0) due = 0;
    document.getElementById('editDue').value = due.toFixed(2);
}

// Attach event listeners
function bindEditEvents() {
    const tbody = document.querySelector('#editItemsTable tbody');

    // Event delegation for rate and qty inputs
    tbody.addEventListener('input', function(e) {
        if(e.target.matches('.rate') || e.target.matches('.qty')) {
            calculateEditTotals();
        }
    });

    // Paid input live update
    document.getElementById('editPaid').addEventListener('input', calculateEditTotals);
}


// Initialize live calculation
bindEditEvents();
calculateEditTotals(); // calculate totals on modal load

</script>