<?php
// ============================================================
// backend/api/products/ProductController.php
// ============================================================

class ProductController {

    private PDO $db;

    public function __construct() {
        $this->db = getDB();
    }

    // GET /products  — supports ?category=&featured=1&search=
    public function index(): void {
        $sql    = 'SELECT * FROM products WHERE 1=1';
        $params = [];

        if (!empty($_GET['category'])) {
            $sql .= ' AND category = ?';
            $params[] = $_GET['category'];
        }
        if (!empty($_GET['featured'])) {
            $sql .= ' AND featured = 1';
        }
        if (!empty($_GET['search'])) {
            $sql .= ' AND (name LIKE ? OR description LIKE ?)';
            $like = '%' . $_GET['search'] . '%';
            $params[] = $like;
            $params[] = $like;
        }

        $sql .= ' ORDER BY featured DESC, created_at DESC';
        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        sendSuccess($stmt->fetchAll());
    }

    // GET /products/{id}
    public function show(string $id): void {
        $stmt = $this->db->prepare('SELECT * FROM products WHERE id = ?');
        $stmt->execute([$id]);
        $product = $stmt->fetch();
        if (!$product) sendError('Product not found', 404);
        sendSuccess($product);
    }
}
