<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

require_once __DIR__.'/../../../includes/auth.php';
requireLogin();
requirePermission('finance.manage');

require_once __DIR__.'/../../../config/database.php';

$company_id = $_SESSION['company_id'] ?? 0;

/* ===============================
FETCH PAYMENTS
================================ */

$stmt = $pdo->prepare("
SELECT p.*, i.id as invoice_number
FROM invoice_payments p
LEFT JOIN invoices i ON p.invoice_id = i.id
WHERE p.company_id = ?
ORDER BY p.created_at DESC
");

$stmt->execute([$company_id]);

$payments = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* ===============================
LAYOUT
================================ */

$breadcrumb = "Payments";

require_once __DIR__.'/../../../includes/layout.php';

?>

<div class="container">

<div class="page-header">
<h2>Payments</h2>
<p class="page-subtitle">
Track payments received from customers.
</p>
</div>

<div class="table-wrap">

<table class="data-table">

<thead>
<tr>

<th>ID</th>
<th>Invoice</th>
<th>Amount</th>
<th>Method</th>
<th>Reference</th>
<th>Date</th>

</tr>
</thead>

<tbody>

<?php if(!$payments): ?>

<tr>
<td colspan="6">No payments recorded.</td>
</tr>

<?php else: ?>

<?php foreach($payments as $p): ?>

<tr>

<td><?= (int)$p['id'] ?></td>

<td>
<a href="../invoices/view.php?id=<?= (int)$p['invoice_id'] ?>">
INV-<?= str_pad($p['invoice_id'],5,"0",STR_PAD_LEFT) ?>
</a>
</td>

<td>
R <?= number_format($p['amount'],2) ?>
</td>

<td>
<?= htmlspecialchars($p['payment_method'] ?? '') ?>
</td>

<td>
<?= htmlspecialchars($p['reference'] ?? '') ?>
</td>

<td>
<?= date("d M Y",strtotime($p['created_at'])) ?>
</td>

</tr>

<?php endforeach; ?>

<?php endif; ?>

</tbody>

</table>

</div>

</div>

<?php require_once __DIR__.'/../../../includes/layout_footer.php'; ?>