<div class="page-header responsive-header">
    <div>
        <a href="<?= APP_URL ?>/reports" class="btn btn-ghost btn-sm mb-3" 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 Reports
        </a>
        <h1><?= $data['title'] ?></h1>
        <div class="page-subtitle">Track outstanding payments for stock purchases</div>
    </div>
    <div class="flex gap-2 flex-wrap">
        <a href="<?= APP_URL ?>/reports?report=purchase-pay-due&format=csv<?= ($qs = http_build_query($data['filters'])) ? '&' . $qs : '' ?>" class="btn btn-outline btn-sm">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                <polyline points="7 10 12 15 17 10"></polyline>
                <line x1="12" y1="15" x2="12" y2="3"></line>
            </svg>
            Export CSV
        </a>
        <a href="<?= APP_URL ?>/reports?report=purchase-pay-due&format=print<?= ($qs = http_build_query($data['filters'])) ? '&' . $qs : '' ?>" class="btn btn-secondary btn-sm">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polyline points="6 9 6 15 18 15"></polyline>
                <path d="M6 4h12v16H6z"></path>
            </svg>
            Print
        </a>
    </div>
</div>

<!-- Filters -->
<div class="card mb-4">
    <div class="card-header">
        <h3 class="card-title">Filters</h3>
    </div>
    <form method="GET" class="p-3">
        <input type="hidden" name="report" value="purchase-pay-due">
        <div class="responsive-grid gap-3">
            <div class="form-group">
                <label class="form-label">Date From</label>
                <input type="date" name="date_from" class="form-control" value="<?= e($data['filters']['date_from']) ?>">
            </div>
            <div class="form-group">
                <label class="form-label">Date To</label>
                <input type="date" name="date_to" class="form-control" value="<?= e($data['filters']['date_to']) ?>">
            </div>
            <div class="form-group">
                <label class="form-label">&nbsp;</label>
                <button type="submit" class="btn btn-primary w-full">Apply Filters</button>
            </div>
            <div class="form-group">
                <label class="form-label">&nbsp;</label>
                <a href="<?= APP_URL ?>/reports?report=purchase-pay-due" class="btn btn-outline w-full">Clear Filters</a>
            </div>
        </div>
    </form>
</div>

<!-- Summary Cards -->
<div class="responsive-grid gap-3 mb-4 summary-cards">
    <div class="card compact-card">
        <div class="p-3">
            <div class="text-xs text-muted">Total Purchases</div>
            <div class="text-xl font-bold"><?= number_format($data['summary']['total_purchases']) ?></div>
        </div>
    </div>
    <div class="card compact-card">
        <div class="p-3">
            <div class="text-xs text-muted">Total Amount Due</div>
            <div class="text-xl font-bold text-red-600"><?= money($data['summary']['total_amount_due']) ?></div>
        </div>
    </div>
    <div class="card compact-card">
        <div class="p-3">
            <div class="text-xs text-muted">Total Amount Paid</div>
            <div class="text-xl font-bold text-green-600"><?= money($data['summary']['total_amount_paid']) ?></div>
        </div>
    </div>
    <div class="card compact-card">
        <div class="p-3">
            <div class="text-xs text-muted">Total Purchase Value</div>
            <div class="text-xl font-bold text-blue-600"><?= money($data['summary']['total_purchase_value']) ?></div>
        </div>
    </div>
    <div class="card compact-card">
        <div class="p-3">
            <div class="text-xs text-muted">Fully Due</div>
            <div class="text-xl font-bold text-red-600"><?= number_format($data['summary']['due_count']) ?></div>
        </div>
    </div>
    <div class="card compact-card">
        <div class="p-3">
            <div class="text-xs text-muted">Partially Paid</div>
            <div class="text-xl font-bold text-yellow-600"><?= number_format($data['summary']['partial_count']) ?></div>
        </div>
    </div>
    <div class="card compact-card">
        <div class="p-3">
            <div class="text-xs text-muted">On Credit</div>
            <div class="text-xl font-bold text-purple-600"><?= number_format($data['summary']['credit_count']) ?></div>
        </div>
    </div>
</div>

<!-- Purchases Table -->
<div class="card mb-4">
    <div class="card-header">
        <h3 class="card-title">Purchases with Due Payments</h3>
    </div>
    <div class="overflow-x-auto">
        <table class="data-table compact-table">
            <thead>
                <tr>
                    <th class="text-left">Purchase No</th>
                    <th class="text-left">Date</th>
                    <th class="text-left">Supplier</th>
                    <th class="text-left">Location</th>
                    <th class="text-center">Total</th>
                    <th class="text-center">Amount Paid</th>
                    <th class="text-center">Due Amount</th>
                    <th class="text-center">Payment Status</th>
                    <th class="text-center">Payment Method</th>
                    <th class="text-center">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($data['purchases'])): ?>
                <tr>
                    <td colspan="10" class="text-center" style="padding: 24px 10px;">No due payments found.</td>
                </tr>
                <?php else: foreach ($data['purchases'] as $purchase): ?>
                <tr>
                    <td class="text-left">
                        <a href="<?= APP_URL ?>/purchases/<?= $purchase['id'] ?>" class="text-blue-600 hover:underline">
                            <?= e($purchase['purchase_no']) ?>
                        </a>
                    </td>
                    <td class="text-left"><?= date('M j, Y', strtotime($purchase['created_at'])) ?></td>
                    <td class="text-left"><?= e($purchase['supplier_name'] ?? 'Direct') ?></td>
                    <td class="text-left"><?= e($purchase['location_name']) ?></td>
                    <td class="text-center font-bold"><?= money($purchase['total']) ?></td>
                    <td class="text-center text-green-600"><?= money($purchase['amount_paid']) ?></td>
                    <td class="text-center font-bold text-red-600"><?= money($purchase['due_amount']) ?></td>
                    <td class="text-center">
                        <?php
                        $paymentBadge = [
                            'paid' => 'bg-green-100 text-green-800',
                            'partial' => 'bg-blue-100 text-blue-800',
                            'credit' => 'bg-purple-100 text-purple-800',
                            'due' => 'bg-red-100 text-red-800'
                        ];
                        $paymentBadgeClass = $paymentBadge[$purchase['payment_status']] ?? 'bg-gray-100 text-gray-800';
                        ?>
                        <span class="badge <?= $paymentBadgeClass ?>">
                            <?= ucfirst(e($purchase['payment_status'])) ?>
                        </span>
                    </td>
                    <td class="text-center"><?= e($purchase['payment_method']) ?></td>
                    <td class="text-center">
                        <button onclick="openPaymentModal(<?= htmlspecialchars(json_encode($purchase)) ?>)" class="btn btn-primary btn-sm">
                            Pay Due
                        </button>
                    </td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
            <tfoot class="bg-gray-50">
                <tr class="font-bold">
                    <td class="text-left" colspan="4">TOTALS</td>
                    <td class="text-center"><?= money($data['summary']['total_purchase_value']) ?></td>
                    <td class="text-center text-green-600"><?= money($data['summary']['total_amount_paid']) ?></td>
                    <td class="text-center text-red-600"><?= money($data['summary']['total_amount_due']) ?></td>
                    <td class="text-center" colspan="3"></td>
                </tr>
            </tfoot>
        </table>
    </div>
    
    <?= paginationLinks($data['pagination'], APP_URL . '/reports?report=purchase-pay-due', $data['filters']) ?>
</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>
.tab-pane {
    display: none;
}
.tab-pane.active {
    display: block;
}
.tab-btn {
    cursor: pointer;
}

/* Responsive Grid Layout */
.responsive-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 1rem;
}

/* Compact Card */
.compact-card {
    padding: 0.75rem;
}

/* Compact Table */
.compact-table thead th {
    padding: 0.5rem 0.75rem;
    font-size: 0.7rem;
}
.compact-table tbody td {
    padding: 0.5rem 0.75rem;
    font-size: 0.8rem;
}
.compact-table tfoot td {
    padding: 0.5rem 0.75rem;
    font-size: 0.8rem;
}

/* Responsive Header */
.responsive-header {
    flex-direction: column;
    align-items: flex-start;
}
@media (min-width: 768px) {
    .responsive-header {
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
    }
}

/* Mobile Responsive */
@media (max-width: 1024px) {
    .responsive-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 640px) {
    .responsive-grid {
        grid-template-columns: 1fr;
    }
    
    .page-header h1 {
        font-size: 1.1rem;
    }
    
    .page-subtitle {
        font-size: 0.75rem;
    }
    
    .card {
        padding: 1rem;
    }
    
    .compact-card {
        padding: 0.6rem;
    }
    
    .compact-table thead th,
    .compact-table tbody td,
    .compact-table tfoot td {
        padding: 0.4rem 0.5rem;
        font-size: 0.75rem;
    }
    
    .btn-sm {
        padding: 0.4rem 0.75rem;
        font-size: 0.75rem;
    }
    
    .form-control {
        padding: 0.5rem 0.75rem;
        font-size: 0.85rem;
    }
}

@media (max-width: 480px) {
    .summary-cards .text-xl {
        font-size: 1.1rem;
    }

    .summary-cards .text-xs {
        font-size: 0.65rem;
    }
}
</style>

<script>
function openPaymentModal(purchase) {
    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(purchase.due_amount).toFixed(2);
    document.getElementById('paymentAmount').value = purchase.due_amount;
    document.getElementById('paymentAmount').max = purchase.due_amount;
    document.getElementById('paymentModal').classList.add('show');
}

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>
