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

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

$userRole = $_SESSION['role']; // admin বা user

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

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

    // Cancel করার সময় status update
    $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 & search
$limit = 10;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $limit;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$search_sql = $search ? "AND Product_id LIKE ?" : "";

// Count total rows
if ($search) {
    $stmt = $con->prepare("SELECT COUNT(DISTINCT Product_id) as total FROM product WHERE status!='Cancelled' $search_sql");
    $like = "%$search%";
    $stmt->bind_param("s", $like);
} else {
    $stmt = $con->prepare("SELECT COUNT(DISTINCT Product_id) as total FROM product WHERE status!='Cancelled'");
}
$stmt->execute();
$total_rows = $stmt->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_rows / $limit);
$stmt->close();

// Fetch products (no GROUP BY — show every entry)
if ($search) {
    $stmt = $con->prepare("
        SELECT p.* FROM product p
        WHERE p.status!='Cancelled' $search_sql
        ORDER BY p.Expiration_date ASC
        LIMIT ?, ?
    ");
    $stmt->bind_param("sii", $like, $offset, $limit);
} else {
    $stmt = $con->prepare("
        SELECT p.* FROM product p
        WHERE p.status!='Cancelled'
        ORDER BY p.Expiration_date ASC
        LIMIT ?, ?
    ");
    $stmt->bind_param("ii", $offset, $limit);
}

$stmt->execute();
$products = $stmt->get_result();
$stmt->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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; }
</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" placeholder="Search by Product ID" value="<?= htmlspecialchars($search) ?>">
        <button class="btn btn-primary">Search</button>
    </form>

    <!-- Product Table -->
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Product ID</th>
                <th>Name</th>
                <th>Quantity</th>
                <th>Expiration Date</th>
                <th>Status</th>
                <?php if ($userRole === 'admin'): ?>
                   <!--- <th>Action</th>--->
                <?php endif; ?>
            </tr>
        </thead>
        <tbody>
            <?php while($row = $products->fetch_assoc()): ?>
                <?php
                    $expiration = $row['Expiration_date'];
                    $statusText = '';
                    $class = '';

                    if (empty($expiration)) {
                        $statusText = "Expired";
                        $class = "expired";
                    } else {
                        $expDate = new DateTime($expiration);
                        $today = new DateTime();
                        $diff = (int)$today->diff($expDate)->format("%r%a");

                        if ($diff < 0) {
                            $statusText = "Expired";
                            $class = "expired";
                        } elseif ($diff <= 2) {
                            $statusText = "Expiring in {$diff} days";
                            $class = "expiring";
                        } else {
                            $statusText = "Active";
                            $class = "active";
                        }
                    }
                ?>
                <tr>
                    <td><?= htmlspecialchars($row['Product_id']) ?></td>
                    <td><?= htmlspecialchars($row['name']) ?></td>
                    <td><?= (int)$row['Quantity'] ?></td>
                    <td><?= $row['Expiration_date'] ?? '' ?></td>
                    <td class="<?= $class ?>"><?= $statusText ?></td>
                    <?php if ($userRole === 'admin'): ?>
                        <td>
                            <form method="POST" style="display:inline;" onsubmit="return confirm('Cancel this product?');">
                                <input type="hidden" name="cancel_id" value="<?= $row['id'] ?>">
                                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                                <!---------------------Bondo----------
                                <button class="btn btn-danger btn-sm">Cancel</button>
                                ----------->
                            </form>
                        </td>
                    <?php endif; ?>
                </tr>
            <?php endwhile; ?>
        </tbody>
    </table>

    <!-- Pagination -->
    <nav>
      <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) ?>">Previous</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) ?>"><?= $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) ?>">Next</a></li>
        <?php endif; ?>
      </ul>
    </nav>
</div>
</body>
</html>
