<?php

ini_set('display_errors',1);
ini_set('display_startup_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;

$search = $_GET['search'] ?? '';

/* ===============================
FETCH INVOICES
================================ */

$stmt = $pdo->prepare("
SELECT i.*, c.company_name
FROM invoices i
LEFT JOIN companies c ON i.customer_id = c.id
WHERE i.company_id = ?
AND (
    i.invoice_number LIKE ?
    OR c.company_name LIKE ?
    OR i.id LIKE ?
)
ORDER BY i.created_at DESC
");

$like = "%".$search."%";

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

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


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

$breadcrumb = "Invoices";
require_once __DIR__ . '/../../../includes/layout.php';

?>

<div class="container">

<div class="page-header">
<h2>Invoices</h2>
<p class="page-subtitle">
Manage customer invoices.
</p>
</div>


<div class="topbar">

<form method="GET">

<input
type="text"
name="search"
placeholder="Search invoice or customer"
value="<?= htmlspecialchars($search) ?>"
style="padding:6px"
>

<button class="btn">Search</button>

</form>

</div>


<div class="table-wrap">

<table class="data-table">

<thead>

<tr>
<th>Invoice #</th>
<th>Customer</th>
<th>Date</th>
<th>Total</th>
<th>Balance</th>
<th>Status</th>
<th>Actions</th>
</tr>

</thead>

<tbody>

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

<tr>
<td colspan="7">No invoices found.</td>
</tr>

<?php else: ?>

<?php foreach($invoices as $inv): ?>

<tr>

<td>

<strong>

<?= htmlspecialchars(
$inv['invoice_number']
?: 'INV-'.str_pad($inv['id'],5,"0",STR_PAD_LEFT)
) ?>

</strong>

</td>

<td>
<?= htmlspecialchars($inv['company_name'] ?? 'No Customer') ?>
</td>

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

<td>
<strong>
R <?= number_format((float)($inv['total'] ?? 0),2) ?>
</strong>
</td>

<td>
R <?= number_format((float)($inv['balance'] ?? 0),2) ?>
</td>

<td>

<span class="status">

<?= htmlspecialchars($inv['payment_status'] ?? 'UNPAID') ?>

</span>

</td>

<td>

<a class="btn-small"
href="view.php?id=<?= (int)$inv['id'] ?>">
View
</a>

<a class="btn-small"
href="preview.php?id=<?= (int)$inv['id'] ?>">
Preview
</a>

<a class="btn-small"
href="pdf.php?id=<?= (int)$inv['id'] ?>">
PDF
</a>

</td>

</tr>

<?php endforeach; ?>

<?php endif; ?>

</tbody>

</table>

</div>

</div>

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