<?php

ini_set('display_errors',1);
error_reporting(E_ALL);

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

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

require_once __DIR__.'/../../includes/header.php';
require_once __DIR__.'/../../includes/sidebar.php';

$company_id = $_SESSION['company_id'];

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

$stmt = $pdo->prepare("
SELECT si.*, s.supplier_name, po.po_number
FROM supplier_invoices si
LEFT JOIN suppliers s ON si.supplier_id = s.id
LEFT JOIN purchase_orders po ON si.purchase_order_id = po.id
WHERE si.company_id = ?
ORDER BY si.created_at DESC
");

$stmt->execute([$company_id]);
$invoices = $stmt->fetchAll();

?>

<div class="main-content">

<div class="page-header">

<h2>Supplier Invoices</h2>

<a href="create.php" class="btn btn-primary">
+ Create Supplier Invoice
</a>

</div>

<div class="stat-card">

<div class="table-responsive">

<table class="table table-striped">

<thead>

<tr>
<th>Invoice</th>
<th>Supplier</th>
<th>PO</th>
<th>Total</th>
<th>Paid</th>
<th>Status</th>
<th>Actions</th>
</tr>

</thead>

<tbody>

<?php if(count($invoices)==0){ ?>

<tr>
<td colspan="7" style="text-align:center;padding:20px;">
No supplier invoices yet
</td>
</tr>

<?php } ?>

<?php foreach($invoices as $invoice){ ?>

<tr>

<td><?php echo htmlspecialchars($invoice['invoice_number']); ?></td>

<td><?php echo htmlspecialchars($invoice['supplier_name']); ?></td>

<td><?php echo htmlspecialchars($invoice['po_number']); ?></td>

<td>R <?php echo number_format($invoice['total_amount'],2); ?></td>

<td>R <?php echo number_format($invoice['paid_amount'],2); ?></td>

<td><?php echo htmlspecialchars($invoice['status']); ?></td>

<td>

<a href="view.php?id=<?php echo $invoice['id']; ?>" class="btn btn-sm btn-info">
View
</a>

</td>

</tr>

<?php } ?>

</tbody>

</table>

</div>

</div>

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