<?php

namespace Core\App\Controllers;

use Core\App\Models\Page;
use Core\System\ThemeManager;
use Core\System\SeoManager;

class PageController
{
    public function show(string $slug)
    {
        $slug = urldecode($slug);

        $page = (new Page())->findBySlug($slug);

        if (!$page || $page['status'] !== 'published') {
            http_response_code(404);
            ThemeManager::render('404');
            return;
        }

        /**
         * SEO CONTEXT — CMS PAGE
         * Priority:
         * meta_title > title
         * meta_description > ''
         */
        SeoManager::fromPage([
            'title'            => $page['meta_title']
                ?? $page['title']
                ?? '',
            // ✅ المفتاح الصحيح الذي يقرأه SeoManager
            'meta_description' => $page['meta_description']
                ?? '',
            // ⛑️ نُبقيه للتوافق الخلفي (لا حذف)
            'description'      => $page['meta_description']
                ?? '',
            'image'            => $page['featured_image']
                ?? '',
            'url'              => $page['url']
                ?? null,
        ]);

        ThemeManager::render('page', [
            'page' => $page
        ]);
    }
}
