<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('payment_view');

$pdo = getDB();

$payments = $pdo->query("
    SELECT pay.*, c.name as customer_name, s.company_name as supplier_name, u.name as received_by_name
    FROM payments pay
    LEFT JOIN customers c ON pay.customer_id = c.id
    LEFT JOIN suppliers s ON pay.supplier_id = s.id
    LEFT JOIN users u ON pay.received_by = u.id
    ORDER BY pay.id DESC
")->fetchAll();

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <h4 class="page-title"><i class="fas fa-money-bill-wave me-2"></i>Payments</h4>
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table id="paymentsTable" class="table table-hover datatable">
                        <thead><tr><th>Date</th><th>Type</th><th>Customer/Supplier</th><th>Amount</th><th>Method</th><th>Received By</th><th>Notes</th></tr></thead>
                        <tbody>
                            <?php foreach ($payments as $p): ?>
                            <tr>
                                <td><?= formatDate($p['payment_date']) ?></td>
                                <td><span class="badge bg-<?= $p['payment_type'] == 'Sale' ? 'success' : ($p['payment_type'] == 'Purchase' ? 'info' : ($p['payment_type'] == 'Repair' ? 'warning' : 'secondary')) ?>"><?= $p['payment_type'] ?></span></td>
                                <td><?= htmlspecialchars($p['customer_name'] ?? $p['supplier_name'] ?? '-') ?></td>
                                <td><strong><?= formatCurrency($p['amount']) ?></strong></td>
                                <td><?= $p['payment_method'] ?></td>
                                <td><?= htmlspecialchars($p['received_by_name'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($p['notes'] ?? '-') ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
