<div class="page-header" style="margin-bottom: 16px;">
    <div>
        <h1 style="font-size: 1.4rem; margin-bottom: 4px;">Stock Purchases</h1>
        <div class="page-subtitle" style="font-size: 0.85rem;">Track incoming stock from suppliers and manage inventory costs.</div>
    </div>
    <div class="flex gap-2">
        <a href="<?= APP_URL ?>/purchases/create" class="btn btn-primary" style="padding: 6px 12px; font-size: 0.85rem;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width: 16px; height: 16px;"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
            Add Purchase
        </a>
    </div>
</div>

<div class="card mb-4" style="padding: 12px;">
    <div class="filter-bar">
        <form action="" method="GET" class="flex gap-2 flex-1">
            <div class="search-box">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width: 14px; height: 14px;"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
                <input type="text" name="search" class="form-control" placeholder="Search purchase no, supplier..." value="<?= e($_GET['search'] ?? '') ?>" style="padding: 6px 10px 6px 32px; font-size: 0.85rem;">
            </div>
            <button type="submit" class="btn btn-primary btn-sm" style="padding: 6px 12px; font-size: 0.85rem;">Search</button>
            <?php if (!empty($_GET['search'])): ?>
                <a href="<?= APP_URL ?>/purchases" class="btn btn-outline btn-sm" style="padding: 6px 12px; font-size: 0.85rem;">Clear</a>
            <?php endif; ?>
        </form>
    </div>

    <div class="table-wrapper" style="margin-top: 12px;">
        <table style="font-size: 0.85rem;">
            <thead>
                <tr>
                    <th style="padding: 8px 10px; font-size: 0.75rem;">Ref No</th>
                    <th style="padding: 8px 10px; font-size: 0.75rem;">Date</th>
                    <th style="padding: 8px 10px; font-size: 0.75rem;">Supplier</th>
                    <th style="padding: 8px 10px; font-size: 0.75rem;">Location</th>
                    <th style="padding: 8px 10px; font-size: 0.75rem;">Total</th>
                    <th style="padding: 8px 10px; font-size: 0.75rem;">Paid</th>
                    <th style="padding: 8px 10px; font-size: 0.75rem;">Status</th>
                    <th style="padding: 8px 10px; font-size: 0.75rem;">Payment</th>
                    <th style="width: 80px; padding: 8px 10px; font-size: 0.75rem;"></th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($purchases['data'])): ?>
                <tr>
                    <td colspan="9" class="text-center" style="padding: 24px 10px;">No purchases found.</td>
                </tr>
                <?php else: foreach ($purchases['data'] as $p): ?>
                <tr>
                    <td style="padding: 8px 10px;"><strong><?= e($p['purchase_no']) ?></strong></td>
                    <td style="padding: 8px 10px; font-size: 0.8rem;"><?= date('M j, Y', strtotime($p['created_at'])) ?></td>
                    <td style="padding: 8px 10px;"><?= e($p['supplier_name']) ?></td>
                    <td style="padding: 8px 10px;"><?= e($p['location_name']) ?></td>
                    <td style="padding: 8px 10px; font-weight: 600;"><?= money($p['total']) ?></td>
                    <td style="padding: 8px 10px; color: #16a34a;"><?= money($p['amount_paid']) ?></td>
                    <td style="padding: 8px 10px;">
                        <?php
                        $statusBadge = [
                            'received' => 'badge-success',
                            'pending'  => 'badge-warning',
                            'ordered'  => 'badge-info',
                            'cancelled' => 'badge-danger'
                        ];
                        $badge = $statusBadge[$p['status']] ?? 'badge-muted';
                        ?>
                        <span class="badge <?= $badge ?>" style="padding: 3px 6px; font-size: 0.7rem;"><?= ucfirst(e($p['status'])) ?></span>
                    </td>
                    <td style="padding: 8px 10px;">
                        <?php
                        $paymentBadge = [
                            'paid' => 'badge-success',
                            'partial' => 'badge-info',
                            'credit' => 'badge-info',
                            'due' => 'badge-danger'
                        ];
                        $paymentBadgeClass = $paymentBadge[$p['payment_status']] ?? 'badge-muted';
                        ?>
                        <span class="badge <?= $paymentBadgeClass ?>" style="padding: 3px 6px; font-size: 0.7rem;"><?= ucfirst(e($p['payment_status'])) ?></span>
                    </td>
                    <td class="text-right">
                        <div class="dropdown">
                            <button type="button" onclick="toggleRowDropdown(event, 'dropdown-<?= $p['id'] ?>')" class="btn btn-ghost btn-icon">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="1"></circle><circle cx="12" cy="5" r="1"></circle><circle cx="12" cy="19" r="1"></circle></svg>
                            </button>
                            <div id="dropdown-<?= $p['id'] ?>" class="dropdown-menu">
                                <a href="<?= APP_URL ?>/purchases/<?= $p['id'] ?>" class="dropdown-item">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
                                    View
                                </a>
                                <a href="<?= APP_URL ?>/purchases/<?= $p['id'] ?>/edit" class="dropdown-item">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></svg>
                                    Edit
                                </a>
                                <?php if ($p['payment_status'] === 'partial' || $p['payment_status'] === 'credit' || $p['payment_status'] === 'due'): ?>
                                <button type="button" onclick="openPaymentModal(<?= htmlspecialchars(json_encode($p)) ?>)" class="dropdown-item text-success">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><rect x="1" y="4" width="22" height="16" rx="2" ry="2"></rect><line x1="1" y1="10" x2="23" y2="10"></line></svg>
                                    Pay Due
                                </button>
                                <?php endif; ?>
                                <a href="<?= APP_URL ?>/purchases/<?= $p['id'] ?>/delete" class="dropdown-item text-danger" onclick="return confirm('Are you sure you want to delete this purchase?');">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><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>
                                    Delete
                                </a>
                            </div>
                        </div>
                    </td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
    
    <?= paginationLinks($purchases, APP_URL . '/purchases', $_GET) ?>
</div>

<!-- Payment Modal -->
<div id="paymentModal" class="modal-overlay">
    <div class="modal">
        <div class="modal-header">
            <h3 class="modal-title">Pay Due Amount</h3>
            <button type="button" onclick="closePaymentModal()" class="modal-close">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
            </button>
        </div>
        <div class="modal-body">
            <form id="paymentForm" action="<?= APP_URL ?>/purchases/process-payment-modal" method="POST">
                <?= Security::csrfField() ?>
                <input type="hidden" name="purchase_id" id="purchaseId">

                <div class="card mb-4">
                    <div class="card-header">
                        <h4 class="card-title">Purchase Details</h4>
                    </div>
                    <div class="p-4">
                        <div class="flex justify-between py-2 border-b border-soft">
                            <span class="text-muted">Purchase No</span>
                            <span class="font-bold" id="modalPurchaseNo"></span>
                        </div>
                        <div class="flex justify-between py-2 border-b border-soft">
                            <span class="text-muted">Supplier</span>
                            <span id="modalSupplier"></span>
                        </div>
                        <div class="flex justify-between py-2 border-b border-soft">
                            <span class="text-muted">Total Amount</span>
                            <span class="font-bold" id="modalTotal"></span>
                        </div>
                        <div class="flex justify-between py-2 border-b border-soft">
                            <span class="text-muted">Amount Paid</span>
                            <span class="text-green-600 font-bold" id="modalPaid"></span>
                        </div>
                        <div class="flex justify-between py-2 border-t-2 border-primary" style="font-size: 1.1rem; font-weight: 800;">
                            <span>Due Amount</span>
                            <span class="text-red-600" id="modalDue"></span>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Payment Amount <span class="required">*</span></label>
                    <div class="input-group">
                        <span class="input-group-text">$</span>
                        <input type="number" name="payment_amount" id="paymentAmount" class="form-control" step="0.01" required>
                    </div>
                </div>

                <div class="form-group mt-4">
                    <label class="form-label">Payment Method <span class="required">*</span></label>
                    <select name="payment_method" class="form-control" required>
                        <option value="cash">Cash</option>
                        <option value="card">Card</option>
                        <option value="transfer">Bank Transfer</option>
                        <option value="cheque">Cheque</option>
                        <option value="credit">Credit</option>
                        <option value="other">Other</option>
                    </select>
                </div>

                <div class="form-group mt-4">
                    <label class="form-label">Notes</label>
                    <textarea name="notes" class="form-control" rows="2" placeholder="Payment reference, cheque number, etc..."></textarea>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button type="button" onclick="closePaymentModal()" class="btn btn-secondary">Cancel</button>
            <button type="button" onclick="submitPayment()" class="btn btn-primary">Process Payment</button>
        </div>
    </div>
</div>

<style>
/* Dropdown Styles */
.dropdown {
    position: relative;
    display: inline-block;
}

.dropdown-menu {
    position: absolute;
    background: white;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
    min-width: 160px;
    z-index: 10000;
    overflow: visible;
    display: none;
    right: 0;
    top: 100%;
    margin-top: 5px;
}

.show {
    display: block !important;
}

/* Ensure table wrapper doesn't clip dropdown */
.table-wrapper {
    overflow-x: auto;
    overflow-y: visible;
}

/* When any dropdown is shown, make table wrapper overflow visible */
body.dropdown-open .table-wrapper {
    overflow: visible;
}

.dropdown-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 16px;
    color: var(--text);
    text-decoration: none;
    font-size: 0.85rem;
    transition: background 0.2s;
    border: none;
    background: none;
    width: 100%;
    text-align: left;
    cursor: pointer;
}

.dropdown-item:hover {
    background: #f3f4f6;
}

.dropdown-item.text-success {
    color: #16a34a;
}

.dropdown-item.text-danger {
    color: #dc2626;
}

.dropdown-item svg {
    flex-shrink: 0;
}
</style>

<script>
function toggleRowDropdown(e, id) {
    if (e) e.stopPropagation();
    const m = document.getElementById(id);
    if (!m) return;
    const is = m.classList.contains('show');
    
    document.querySelectorAll('.dropdown-menu').forEach(x => x.classList.remove('show'));
    
    if (!is) {
        m.classList.add('show');
        document.body.classList.add('dropdown-open');
    } else {
        document.body.classList.remove('dropdown-open');
    }
}

function closeAllDropdowns() {
    document.querySelectorAll('.dropdown-menu').forEach(menu => {
        menu.classList.remove('show');
    });
    document.body.classList.remove('dropdown-open');
}

// Close dropdowns when clicking outside
document.addEventListener('click', function(e) {
    if (!e.target.closest('.dropdown')) {
        closeAllDropdowns();
    }
});

window.addEventListener('resize', closeAllDropdowns, { passive: true });

function openPaymentModal(purchase) {
    const dueAmount = purchase.total - purchase.amount_paid;
    document.getElementById('purchaseId').value = purchase.id;
    document.getElementById('modalPurchaseNo').textContent = purchase.purchase_no;
    document.getElementById('modalSupplier').textContent = purchase.supplier_name || 'Direct';
    document.getElementById('modalTotal').textContent = '$' + parseFloat(purchase.total).toFixed(2);
    document.getElementById('modalPaid').textContent = '$' + parseFloat(purchase.amount_paid).toFixed(2);
    document.getElementById('modalDue').textContent = '$' + parseFloat(dueAmount).toFixed(2);
    document.getElementById('paymentAmount').value = dueAmount;
    document.getElementById('paymentAmount').max = dueAmount;
    document.getElementById('paymentModal').classList.add('show');

    // Close dropdown
    document.querySelectorAll('.dropdown-menu').forEach(menu => {
        menu.style.display = 'none';
    });
}

function closePaymentModal() {
    document.getElementById('paymentModal').classList.remove('show');
    document.getElementById('paymentForm').reset();
}

function submitPayment() {
    const form = document.getElementById('paymentForm');
    const paymentAmount = parseFloat(document.getElementById('paymentAmount').value);
    const dueAmount = parseFloat(document.getElementById('paymentAmount').max);

    if (paymentAmount <= 0) {
        alert('Payment amount must be greater than 0');
        return;
    }

    if (paymentAmount > dueAmount) {
        alert('Payment amount cannot exceed due amount');
        return;
    }

    form.submit();
}

// Close modal when clicking outside
document.getElementById('paymentModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closePaymentModal();
    }
});
</script>
