<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\Model;
use PDO;

/**
 * Page Model
 *
 * Handles static CMS pages with slug-based lookups
 * and published page retrieval.
 */
class Page extends Model
{
    /**
     * The database table associated with the model.
     */
    protected string $table = 'pages';

    /**
     * Get a published page by its slug.
     *
     * @param string $slug The URL-friendly slug to look up
     * @return array<string, mixed>|null The page record or null if not found
     */
    public function getBySlug(string $slug): ?array
    {
        $sql = sprintf(
            'SELECT * FROM `%s` WHERE `slug` = :slug AND `is_published` = :published LIMIT 1',
            $this->table
        );

        $stmt = $this->db->prepare($sql);
        $stmt->execute([':slug' => $slug, ':published' => 1]);

        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        return $result !== false ? $result : null;
    }

    /**
     * Get all published pages.
     *
     * @return array<int, array<string, mixed>> Array of published page records
     */
    public function getPublished(): array
    {
        $sql = sprintf(
            'SELECT * FROM `%s` WHERE `is_published` = :published ORDER BY `title` ASC',
            $this->table
        );

        $stmt = $this->db->prepare($sql);
        $stmt->execute([':published' => 1]);

        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
}
