<?php

namespace Core\App\Controllers;

use Core\System\ThemeManager;
use Core\System\Request;
use Core\System\Response;
use Core\App\Models\Page;

class HeaderController
{
    /**
     * Show Header Menu Builder page
     */
    public function index()
    {
        $menu = ThemeManager::getSetting('header_menu', []);

        view_admin('appearance/header_menu', [
            'menu' => $menu
        ]);
    }

    /**
     * Save Header Menu
     */
    public function save()
    {
        $data = Request::input();
        $menu = $data['menu'] ?? [];

        $pagesModel = new Page();
        $menuPages  = $pagesModel->getMenuPages();

        // Index pages by slug for quick lookup
        $pagesBySlug = [];
        foreach ($menuPages as $page) {
            $pagesBySlug[$page['slug']] = $page;
        }

        // Normalize menu items
        $normalized = [];

        foreach ($menu as $item) {

            if (empty($item['label'])) {
                continue;
            }

            $type = $item['type'] ?? 'custom';
            $url  = '';

            if ($type === 'home') {
                $url = '/';
            }
            elseif ($type === 'page') {
                $slug = $item['page_slug'] ?? null;

                if (!$slug || !isset($pagesBySlug[$slug])) {
                    continue;
                }

                    $url = '/page/' . ltrim($slug, '/');
            }
            else { // custom
                if (empty($item['url'])) {
                    continue;
                }
                $url = trim($item['url']);
            }

            $normalized[] = [
                'label'   => trim($item['label']),
                'url'     => $url,
                'type'    => $type,
                'enabled' => isset($item['enabled']) ? 1 : 0,
                'order'   => (int)($item['order'] ?? 0),
            ];
        }

        // Sort by order
        usort($normalized, function ($a, $b) {
            return $a['order'] <=> $b['order'];
        });

        ThemeManager::setSetting('header_menu', $normalized);

        // Flash success message (clean URL)
        $_SESSION['success'] = __('header.menu_saved', 'Header menu saved successfully.');

        return Response::redirect('/admin/appearance/header');
    }
}
