<div class="page-header">
    <div>
        <a href="<?= APP_URL ?>/sales" class="btn btn-ghost btn-sm mb-4" style="padding-left:0;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>
            Back to Sales
        </a>
        <h1>Edit Sale: <?= e($sale['sale_no']) ?></h1>
    </div>
</div>

<div class="card">
    <div class="p-6">
        <div class="alert alert-warning mb-6">
            <strong>Warning:</strong> Editing a sale will affect your financial records and stock levels. Please ensure you have proper authorization before making changes.
        </div>

        <form action="<?= APP_URL ?>/sales/<?= $sale['id'] ?>/update" method="POST">
            <?= Security::csrfField() ?>

            <div class="form-row mb-4">
                <div>
                    <label class="form-label">Customer</label>
                    <input type="text" class="form-control" value="<?= e($sale['customer_name'] ?? 'Walk-in Customer') ?>" readonly>
                </div>
                <div>
                    <label class="form-label">Location</label>
                    <input type="text" class="form-control" value="<?= e($sale['location_name'] ?? 'N/A') ?>" readonly>
                </div>
            </div>

            <div class="mb-6">
                <label class="form-label mb-3">Sale Items</label>
                <div class="table-wrapper">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Product</th>
                                <th class="text-right">Unit Price</th>
                                <th class="text-center">Quantity</th>
                                <th class="text-right">Total</th>
                                <th class="text-center">Action</th>
                            </tr>
                        </thead>
                        <tbody id="items-table">
                            <?php foreach ($sale['items'] as $idx => $item): ?>
                            <tr data-item-id="<?= $item['id'] ?>">
                                <td>
                                    <div style="font-weight:600;"><?= e($item['product_name']) ?></div>
                                    <div style="font-size:0.75rem; color:var(--text-muted)">SKU: <?= e($item['sku']) ?></div>
                                    <input type="hidden" name="items[<?= $idx ?>][id]" value="<?= $item['id'] ?>">
                                    <input type="hidden" name="items[<?= $idx ?>][product_id]" value="<?= $item['product_id'] ?>">
                                    <input type="hidden" name="items[<?= $idx ?>][batch_id]" value="<?= $item['batch_id'] ?? '' ?>">
                                </td>
                                <td>
                                    <input type="number" name="items[<?= $idx ?>][unit_price]" class="form-control text-right" 
                                           value="<?= $item['unit_price'] ?>" step="0.01" min="0"
                                           onchange="updateItemTotal(<?= $idx ?>)">
                                </td>
                                <td>
                                    <input type="number" name="items[<?= $idx ?>][quantity]" class="form-control text-center" 
                                           value="<?= $item['quantity'] ?>" step="0.01" min="0"
                                           onchange="updateItemTotal(<?= $idx ?>)">
                                </td>
                                <td class="text-right">
                                    <span id="total-<?= $idx ?>"><?= money($item['unit_price'] * $item['quantity']) ?></span>
                                </td>
                                <td class="text-center">
                                    <button type="button" class="btn btn-ghost btn-sm text-red-600" onclick="removeItem(this)">
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;height:16px;"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>
                                    </button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="3" class="text-right font-bold">Subtotal:</td>
                                <td class="text-right font-bold" id="subtotal-display"><?= money($sale['subtotal']) ?></td>
                                <td></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>

            <div class="form-row mb-4">
                <div>
                    <label class="form-label">Tax Amount</label>
                    <input type="number" name="tax_amount" class="form-control" value="<?= $sale['tax_amount'] ?? 0 ?>" step="0.01" onchange="updateGrandTotal()">
                </div>
                <div>
                    <label class="form-label">Discount Amount</label>
                    <input type="number" name="discount_amount" class="form-control" value="<?= $sale['discount_amount'] ?? 0 ?>" step="0.01" onchange="updateGrandTotal()">
                </div>
            </div>

            <div class="form-row mb-4">
                <div>
                    <label class="form-label">Grand Total</label>
                    <input type="number" name="total" id="grand-total" class="form-control font-bold" value="<?= $sale['total'] ?>" step="0.01" readonly>
                </div>
                <div>
                    <label class="form-label">Amount Paid</label>
                    <input type="number" name="amount_paid" class="form-control" value="<?= $sale['amount_paid'] ?>" step="0.01">
                </div>
            </div>

            <div class="form-row mb-4">
                <div>
                    <label class="form-label">Payment Status</label>
                    <select name="payment_status" class="form-control">
                        <option value="paid" <?= $sale['payment_status'] == 'paid' ? 'selected' : '' ?>>Paid</option>
                        <option value="partial" <?= $sale['payment_status'] == 'partial' ? 'selected' : '' ?>>Partial</option>
                        <option value="pending" <?= $sale['payment_status'] == 'pending' ? 'selected' : '' ?>>Pending</option>
                        <option value="credit" <?= $sale['payment_status'] == 'credit' ? 'selected' : '' ?>>Credit</option>
                    </select>
                </div>
                <div>
                    <label class="form-label">Payment Method</label>
                    <select name="payment_method" class="form-control">
                        <option value="cash" <?= ($sale['payment_method'] ?? 'cash') == 'cash' ? 'selected' : '' ?>>Cash</option>
                        <option value="card" <?= ($sale['payment_method'] ?? 'cash') == 'card' ? 'selected' : '' ?>>Card</option>
                        <option value="transfer" <?= ($sale['payment_method'] ?? 'cash') == 'transfer' ? 'selected' : '' ?>>Transfer</option>
                        <option value="cheque" <?= ($sale['payment_method'] ?? 'cash') == 'cheque' ? 'selected' : '' ?>>Cheque</option>
                        <option value="other" <?= ($sale['payment_method'] ?? 'cash') == 'other' ? 'selected' : '' ?>>Other</option>
                    </select>
                </div>
            </div>

            <div class="form-row mb-4">
                <div>
                    <label class="form-label">Status</label>
                    <select name="status" class="form-control">
                        <option value="completed" <?= $sale['status'] == 'completed' ? 'selected' : '' ?>>Completed</option>
                        <option value="pending" <?= $sale['status'] == 'pending' ? 'selected' : '' ?>>Pending</option>
                        <option value="cancelled" <?= $sale['status'] == 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
                    </select>
                </div>
                <div></div>
            </div>

            <div class="form-group mb-4">
                <label class="form-label">Notes</label>
                <textarea name="notes" class="form-control" rows="3"><?= e($sale['notes'] ?? '') ?></textarea>
            </div>

            <div class="flex gap-2">
                <button type="submit" class="btn btn-primary">Update Sale</button>
                <a href="<?= APP_URL ?>/sales" class="btn btn-outline">Cancel</a>
            </div>
        </form>
    </div>
</div>

<script>
function updateItemTotal(idx) {
    const price = parseFloat(document.querySelector(`input[name="items[${idx}][unit_price]"]`).value) || 0;
    const qty = parseFloat(document.querySelector(`input[name="items[${idx}][quantity]"]`).value) || 0;
    const total = price * qty;
    document.getElementById(`total-${idx}`).textContent = formatCurrency(total);
    updateSubtotal();
}

function updateSubtotal() {
    let subtotal = 0;
    const rows = document.querySelectorAll('#items-table tr');
    rows.forEach(row => {
        const price = parseFloat(row.querySelector('input[name$="[unit_price]"]')?.value) || 0;
        const qty = parseFloat(row.querySelector('input[name$="[quantity]"]')?.value) || 0;
        subtotal += price * qty;
    });
    document.getElementById('subtotal-display').textContent = formatCurrency(subtotal);
    updateGrandTotal();
}

function updateGrandTotal() {
    const subtotal = parseCurrency(document.getElementById('subtotal-display').textContent);
    const tax = parseFloat(document.querySelector('input[name="tax_amount"]').value) || 0;
    const discount = parseFloat(document.querySelector('input[name="discount_amount"]').value) || 0;
    const total = subtotal - discount; // Inclusive tax: Total is just subtotal minus discount.
    document.getElementById('grand-total').value = total.toFixed(2);
}

function removeItem(btn) {
    if (confirm('Are you sure you want to remove this item?')) {
        const row = btn.closest('tr');
        row.remove();
        updateSubtotal();
    }
}

function formatCurrency(amount) {
    return '<?= setting('currency_symbol', 'GH₵') ?>' + amount.toFixed(2);
}

function parseCurrency(str) {
    return parseFloat(str.replace(/[^\d.-]/g, '')) || 0;
}
</script>
