<?php
session_start();
if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'admin') {
    header("Location: login.html");
    exit();
}

include 'db_connect.php';

// Determine if user wants to see all entries
$view_all = isset($_GET['view']) && $_GET['view'] === 'all';

// Pagination setup
$limit  = $view_all ? 0 : 20; // 20 entries per page or all
$page   = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $limit;

// Count total batches
$countResult = $conn->query("SELECT COUNT(*) AS total FROM stock_batches");
$totalRows   = $countResult->fetch_assoc()['total'];
$totalPages  = $limit > 0 ? ceil($totalRows / $limit) : 1;

// Fetch batches
$query = "
    SELECT sb.id,
           p.name AS product_name,
           sb.quantity_added,
           sb.buying_price,
           sb.supplier,
           sb.batch_date
    FROM stock_batches sb
    JOIN products p ON sb.product_id = p.id
    ORDER BY sb.batch_date DESC
";

if (!$view_all) {
    $query .= " LIMIT $limit OFFSET $offset";
}

$result = $conn->query($query);
?>
<!DOCTYPE html>
<html>
<head>
    <title>Stock Batches</title>
    <?php include('head.php'); ?>
    <style>
        body {
            font-family: 'Poppins', Arial, sans-serif;
            background: var(--bg-main);
            margin: 0;
            color: var(--text-main);
        }

        /* Content to the right of the sidebar */
        .content-wrapper {
            margin-left: 250px; /* match sidebar width */
            padding: 30px;
            min-height: 100vh;
            background: var(--bg-main);
            color: var(--text-main);
            box-sizing: border-box;
        }

        .sidebar.collapsed + .content-wrapper {
            margin-left: 70px;
        }

        h2 {
            text-align: center;
            color: var(--text-heading);
            margin-bottom: 10px;
            font-weight: 600;
        }

        .subtitle {
            text-align: center;
            color: var(--accent-gold);
            margin-bottom: 20px;
            font-size: 14px;
        }

        /* Card that holds filters and table */
        .page-card {
            background: var(--bg-card);
            border-radius: 14px;
            padding: 20px 24px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.35);
            border: 1px solid rgba(0,0,0,0.15);
            color: var(--text-main);
        }

        /* stronger border in dark theme like before */
        body:not([data-theme="light"]) .page-card {
            border-color: #0a4a85;
        }

        .page-header-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            margin-bottom: 15px;
        }

        .page-header-row h3 {
            margin: 0;
            color: var(--text-heading);
        }

        /* View options */
        .view-options {
            text-align: right;
        }

        .view-options form {
            display: inline-block;
        }

        .view-options label {
            margin-right: 4px;
            color: var(--text-main);
            font-size: 13px;
        }

        .view-options select {
            padding: 6px 10px;
            border-radius: 6px;
            border: 1px solid rgba(0,0,0,0.2);
            background: var(--bg-table-head);
            color: var(--text-heading);
            font-size: 13px;
        }

        body:not([data-theme="light"]) .view-options select {
            border-color: #0a4a85;
            color: #ffffff;
        }

        .view-options select:focus {
            outline: none;
            background: var(--bg-table-hover);
            border-color: var(--accent-gold);
        }

        /* Table wrapper for wide, scrollable table */
        .table-wrapper {
            width: 100%;
            overflow-x: auto;
            margin-top: 10px;
        }

        table {
            width: 100%;
            min-width: 1050px; /* keep table wide for readability */
            border-collapse: collapse;
            background: var(--bg-card);
            color: var(--text-main);
            border-radius: 10px;
            overflow: hidden;
        }

        th,
        td {
            padding: 10px 12px;
            text-align: center;
            border: 1px solid rgba(0,0,0,0.12);
            font-size: 13px;
            white-space: nowrap;
        }

        /* darker borders in dark mode like original */
        body:not([data-theme="light"]) th,
        body:not([data-theme="light"]) td {
            border-color: rgba(255,255,255,0.15);
        }

        th {
            background: var(--bg-table-head);
            color: #ffffff;
            font-weight: 600;
        }

        body[data-theme="light"] th {
            color: #111827; /* strong dark text for light header */
        }

        tbody tr {
            background: var(--bg-table-row);
        }

        tbody tr:nth-child(even) {
            background: var(--bg-table-row);
        }

        tbody tr:hover {
            background: var(--bg-table-hover);
        }

        /* Pagination */
        .pagination {
            text-align: center;
            margin-top: 15px;
        }

        .pagination a {
            margin: 0 4px;
            padding: 8px 12px;
            background: var(--bg-card);
            color: var(--text-main);
            text-decoration: none;
            border-radius: 5px;
            border: 1px solid rgba(0,0,0,0.12);
            font-size: 13px;
        }

        body:not([data-theme="light"]) .pagination a {
            border-color: #0a4a85;
            color: #ffffff;
        }

        .pagination a:hover {
            background: var(--bg-table-hover);
            border-color: var(--bg-table-hover);
        }

        .pagination .current {
            background: #5a47f5;
            border-color: #5a47f5;
            font-weight: 700;
            color: #ffffff;
        }

        /* Back button */
        .back {
            display: inline-block;
            margin-top: 18px;
            padding: 10px 18px;
            background: var(--accent-gold);
            color: var(--bg-main);
            text-decoration: none;
            border-radius: 6px;
            font-weight: 600;
            font-size: 14px;
        }

        .back:hover {
            background: var(--accent-gold-soft);
        }
    </style>
</head>
<body>
    <?php include("sidebar.php"); ?>

    <div class="content-wrapper">
        <h2>Stock Batches</h2>
        <div class="subtitle">
            <?= $view_all ? 'All entries' : "Page $page of $totalPages" ?>
        </div>

        <div class="page-card">
            <div class="page-header-row">
                <h3>Stock Batch History</h3>

                <div class="view-options">
                    <form method="get">
                        <label>View</label>
                        <select name="view" onchange="this.form.submit()">
                            <option value="page" <?= !$view_all ? 'selected' : '' ?>>20 per page</option>
                            <option value="all"  <?= $view_all ? 'selected' : '' ?>>All entries</option>
                        </select>
                        <?php if (!$view_all): ?>
                            <input type="hidden" name="page" value="<?= $page ?>">
                        <?php endif; ?>
                    </form>
                </div>
            </div>

            <?php if ($result->num_rows > 0): ?>
                <div class="table-wrapper">
                    <table>
                        <thead>
                            <tr>
                                <th>Batch ID</th>
                                <th>Product</th>
                                <th>Quantity Added</th>
                                <th>Buying Price (KES)</th>
                                <th>Supplier</th>
                                <th>Batch Date</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php while ($row = $result->fetch_assoc()): ?>
                            <tr>
                                <td><?= $row['id'] ?></td>
                                <td><?= htmlspecialchars($row['product_name']) ?></td>
                                <td><?= $row['quantity_added'] ?></td>
                                <td><?= number_format($row['buying_price'], 2) ?></td>
                                <td><?= $row['supplier'] ? htmlspecialchars($row['supplier']) : '-' ?></td>
                                <td><?= date('Y-m-d H:i', strtotime($row['batch_date'])) ?></td>
                            </tr>
                        <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>

                <?php if (!$view_all): ?>
                    <div class="pagination">
                        <?php for ($p = 1; $p <= $totalPages; $p++): ?>
                            <a href="?page=<?= $p ?>&view=page"
                               class="<?= $p == $page ? 'current' : '' ?>">
                                <?= $p ?>
                            </a>
                        <?php endfor; ?>
                    </div>
                <?php endif; ?>

            <?php else: ?>
                <p>No stock batches found.</p>
            <?php endif; ?>
        </div>

        <a href="manage_products.php" class="back">← Back to Products</a>

        <?php include 'footer.php'; ?>
    </div>
</body>
</html>
