<?php

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

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

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

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

/* -------------------------------
SESSION TENANT
--------------------------------*/

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

/* -------------------------------
LOAD RETURNS (TENANT SAFE)
--------------------------------*/

$stmt = $pdo->prepare("
SELECT *
FROM inventory_returns
WHERE company_id = ?
ORDER BY id DESC
");

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

$returns = $stmt->fetchAll();

?>

<div class="main-content">

<div class="page-header">
<h2>Sales Inventory Returns</h2>
</div>

<div class="stat-card">

<div style="margin-bottom:20px;">

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

</div>

<table class="table">

<thead>

<tr>
<th>ID</th>
<th>Return Number</th>
<th>Return Type</th>
<th>Status</th>
<th>Date</th>
<th>Action</th>
</tr>

</thead>

<tbody>

<?php if(empty($returns)): ?>

<tr>
<td colspan="6">No returns found.</td>
</tr>

<?php else: ?>

<?php foreach($returns as $return): ?>

<tr>

<td><?php echo $return['id']; ?></td>

<td><?php echo $return['return_number']; ?></td>

<td><?php echo $return['return_type']; ?></td>

<td>

<?php
$color="#999";

if($return['status']=="Pending") $color="#f2531e";
if($return['status']=="Approved") $color="#007bff";
if($return['status']=="Closed") $color="#28a745";
?>

<span style="
padding:4px 10px;
border-radius:20px;
color:#fff;
background:<?php echo $color; ?>;
font-size:12px;
font-weight:600;
">

<?php echo $return['status']; ?>

</span>

</td>

<td><?php echo $return['created_at']; ?></td>

<td>

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

</td>

</tr>

<?php endforeach; ?>

<?php endif; ?>

</tbody>

</table>

</div>

</div>

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