<?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 PURCHASE ORDERS
================================ */

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

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

?>

<div class="main-content">

<div class="page-header">

<h2>Purchase Orders</h2>

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

</div>


<div class="stat-card">

<table class="table">

<thead>

<tr>
<th>PO Number</th>
<th>Supplier</th>
<th>Order Date</th>
<th>Status</th>
<th>Actions</th>
</tr>

</thead>

<tbody>

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

<tr>
<td colspan="5" style="text-align:center;padding:20px;">
No purchase orders found
</td>
</tr>

<?php } ?>

<?php foreach($orders as $order){ ?>

<tr>

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

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

<td><?php echo htmlspecialchars($order['order_date']); ?></td>

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

<td>

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

</td>

</tr>

<?php } ?>

</tbody>

</table>

</div>

</div>

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