<?php

namespace App\Models;

use App\Core\Model;

class Page extends Model
{
    protected static string $table = 'iw_pages';

    public static function published(string $orderBy = 'sort_order', string $direction = 'ASC'): array
    {
        return static::where(['status' => 'published'], $orderBy, $direction);
    }

    public static function homepage(): ?array
    {
        return static::findWhere(['is_homepage' => 1, 'status' => 'published']);
    }

    /**
     * Most recently updated pages for the admin dashboard (lightweight).
     */
    public static function recentlyUpdated(int $limit = 5): array
    {
        $limit = max(1, min(50, $limit));
        return static::db()->fetchAll(
            "SELECT id, title, slug, status, updated_at
             FROM iw_pages
             ORDER BY updated_at DESC
             LIMIT {$limit}"
        );
    }

    /**
     * Find a page by its page_type.
     * Used to look up system/module pages (gallery, blog, events, downloads).
     *
     * Returns null gracefully if the page_type column does not yet exist
     * (e.g. migration 021 has not been applied). This prevents HTTP 500
     * errors on systems that have updated files but not yet run the migration.
     */
    public static function findByType(string $pageType): ?array
    {
        try {
            return static::db()->fetch(
                "SELECT * FROM iw_pages WHERE page_type = :page_type LIMIT 1",
                ['page_type' => $pageType]
            );
        } catch (\PDOException $e) {
            // Column does not exist (MySQL error 1054) – migration 021 not yet applied
            if (strpos($e->getMessage(), '1054') !== false || stripos($e->getMessage(), 'Unknown column') !== false) {
                return null;
            }
            throw $e;
        }
    }

    /**
     * List of system page types that should not be deleted or have their slug changed.
     */
    public static function systemPageTypes(): array
    {
        return ['home', 'contact', 'gallery', 'blog', 'events', 'downloads'];
    }

    /**
     * Check if a page is a system/module page.
     */
    public static function isSystemPage(array $page): bool
    {
        $type = $page['page_type'] ?? 'page';
        return in_array($type, static::systemPageTypes(), true);
    }
}
