<?php
session_start();
require_once '../assets/db_connect.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';
if (!isset($_SESSION['user']) || $_SESSION['user']['role']!=='admin') { echo "Access denied"; exit; }

$today = new DateTimeImmutable();
$rows = $pdo->query("
 SELECT p.name AS product_name, pb.batch_no, pb.qty, pb.expiry_date, s.name AS supplier
 FROM product_batches pb
 JOIN products p ON p.id = pb.product_id
 LEFT JOIN suppliers s ON s.id = pb.supplier_id
 ORDER BY pb.expiry_date ASC
")->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
/* Back button styling - consistent with other pages */
.back-btn {
    display: inline-block;
    padding: 8px 16px;
    background-color: #6c757d;
    color: white;
    text-decoration: none;
    border-radius: 4px;
    border: none;
    cursor: pointer;
    font-size: 14px;
    margin-bottom: 15px;
    transition: background-color 0.2s;
}
.back-btn:hover {
    background-color: #5a6268;
    color: white;
    text-decoration: none;
}
.back-btn i {
    margin-right: 5px;
}
/* Styling for expired items */
.expired {
    background-color: #f8d7da;
    color: #721c24;
}
.near-expiry {
    background-color: #fff3cd;
    color: #856404;
}
</style>

<div class="col-md-10 ml-sm-auto px-4 py-4">

<!-- BACK BUTTON at the top -->
<div class="mb-3">
    <a href="daily_sales.php" class="back-btn">
        <i>←</i> Back to Reports
    </a>
</div>

<h3 class="text-success">Expired / Near Expiry</h3>

<div class="table-responsive">
<table class="table table-sm table-bordered">
<thead class="thead-dark"><tr><th>Product</th><th>Batch</th><th>Qty</th><th>Expiry Date</th><th>Status</th><th>Supplier</th></tr></thead>
<tbody>
<?php foreach($rows as $r):
    $expiryDate = $r['expiry_date'] ? new DateTime($r['expiry_date']) : null;
    $today = new DateTime();
    $days = null;
    $statusClass = '';
    
    if ($expiryDate) {
        $interval = $expiryDate->diff($today);
        $days = $interval->days;
        if ($expiryDate < $today) {
            $status = 'EXPIRED';
            $statusClass = 'expired';
            $days = abs($days) . ' days ago';
        } else {
            $status = $days . ' days left';
            $statusClass = $days <= 30 ? 'near-expiry' : '';
        }
    } else {
        $status = '-';
        $days = '-';
    }
?>
<tr class="<?= $statusClass ?>">
  <td><?= htmlspecialchars($r['product_name']) ?></td>
  <td><?= htmlspecialchars($r['batch_no']) ?></td>
  <td><?= $r['qty'] ?></td>
  <td><?= $r['expiry_date'] ? date('d-M-Y', strtotime($r['expiry_date'])) : '-' ?></td>
  <td><strong><?= $status ?></strong></td>
  <td><?= htmlspecialchars($r['supplier']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>

<!-- BACK BUTTON at the bottom -->
<div class="mt-4">
    <a href="daily_sales.php" class="back-btn">
        <i>←</i> Back to Reports
    </a>
</div>

</div>

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