<?php

require_once BASE_PATH . '/config/database.php';

class ProductCategory
{
    private PDO $db;

    public function __construct()
    {
        $database = new Database();
        $this->db = $database->connect();
    }

    /**
     * Lấy tất cả danh mục đang hoạt động.
     */
    public function getActiveCategories(): array
    {
        $sql = "
            SELECT
                id,
                parent_id,
                name,
                slug,
                description,
                image,
                sort_order
            FROM product_categories
            WHERE is_active = 1
            ORDER BY sort_order ASC, name ASC
        ";

        $stmt = $this->db->query($sql);

        return $stmt->fetchAll();
    }

    /**
     * Tìm danh mục bằng slug.
     */
    public function findBySlug(string $slug): ?array
    {
        $sql = "
            SELECT *
            FROM product_categories
            WHERE slug = :slug
              AND is_active = 1
            LIMIT 1
        ";

        $stmt = $this->db->prepare($sql);

        $stmt->execute([
            'slug' => $slug
        ]);

        $category = $stmt->fetch();

        return $category ?: null;
    }

    /**
     * Tìm danh mục bằng ID.
     */
    public function findById(int $id): ?array
    {
        $sql = "
            SELECT *
            FROM product_categories
            WHERE id = :id
              AND is_active = 1
            LIMIT 1
        ";

        $stmt = $this->db->prepare($sql);

        $stmt->execute([
            'id' => $id
        ]);

        $category = $stmt->fetch();

        return $category ?: null;
    }
    public function getAllForOwner(): array
{
    $sql = "
        SELECT
            pc.*,

            (
                SELECT COUNT(*)

                FROM products p

                WHERE p.category_id = pc.id
            ) AS product_count

        FROM product_categories pc

        ORDER BY
            pc.sort_order ASC,
            pc.name ASC
    ";

    return $this->db
        ->query($sql)
        ->fetchAll();
}


public function findAnyById(
    int $id
): ?array {

    $stmt =
        $this->db->prepare("
            SELECT *

            FROM product_categories

            WHERE id = :id

            LIMIT 1
        ");

    $stmt->execute([
        'id' => $id
    ]);

    $category =
        $stmt->fetch();

    return $category ?: null;
}


public function slugExists(
    string $slug,
    ?int $excludeId = null
): bool {

    $sql = "
        SELECT COUNT(*)

        FROM product_categories

        WHERE slug = :slug
    ";

    $params = [
        'slug' => $slug
    ];

    if ($excludeId !== null) {

        $sql .= "
            AND id != :exclude_id
        ";

        $params['exclude_id'] =
            $excludeId;
    }

    $stmt =
        $this->db->prepare($sql);

    $stmt->execute($params);

    return (int)
        $stmt->fetchColumn() > 0;
}


public function create(
    array $data
): int {

    $stmt =
        $this->db->prepare("
            INSERT INTO product_categories (
                parent_id,
                name,
                slug,
                description,
                image,
                sort_order,
                is_active
            )
            VALUES (
                :parent_id,
                :name,
                :slug,
                :description,
                :image,
                :sort_order,
                :is_active
            )
        ");

    $stmt->execute([
        'parent_id' =>
            $data['parent_id']
            ?: null,

        'name' =>
            $data['name'],

        'slug' =>
            $data['slug'],

        'description' =>
            $data['description']
            ?: null,

        'image' =>
            $data['image']
            ?: null,

        'sort_order' =>
            $data['sort_order'],

        'is_active' =>
            $data['is_active']
    ]);

    return (int)
        $this->db->lastInsertId();
}


public function update(
    int $id,
    array $data
): void {

    $stmt =
        $this->db->prepare("
            UPDATE product_categories

            SET
                parent_id = :parent_id,
                name = :name,
                slug = :slug,
                description = :description,
                sort_order = :sort_order,
                is_active = :is_active

            WHERE id = :id
        ");

    $stmt->execute([
        'parent_id' =>
            $data['parent_id']
            ?: null,

        'name' =>
            $data['name'],

        'slug' =>
            $data['slug'],

        'description' =>
            $data['description']
            ?: null,

        'sort_order' =>
            $data['sort_order'],

        'is_active' =>
            $data['is_active'],

        'id' =>
            $id
    ]);
}


public function toggleActive(
    int $id
): void {

    $stmt =
        $this->db->prepare("
            UPDATE product_categories

            SET is_active =
                CASE
                    WHEN is_active = 1
                    THEN 0
                    ELSE 1
                END

            WHERE id = :id
        ");

    $stmt->execute([
        'id' => $id
    ]);
}
}