<?php
session_start();
require_once 'includes/auth.php';
requireAdmin();
require_once 'config/db.php';

$flash = '';

// ---- Handle Delete ----
if (isset($_GET['delete'])) {
    $del_id = (int) $_GET['delete'];
    // ON DELETE CASCADE handles stock_transactions automatically
    $pdo->prepare("DELETE FROM products WHERE id = ?")->execute([$del_id]);
    $flash = 'Product deleted successfully.';
}

// ---- Search ----
$search = trim($_GET['search'] ?? '');
$params = [];
$where  = '';

if ($search !== '') {
    $where    = "WHERE name LIKE ? OR description LIKE ?";
    $like     = "%{$search}%";
    $params   = [$like, $like];
}

$stmt = $pdo->prepare("SELECT * FROM products {$where} ORDER BY name ASC");
$stmt->execute($params);
$products = $stmt->fetchAll();

include 'includes/header.php';
?>

<div class="row mb-3 align-items-center">
    <div class="col">
        <h4 class="page-title"><i class="bi bi-list-ul me-2 text-primary"></i>Product List</h4>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                <li class="breadcrumb-item active">Products</li>
            </ol>
        </nav>
    </div>
    <div class="col-auto">
        <a href="add_product.php" class="btn btn-primary">
            <i class="bi bi-plus-circle me-1"></i> Add Product
        </a>
    </div>
</div>

<?php if ($flash !== ''): ?>
<div class="alert alert-warning alert-dismissible fade show d-flex align-items-center gap-2">
    <i class="bi bi-check-circle-fill"></i>
    <?= htmlspecialchars($flash) ?>
    <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<div class="card">
    <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center flex-wrap gap-2">
        <span><i class="bi bi-box me-1"></i>All Products
            <span class="badge bg-light text-primary ms-1"><?= count($products) ?></span>
        </span>
        <!-- Search form -->
        <form class="d-flex gap-2" method="GET" action="">
            <input type="text"
                   class="form-control form-control-sm"
                   name="search"
                   value="<?= htmlspecialchars($search) ?>"
                   placeholder="Search by name or description…"
                   style="min-width:220px;">
            <button type="submit" class="btn btn-light btn-sm fw-semibold">
                <i class="bi bi-search"></i>
            </button>
            <?php if ($search !== ''): ?>
            <a href="product_list.php" class="btn btn-outline-light btn-sm">Clear</a>
            <?php endif; ?>
        </form>
    </div>

    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0 align-middle">
                <thead>
                    <tr>
                        <th style="width:40px;">#</th>
                        <th>Product Name</th>
                        <th>Description</th>
                        <th>Unit</th>
                        <th class="text-end" style="width:120px;">Current Stock</th>
                        <th class="text-center" style="width:110px;">Status</th>
                        <th class="text-center" style="width:160px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($products)): ?>
                    <tr>
                        <td colspan="7" class="text-center py-5 text-muted">
                            <i class="bi bi-inbox fs-1 d-block mb-2"></i>
                            <?php if ($search !== ''): ?>
                                No products match "<strong><?= htmlspecialchars($search) ?></strong>".
                                <a href="product_list.php">Clear search</a>
                            <?php else: ?>
                                No products yet. <a href="add_product.php">Add your first product →</a>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($products as $i => $p): ?>
                    <tr class="<?= $p['current_stock'] < 10 ? 'low-stock' : '' ?>">
                        <td class="text-muted small"><?= $i + 1 ?></td>
                        <td class="fw-semibold"><?= htmlspecialchars($p['name']) ?></td>
                        <td class="text-muted small"><?= htmlspecialchars($p['description'] ?: '—') ?></td>
                        <td><?= htmlspecialchars($p['unit']) ?></td>
                        <td class="text-end fw-bold">
                            <span class="
                                <?= $p['current_stock'] === 0
                                    ? 'text-danger'
                                    : ($p['current_stock'] < 10 ? 'text-warning' : 'text-success')
                                ?>">
                                <?= number_format($p['current_stock']) ?>
                            </span>
                        </td>
                        <td class="text-center">
                            <?php if ($p['current_stock'] === 0): ?>
                                <span class="badge bg-danger">Out of Stock</span>
                            <?php elseif ($p['current_stock'] < 10): ?>
                                <span class="badge bg-warning text-dark">Low Stock</span>
                            <?php else: ?>
                                <span class="badge bg-success">In Stock</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-center">
                            <!-- Add Stock -->
                            <a href="stock_add.php?product_id=<?= $p['id'] ?>"
                               class="btn btn-sm btn-success" title="Add Stock">
                                <i class="bi bi-plus-square"></i>
                            </a>
                            <!-- Deduct Stock -->
                            <a href="stock_deduct.php?product_id=<?= $p['id'] ?>"
                               class="btn btn-sm btn-warning text-white" title="Deduct Stock">
                                <i class="bi bi-dash-square"></i>
                            </a>
                            <!-- History -->
                            <a href="stock_history.php?product_id=<?= $p['id'] ?>"
                               class="btn btn-sm btn-info text-white" title="View History">
                                <i class="bi bi-clock-history"></i>
                            </a>
                            <!-- Delete -->
                            <a href="product_list.php?delete=<?= $p['id'] ?>"
                               class="btn btn-sm btn-danger"
                               title="Delete Product"
                               onclick="return confirm('Delete \'<?= addslashes($p['name']) ?>\' and all its stock history? This cannot be undone.')">
                                <i class="bi bi-trash"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <?php if (!empty($products)): ?>
    <div class="card-footer text-muted small">
        Showing <?= count($products) ?> product(s).
        <?php if ($search !== ''): ?>
            — Filtered by "<strong><?= htmlspecialchars($search) ?></strong>"
        <?php endif; ?>
    </div>
    <?php endif; ?>

</div>

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