<?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
    {
        $direction = strtoupper($direction) === 'ASC' ? 'ASC' : 'DESC';
        $allowed   = ['sort_order', 'title', 'created_at', 'updated_at'];
        $orderBy   = in_array($orderBy, $allowed, true) ? $orderBy : 'sort_order';

        return static::db()->fetchAll(
            "SELECT * FROM iw_pages
             WHERE status = 'published'
               AND (unpublish_at IS NULL OR unpublish_at > NOW())
             ORDER BY {$orderBy} {$direction}"
        );
    }

    public static function homepage(): ?array
    {
        return static::db()->fetch(
            "SELECT * FROM iw_pages
             WHERE is_homepage = 1 AND status = 'published'
               AND (unpublish_at IS NULL OR unpublish_at > NOW())
             LIMIT 1"
        );
    }

    /**
     * Check if a page is currently visible on the frontend.
     * Accounts for scheduling window (publish_at / unpublish_at).
     */
    public static function isVisible(array $page): bool
    {
        if ($page['status'] === 'published') {
            if (!empty($page['unpublish_at']) && strtotime($page['unpublish_at']) <= time()) {
                return false;
            }
            return true;
        }
        // Scheduled page whose publish_at has passed (cron hasn't run yet)
        if ($page['status'] === 'scheduled' && !empty($page['publish_at']) && strtotime($page['publish_at']) <= time()) {
            if (!empty($page['unpublish_at']) && strtotime($page['unpublish_at']) <= time()) {
                return false;
            }
            return true;
        }
        return false;
    }

    /**
     * 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', '404'];
    }

    /**
     * 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);
    }
}
