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

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

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

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

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

    // প্রথমে cancelled product info নাও
    $stmt = $con->prepare("SELECT Product_id, Quantity FROM product WHERE id=? AND status='Cancelled'");
    $stmt->bind_param("i", $activate_id);
    $stmt->execute();
    $product = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($product) {
        $product_id = $product['Product_id'];
        $quantity = $product['Quantity'];

        // Status update এবং Quantity আবার যোগ
        $stmt = $con->prepare("UPDATE product SET status='Active', Quantity=Quantity+? WHERE id=?");
        $stmt->bind_param("ii", $quantity, $activate_id);
        $stmt->execute();
        $stmt->close();
    }

    header("Location: products_activate.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 (Cancelled products)
if ($search) {
    $stmt = $con->prepare("SELECT COUNT(*) as total FROM product WHERE status='Cancelled' $search_sql");
    $like = "%$search%";
    $stmt->bind_param("s", $like);
} else {
    $stmt = $con->prepare("SELECT COUNT(*) 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 Cancelled products
if ($search) {
    $stmt = $con->prepare("
        SELECT * FROM product 
        WHERE status='Cancelled' $search_sql
        GROUP BY Product_id
        ORDER BY Expiration_date ASC
        LIMIT ?, ?
    ");
    $stmt->bind_param("sii", $like, $offset, $limit);
} else {
    $stmt = $con->prepare("
        SELECT * FROM product 
        WHERE status='Cancelled'
        GROUP BY Product_id
        ORDER BY 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>Activate Cancelled Products</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-4">
    <h2>Activate Cancelled Products</h2>

    <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>

    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Product ID</th>
                <th>Name</th>
                <th>Quantity</th>
                <th>Expiration Date</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php while($row = $products->fetch_assoc()): ?>
                <tr>
                    <td><?= htmlspecialchars($row['Product_id']) ?></td>
                    <td><?= htmlspecialchars($row['name']) ?></td>
                    <td><?= (int)$row['Quantity'] ?></td>
                    <td><?= $row['Expiration_date'] ?? '' ?></td>
                    <td>
                        <?php if ($userRole === 'admin'): ?>
                            <form method="POST" style="display:inline;" onsubmit="return confirm('Activate this product?');">
                                <input type="hidden" name="activate_id" value="<?= $row['id'] ?>">
                                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                                <button class="btn btn-success btn-sm">Activate</button>
                            </form>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endwhile; ?>
        </tbody>
    </table>

    <!-- Pagination -->
    <nav>
      <ul class="pagination">
        <?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>
