
<?php
session_start();
include 'php/db_connection.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$userRole = $_SESSION['role'];

// CSRF
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Cancel (Admin)
if (isset($_POST['cancel_id']) && $_POST['csrf_token'] === $_SESSION['csrf_token'] && $userRole === 'admin') {
    $cancel_id = (int)$_POST['cancel_id'];

    $stmt = $con->prepare("UPDATE product SET status='Cancelled' WHERE id=?");
    $stmt->bind_param("i", $cancel_id);
    $stmt->execute();
    $stmt->close();

    header("Location: products_expiration.php");
    exit();
}

// Pagination
$limit = 10;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;

// Search & Filter
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$status_filter = $_GET['status'] ?? 'all';

// Fetch ALL (filter later in PHP)
if ($search) {
    $stmt = $con->prepare("SELECT * FROM product WHERE Product_id LIKE ? ORDER BY Expiration_date ASC");
    $like = "%$search%";
    $stmt->bind_param("s", $like);
} else {
    $stmt = $con->prepare("SELECT * FROM product ORDER BY Expiration_date ASC");
}
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();

// FILTER in PHP
$filtered = [];

while ($row = $result->fetch_assoc()) {

    $expiration = $row['Expiration_date'];
    $dbStatus = $row['status'];

    // Status detect
    if ($dbStatus === 'Cancelled') {
        $isExpired = true;
        $isActive = false;
    } else {
        if (!empty($expiration)) {
            $expDate = new DateTime($expiration);
            $today = new DateTime();
            $diff = (int)$today->diff($expDate)->format("%r%a");

            $isExpired = ($diff < 0);
            $isActive = ($diff >= 0);
        } else {
            $isExpired = false;
            $isActive = true;
        }
    }

    // Apply filter
    if ($status_filter == 'active' && !$isActive) continue;
    if ($status_filter == 'expired' && !$isExpired) continue;

    $filtered[] = $row;
}

// Pagination after filter
$total_rows = count($filtered);
$total_pages = ceil($total_rows / $limit);
$offset = ($page - 1) * $limit;

$products = array_slice($filtered, $offset, $limit);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Products Expiration</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

<style>
.expired { color:red; font-weight:bold; }
.expiring { color:orange; font-weight:bold; }
.active { color:green; font-weight:bold; }
.cancelled { color:gray; font-weight:bold; }
</style>
</head>

<body>
<?php include 'sidebar.php';?>

<div class="container mt-4">
<h2>Products Expiration</h2>

<!-- Search -->
<form method="GET" class="form-inline mb-3">
    <input type="text" name="search" class="form-control mr-2"
           value="<?= htmlspecialchars($search) ?>" placeholder="Search Product ID">

    <label class="mr-2 ml-2">
        <input type="radio" name="status" value="all" <?= $status_filter=='all'?'checked':'' ?>> All
    </label>

    <label class="mr-2">
        <input type="radio" name="status" value="active" <?= $status_filter=='active'?'checked':'' ?>> Active
    </label>

    <label class="mr-2">
        <input type="radio" name="status" value="expired" <?= $status_filter=='expired'?'checked':'' ?>> Expired / Cancelled
    </label>

    <button class="btn btn-primary">Search</button>
</form>

<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Qty</th>
<th>Expiry</th>
<th>Status</th>
</tr>
</thead>

<tbody>
<?php foreach($products as $row): ?>

<?php
$expiration = $row['Expiration_date'];
$dbStatus = $row['status'];

if ($dbStatus === 'Cancelled') {
    $text = "Cancelled";
    $class = "cancelled";
}
else {
    if (!empty($expiration)) {
        $expDate = new DateTime($expiration);
        $today = new DateTime();
        $diff = (int)$today->diff($expDate)->format("%r%a");

        if ($diff < 0) {
            $text = "Expired";
            $class = "expired";
        } elseif ($diff <= 2) {
            $text = "Expiring in $diff days";
            $class = "expiring";
        } else {
            $text = "Active";
            $class = "active";
        }
    } else {
        $text = "No Expiry";
        $class = "active";
    }
}
?>

<tr>
<td><?= $row['Product_id'] ?></td>
<td><?= $row['name'] ?></td>
<td><?= $row['Quantity'] ?></td>
<td><?= $row['Expiration_date'] ?></td>
<td class="<?= $class ?>"><?= $text ?></td>
</tr>

<?php endforeach; ?>
</tbody>
</table>

<!-- Pagination -->
<ul class="pagination justify-content-center">
<?php if($page>1): ?>
<li class="page-item">
<a class="page-link" href="?page=<?= $page-1 ?>&search=<?= urlencode($search) ?>&status=<?= $status_filter ?>">Prev</a>
</li>
<?php endif; ?>

<?php for($p=1;$p<=$total_pages;$p++): ?>
<li class="page-item <?= $p==$page?'active':'' ?>">
<a class="page-link" href="?page=<?= $p ?>&search=<?= urlencode($search) ?>&status=<?= $status_filter ?>"><?= $p ?></a>
</li>
<?php endfor; ?>

<?php if($page<$total_pages): ?>
<li class="page-item">
<a class="page-link" href="?page=<?= $page+1 ?>&search=<?= urlencode($search) ?>&status=<?= $status_filter ?>">Next</a>
</li>
<?php endif; ?>
</ul>

</div>
</body>
</html>