<?php
session_start();

require_once '../../config/database.php';
require_once '../../includes/auth.php';

$db = (new Database())->connect();

$action = $_GET['action'] ?? '';

if ($action === 'categories') {
    loadCategories($db);
    exit;
}

if ($action === 'items') {
    loadItems($db);
    exit;
}

function loadCategories($db)
{
    $stmt = $db->prepare("SELECT * FROM categories ORDER BY name ASC");
    $stmt->execute();
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo '<button class="btn btn-primary category-btn" onclick="loadItems()">All</button>';

    foreach ($categories as $category) {
        echo '<button 
                class="btn btn-outline-primary category-btn"
                onclick="loadItems(' . (int)$category['id'] . ')">
                ' . htmlspecialchars($category['name']) . '
              </button>';
    }
}

function loadItems($db)
{
    $category = $_GET['category'] ?? '';
    $search = trim($_GET['search'] ?? '');

    $sql = "SELECT * FROM items WHERE 1=1";
    $params = [];

    if (!empty($category)) {
        $sql .= " AND category_id = ?";
        $params[] = $category;
    }

    if (!empty($search)) {
        $sql .= " AND name LIKE ?";
        $params[] = '%' . $search . '%';
    }

    $sql .= " ORDER BY name ASC";

    $stmt = $db->prepare($sql);
    $stmt->execute($params);

    $items = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (!$items) {
        echo '
            <div class="col-12">
                <div class="alert alert-warning">
                    No items found.
                </div>
            </div>
        ';
        return;
    }

    foreach ($items as $item) {
        $itemId = (int)$item['id'];
        $itemName = htmlspecialchars($item['name']);
        $price = number_format((float)$item['price'], 2);
        $stock = isset($item['stock']) ? (float)$item['stock'] : 0;
        $imagePath = !empty($item['image_path'])
            ? '../../assets/images/' . trim($item['image_path'])
            : '../../assets/images/no_image.jpg';

        echo '
            <div class="col-md-3 mb-3">
                <div class="card item-card shadow-sm" onclick="addToCart(' . $itemId . ')">

                    <img 
                        src="' . $imagePath . '" 
                        class="card-img-top item-img"
                        alt="' . $itemName . '"
                    >

                    <div class="card-body text-center">
                        <h6>' . $itemName . '</h6>
                        <p class="mb-1">₹ ' . $price . '</p>
                        <small class="text-muted">Stock: ' . $stock . '</small>
                    </div>

                </div>
            </div>
        ';
    }
}
?>