<?php

namespace Formatrica\Admin;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

use Formatrica\Admin\Pages\Form_Builder_Page;
use Formatrica\Admin\Pages\Form_List_Page;
use Formatrica\Admin\Pages\License_Page;
use Formatrica\Admin\Pages\Settings_Page;
use Formatrica\Capability\Feature_Gate;

final class Menu
{
    private Form_List_Page $list_page;
    private Form_Builder_Page $builder_page;
    private Settings_Page $settings_page;
    private ?License_Page $license_page = null;
    private \Formatrica\Admin\Pages\Submissions_Page $submissions_page;

    public function __construct(?Feature_Gate $gate = null)
    {
        $this->submissions_page = new \Formatrica\Admin\Pages\Submissions_Page();
        $this->list_page = new Form_List_Page();
    $this->builder_page = new Form_Builder_Page($gate);
        $this->builder_page->boot();
    $this->settings_page = new Settings_Page();
    $this->settings_page->boot();
        // License_Page.php is stripped from the wporg package. Only construct it
        // when the class is present (selfhost/pro), mirroring the class_exists
        // guards used for every other package-stripped class.
        if (class_exists(License_Page::class)) {
            $this->license_page = new License_Page($gate);
            $this->license_page->boot();
        }
    }

    public function register_menu(): void
    {
        $capability = 'manage_options';

        // Load custom menu icon from SVG file
        $icon_file = FORMATRICA_PATH . 'assets/formatrica-mono.svg';
        if (file_exists($icon_file)) {
            $icon_svg = file_get_contents($icon_file);
            // Remove XML declaration and DOCTYPE for cleaner base64 encoding
            $icon_svg = preg_replace('/<\?xml.*?\?>\s*/s', '', $icon_svg);
            $icon_svg = preg_replace('/<!DOCTYPE.*?>\s*/s', '', $icon_svg);
            $icon_svg = preg_replace('/<!--.*?-->\s*/s', '', $icon_svg);
            $icon_svg = trim($icon_svg);
            $icon = 'data:image/svg+xml;base64,' . base64_encode($icon_svg);
        } else {
            $icon = 'dashicons-feedback';
        }

        $hook = add_menu_page(
            __('Formatrica', 'formatrica'),
            __('Formatrica', 'formatrica'),
            $capability,
            'formatrica',
            [$this->list_page, 'render'],
            $icon,
            25
        );

        $list_hook = add_submenu_page(
            'formatrica',
            __('Forms', 'formatrica'),
            __('Forms', 'formatrica'),
            $capability,
            'formatrica',
            [$this->list_page, 'render']
        );

        $builder_hook = add_submenu_page(
            'formatrica',
            __('Create Form', 'formatrica'),
            __('Create Form', 'formatrica'),
            $capability,
            'formatrica-builder',
            [$this->builder_page, 'render']
        );

        $submissions_hook = add_submenu_page(
            'formatrica',
            __('Submissions', 'formatrica'),
            __('Submissions', 'formatrica'),
            $capability,
            'formatrica-submissions',
            [$this->submissions_page, 'render']
        );
        // Process bulk delete/export before any output so redirects can send
        // headers (see Submissions_Page::load()).
        add_action("load-{$submissions_hook}", [$this->submissions_page, 'load']);

        $settings_hook = add_submenu_page(
            'formatrica',
            __('Settings', 'formatrica'),
            __('Settings', 'formatrica'),
            $capability,
            'formatrica-settings',
            [$this->settings_page, 'render']
        );

        // No license surface in the Free packages (wporg, selfhost). The page
        // object is also null there (the class is stripped), so guard on both.
        if ($this->license_page !== null
            && (!defined('FORMATRICA_PACKAGE')
                || !in_array(FORMATRICA_PACKAGE, ['wporg', 'selfhost'], true))) {
            add_submenu_page(
                'formatrica',
                __('License', 'formatrica'),
                __('License', 'formatrica'),
                $capability,
                'formatrica-license',
                [$this->license_page, 'render']
            );
        }

        add_action("load-{$hook}", [$this->list_page, 'load']);

        // Add admin styles to ensure icon displays correctly
    add_action('admin_head', [$this, 'add_menu_icon_styles']);
    }

    public function add_menu_icon_styles(): void
    {
        $css = '#adminmenu #toplevel_page_formatrica .wp-menu-image img {'
            . 'width:20px;height:20px;padding:6px 0 !important;'
            . 'filter:brightness(0) saturate(100%) invert(50%) sepia(0%) saturate(0%) hue-rotate(0deg) brightness(94%) contrast(86%);'
            . '}'
            . '#adminmenu #toplevel_page_formatrica:hover .wp-menu-image img {'
            . 'filter:brightness(0) saturate(100%) invert(100%);'
            . '}'
            . '#adminmenu #toplevel_page_formatrica.current .wp-menu-image img,'
            . '#adminmenu #toplevel_page_formatrica.wp-has-current-submenu .wp-menu-image img {'
            . 'filter:brightness(0) saturate(100%) invert(100%);'
            . '}';

        $css = wp_kses_no_null($css, ['slash_zero' => 'keep']);
        $css = preg_replace('#</style#i', '<\\/style', $css);
        wp_register_style('formatrica-menu-icon', false, [], FORMATRICA_VERSION);
        wp_enqueue_style('formatrica-menu-icon');
        wp_add_inline_style('formatrica-menu-icon', $css);
    }
}
