<?php
require_once __DIR__ . '/../../../core/Database.php';
require_once __DIR__ . '/Subcategory.php';

class Category extends Database {

    public function createCategory($category_name) {
        $sql = "INSERT INTO categories (category_name) VALUES (?)";
        return $this->executeNonQuery($sql, [$category_name]);
    }

    public function getCategories() {
        $sql = "SELECT * FROM categories ORDER BY category_name";
        return $this->executeQuery($sql);
    }

    public function getCategoriesWithSubcategories() {
        $categories = $this->getCategories();
        $result = [];
        $subcategory = new Subcategory();
        foreach ($categories as $category) {
            $subcategories = $subcategory->getSubcategoriesByCategoryId($category['category_id']);
            $category['subcategories'] = $subcategories;
            $result[] = $category;
        }
        return $result;
    }

    public function getCategory($category_id) {
        $sql = "SELECT * FROM categories WHERE category_id = ?";
        return $this->executeQuerySingle($sql, [$category_id]);
    }

    public function updateCategory($category_id, $category_name) {
        $sql = "UPDATE categories SET category_name = ? WHERE category_id = ?";
        return $this->executeNonQuery($sql, [$category_name, $category_id]);
    }

    public function deleteCategory($category_id) {
        $subcategory = new Subcategory();
        $subcategories = $subcategory->getSubcategoriesByCategoryId($category_id);

        foreach ($subcategories as $sub) {
            $subcategory->deleteSubcategory($sub['subcategory_id']);
        }

        $sql = "DELETE FROM categories WHERE category_id = ?";
        return $this->executeNonQuery($sql, [$category_id]);
    }
}
?>