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

include 'db_connect.php';

// ---------- SEARCH ----------
$search = trim($_GET['search'] ?? '');

// ---------- PAGINATION ----------
$limit    = 20;
$page     = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$show_all = isset($_GET['all']);
$offset   = ($page - 1) * $limit;

// ---------- WHERE CLAUSE FOR SEARCH ----------
$where = '';
if ($search !== '') {
    $safe = $conn->real_escape_string($search);
    $where = "WHERE name LIKE '%$safe%' OR barcode LIKE '%$safe%'";
}

// ---------- COUNT PRODUCTS (RESPECT SEARCH) ----------
$count_sql   = "SELECT COUNT(*) AS total FROM products $where";
$count_res   = $conn->query($count_sql);
$total_row   = $count_res ? $count_res->fetch_assoc() : ['total' => 0];
$total_records = (int)($total_row['total'] ?? 0);

if ($show_all) {
    $total_pages = 1;
    $page        = 1;
} else {
    $total_pages = max(1, (int)ceil($total_records / $limit));
    if ($page > $total_pages) {
        $page = $total_pages;
    }
    $offset = ($page - 1) * $limit;
}

// ---------- FETCH PRODUCTS (RESPECT SEARCH + PAGINATION) ----------
$select_sql = "
    SELECT 
        id,
        name,
        category,
        barcode,
        buying_price,
        selling_price,
        quantity,
        date_added
    FROM products
    $where
    ORDER BY name ASC
";
if (!$show_all) {
    $select_sql .= " LIMIT $limit OFFSET $offset";
}

$result = $conn->query($select_sql);

// Page totals
$page_value = 0;
$page_qty   = 0;
$rows       = [];

if ($result) {
    while ($row = $result->fetch_assoc()) {
        $rows[]      = $row;
        $page_value += (float)$row['buying_price'] * (int)$row['quantity'];
        $page_qty   += (int)$row['quantity'];
    }
}

// ---------- GRAND TOTALS (ALL PRODUCTS, NOT FILTERED BY SEARCH) ----------
$grand = $conn->query("
    SELECT 
        SUM(buying_price * quantity) AS val,
        SUM(quantity)                AS qty
    FROM products
");
$grand_data = $grand ? $grand->fetch_assoc() : ['val' => 0, 'qty' => 0];

// Page title for <title> tag
$page_title = "Manage Products";

include('head.php'); // brings in theme + sidebar styles + theme JS
?>

<body>

<?php include("sidebar.php"); ?>

<div class="content-wrapper">

    <div class="page-header">
        <div>
            <div class="page-title">Manage Products</div>
            <div class="page-subtitle">
                <?= $show_all ? 'Showing all products' : "Page $page of $total_pages" ?>
                <?php if ($search !== ''): ?>
                    · Filtered by "<strong><?= htmlspecialchars($search) ?></strong>"
                <?php endif; ?>
            </div>
        </div>

        <div class="page-header-right">
            <!-- Search by Name / Barcode -->
            <form method="get" class="product-search">
                <input
                    type="text"
                    name="search"
                    placeholder="Search by name or barcode..."
                    value="<?= htmlspecialchars($search) ?>"
                >
                <?php if ($show_all): ?>
                    <input type="hidden" name="all" value="1">
                <?php endif; ?>
                <button type="submit" class="btn btn-outline">Search</button>
                <?php if ($search !== ''): ?>
                    <a href="manage_products.php" class="btn btn-ghost">Reset</a>
                <?php endif; ?>
            </form>

            <div class="top-buttons">
                <a href="add_products.php" class="btn">+ Add New Product</a>
                <a href="batch_list.php" class="btn">View Stock Batches</a>

                <?php if (!$show_all): ?>
                    <a href="?all=1<?= $search !== '' ? '&search=' . urlencode($search) : '' ?>" class="btn">Show All</a>
                <?php else: ?>
                    <a href="?page=1<?= $search !== '' ? '&search=' . urlencode($search) : '' ?>" class="btn">Paginated View</a>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="page-card">
        <div class="table-wrapper">
            <table class="table-theme product-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th class="name-col">Name</th>
                        <th>Barcode</th>
                        <th class="category-col">Category</th>
                        <th>Avg Buying Price</th>
                        <th>Selling Price</th>
                        <th>Quantity</th>
                        <th>Total Value</th>
                        <th>Date Added</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!empty($rows)): ?>
                    <?php foreach ($rows as $p): ?>
                        <tr class="<?= ($p['quantity'] < 10 ? 'low-stock' : '') ?>">
                            <td><?= (int)$p['id'] ?></td>
                            <td class="name-cell"><?= htmlspecialchars($p['name']) ?></td>
                            <td><?= htmlspecialchars($p['barcode'] ?? '-') ?></td>
                            <td class="category-cell"><?= htmlspecialchars($p['category']) ?></td>
                            <td class="numeric">KES <?= number_format($p['buying_price'], 2) ?></td>
                            <td class="numeric">KES <?= number_format($p['selling_price'], 2) ?></td>
                            <td class="numeric"><?= (int)$p['quantity'] ?></td>
                            <td class="numeric">KES <?= number_format($p['buying_price'] * $p['quantity'], 2) ?></td>
                            <td><?= htmlspecialchars($p['date_added'] ?? '-') ?></td>
                            <td class="actions">
                                <a href="add_stock.php?id=<?= (int)$p['id'] ?>">Stock</a>
                                <a href="edit_product.php?id=<?= (int)$p['id'] ?>">Edit</a>
                                <a href="delete_product.php?id=<?= (int)$p['id'] ?>"
                                   onclick="return confirm('Delete this product?')"
                                   class="delete">Delete</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>

                    <tr class="totals-row">
                        <td colspan="4" class="totals-label">Page Totals</td>
                        <td class="numeric">KES <?= number_format($page_value, 2) ?></td>
                        <td>-</td>
                        <td class="numeric"><?= $page_qty ?></td>
                        <td colspan="3"></td>
                    </tr>
                <?php else: ?>
                    <tr>
                        <td colspan="10" class="empty-row">No products found.</td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if (!$show_all && $total_pages > 1): ?>
            <div class="pagination">
                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <a href="?page=<?= $i ?><?= $search !== '' ? '&search=' . urlencode($search) : '' ?>"
                       class="<?= ($i == $page ? 'active' : '') ?>">
                        <?= $i ?>
                    </a>
                <?php endfor; ?>
            </div>
        <?php endif; ?>
    </div>

    <div class="totals-box">
        Grand Total Quantity: <?= (int)($grand_data['qty'] ?? 0) ?><br>
        Grand Total Inventory Value: KES <?= number_format(($grand_data['val'] ?? 0), 2) ?>
    </div>

    <?php include 'footer.php'; ?>

</div> <!-- END content-wrapper -->

<style>
    /* Layout next to the global sidebar */
    .content-wrapper {
        margin-left: 250px;
        padding: 25px 30px;
        background: var(--bg-main);
        min-height: 100vh;
        box-sizing: border-box;
    }

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

    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        flex-wrap: wrap;
        margin-bottom: 18px;
        gap: 12px;
    }

    .page-title {
        font-size: 22px;
        font-weight: 600;
        color: var(--text-heading);
    }

    .page-subtitle {
        font-size: 13px;
        color: var(--accent-gold);
        margin-top: 4px;
    }

    .page-header-right {
        display: flex;
        flex-direction: column;
        gap: 10px;
        align-items: flex-end;
    }

    .top-buttons {
        display: flex;
        justify-content: flex-start;
        flex-wrap: wrap;
        gap: 10px;
    }

    /* Search bar */
    .product-search {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        align-items: center;
        justify-content: flex-end;
    }

    .product-search input[type="text"] {
        min-width: 220px;
        padding: 8px 10px;
        border-radius: 999px;
        border: 1px solid rgba(148,163,184,0.7);
        background: var(--bg-card);
        color: var(--text-main);
        font-size: 13px;
    }

    .product-search input[type="text"]:focus {
        outline: none;
        border-color: var(--accent-gold);
        box-shadow: 0 0 0 1px rgba(244,180,0,0.3);
    }

    .btn.btn-outline {
        padding: 8px 14px;
        border-radius: 999px;
        border: 1px solid var(--accent-gold);
        background: transparent;
        color: var(--accent-gold);
        font-size: 13px;
        font-weight: 500;
    }

    .btn.btn-outline:hover {
        background: var(--accent-gold);
        color: var(--bg-main);
    }

    .btn.btn-ghost {
        padding: 6px 10px;
        border-radius: 999px;
        border: none;
        background: transparent;
        color: var(--text-muted);
        font-size: 12px;
        text-decoration: underline;
    }

    .page-card {
        background: var(--bg-card);
        border-radius: 14px;
        padding: 18px 22px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.25);
        border: 1px solid rgba(0,0,0,0.15);
    }

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

    .table-wrapper {
        width: 100%;
        margin-top: 10px;
        overflow-x: auto;
    }

    .product-table {
        min-width: 1100px;
        font-size: 13px;
        border-collapse: collapse;
        width: 100%;
    }

    .product-table th,
    .product-table td {
        padding: 9px 10px;
        white-space: nowrap;
        text-align: center;
    }

    .product-table th.name-col,
    .product-table td.name-cell,
    .product-table th.category-col,
    .product-table td.category-cell {
        text-align: left;
    }

    .product-table td.numeric {
        text-align: right;
    }

    /* Quantity < 10: red text only, no background */
    .product-table tr.low-stock td {
        color: #dc2626;
        font-weight: 600;
    }

    body[data-theme="light"] .product-table tr.low-stock td {
        color: #b91c1c;
    }

    .actions a {
        margin: 0 3px;
        padding: 5px 8px;
        font-size: 12px;
        background: var(--accent-gold);
        color: var(--bg-main);
        border-radius: 5px;
        text-decoration: none;
        transition: 0.2s;
        border: none;
        display: inline-block;
    }

    .actions a:hover {
        background: var(--accent-gold-soft);
    }

    .actions .delete {
        background: #e74c3c;
        color: #ffffff;
    }

    .actions .delete:hover {
        background: #c0392b;
    }

    .totals-row {
        font-weight: 600;
        background: rgba(0,0,0,0.04);
    }

    body:not([data-theme="light"]) .totals-row {
        background: #001f3f;
    }

    .totals-row td {
        border-top: 1px solid rgba(0,0,0,0.25);
    }

    body:not([data-theme="light"]) .totals-row td {
        border-top-color: rgba(255,255,255,0.25);
    }

    .empty-row {
        text-align: center;
        padding: 14px;
        color: var(--text-muted);
    }

    .totals-box {
        margin: 26px auto 10px auto;
        color: var(--accent-gold);
        max-width: 520px;
        background: var(--bg-card);
        padding: 16px 18px;
        border-left: 8px solid var(--accent-gold);
        border-radius: 10px;
        text-align: center;
        font-size: 16px;
        font-weight: 600;
        box-shadow: 0 4px 10px rgba(0,0,0,0.3);
    }

    .pagination {
        margin: 20px 0 10px 0;
        text-align: center;
    }

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

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

    .pagination a.active {
        background: var(--accent-gold);
        border-color: var(--accent-gold);
        color: var(--bg-main);
        font-weight: 700;
    }

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

    footer {
        background: transparent;
    }

    @media (max-width: 900px) {
        .content-wrapper {
            margin-left: 0;
            padding: 18px 14px;
        }

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

        .page-header {
            flex-direction: column;
            align-items: flex-start;
        }

        .page-header-right {
            align-items: stretch;
        }

        .product-search {
            justify-content: flex-start;
        }
    }
</style>

</body>
</html>
