<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\Database;
use Throwable;

/**
 * Lecture des pages éditoriales publiées (accueil, mentions légales…).
 */
final class Page
{
    /** @var array<string,array<string,mixed>|null> */
    private static array $cache = [];

    /** @return array<string,mixed>|null */
    public static function findPublishedBySlug(string $slug): ?array
    {
        if (array_key_exists($slug, self::$cache)) {
            return self::$cache[$slug];
        }

        try {
            $pdo  = Database::connection();
            $stmt = $pdo->prepare("SELECT * FROM pages WHERE slug = :slug AND status = 'published' LIMIT 1");
            $stmt->execute(['slug' => $slug]);
            $row = $stmt->fetch();
            self::$cache[$slug] = $row === false ? null : $row;
        } catch (Throwable) {
            self::$cache[$slug] = null;
        }

        return self::$cache[$slug];
    }

    public static function isPublished(string $slug): bool
    {
        return self::findPublishedBySlug($slug) !== null;
    }
}
