<?php
class Item {
    private $db;

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

    public function getAllItems() {
        $sql = "
            SELECT i.id, i.name, i.specs, i.price, i.img, GROUP_CONCAT(t.name) AS tags
            FROM items i
            LEFT JOIN item_tags it ON i.id = it.item_id
            LEFT JOIN tags t ON t.id = it.tag_id
            GROUP BY i.id
        ";
        return $this->db->query($sql);
    }

    public function getAllTags() {
        $sql = "SELECT name FROM tags";
        $result = $this->db->query($sql);
        return $result->rows ? array_column($result->rows, 'name') : [];
    }

    
    public function getItemsByTag($tag) {
        $tag = $this->db->escape($tag); // Escape the tag input
        $sql = "
            SELECT i.id, i.name, i.specs, i.price, i.img, GROUP_CONCAT(t.name) AS tags
            FROM items i
            LEFT JOIN item_tags it ON i.id = it.item_id
            LEFT JOIN tags t ON t.id = it.tag_id
            WHERE t.name = '$tag'
            GROUP BY i.id
        ";
        return $this->db->query($sql);
    }

    public function getItemById($id) {
        $sql = "
            SELECT i.*, GROUP_CONCAT(t.name) AS tags
            FROM items i
            LEFT JOIN item_tags it ON i.id = it.item_id
            LEFT JOIN tags t ON t.id = it.tag_id
            WHERE i.id = $id
            GROUP BY i.id
        ";
        return $this->db->query($sql);
    }
}