<?php
namespace CAE\Models;

use CAE\Lib\Database;

class PageType
{
    private Database $db;

    public function __construct()
    {
        $this->db = Database::getInstance();
    }

    public function all(): array
    {
        $rows = $this->db->fetchAll("SELECT * FROM page_types WHERE is_active = 1 ORDER BY name ASC");
        return array_map([$this, 'decode'], $rows);
    }

    public function find(int $id): ?array
    {
        $row = $this->db->fetch("SELECT * FROM page_types WHERE id = ?", [$id]);
        return $row ? $this->decode($row) : null;
    }

    public function findBySlug(string $slug): ?array
    {
        $row = $this->db->fetch("SELECT * FROM page_types WHERE slug = ?", [$slug]);
        return $row ? $this->decode($row) : null;
    }

    public function allForSelect(): array
    {
        return $this->db->fetchAll("SELECT id, name, category FROM page_types WHERE is_active = 1 ORDER BY name");
    }

    private function decode(array $row): array
    {
        foreach (['structure_rules', 'seo_rules', 'content_blocks'] as $field) {
            if (!empty($row[$field]) && is_string($row[$field])) {
                $row[$field] = json_decode($row[$field], true) ?? [];
            }
        }
        return $row;
    }
}
