<?php

declare(strict_types=1);

namespace App\Repositories;

use PDO;

final class CategoryRepository
{
    public function __construct(private PDO $pdo) {}

    public function all(): array
    {
        return $this->pdo->query("SELECT id, name, parent_id, is_active FROM categories ORDER BY name")->fetchAll() ?: [];
    }

    public function findById(int $id): array|false
    {
        $st = $this->pdo->prepare("SELECT id, name, parent_id, is_active FROM categories WHERE id=? LIMIT 1");
        $st->execute([$id]);
        return $st->fetch();
    }

    public function countItemsUsing(int $id): int
    {
        $st = $this->pdo->prepare("SELECT COUNT(*) FROM items WHERE category_id=?");
        $st->execute([$id]);
        return (int)($st->fetchColumn() ?: 0);
    }

    public function create(array $data): int
    {
        $this->pdo->prepare("INSERT INTO categories (name, parent_id, is_active) VALUES (?,?,?)")
            ->execute([$data['name'], $data['parent_id'], $data['is_active']]);
        return (int)$this->pdo->lastInsertId();
    }

    public function update(int $id, array $data): void
    {
        $this->pdo->prepare("UPDATE categories SET name=?, parent_id=?, is_active=? WHERE id=?")
            ->execute([$data['name'], $data['parent_id'], $data['is_active'], $id]);
    }

    public function delete(int $id): void
    {
        $this->pdo->prepare("DELETE FROM categories WHERE id=?")->execute([$id]);
    }
}
