<?php

namespace Formatrica\Admin\Pages;

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

final class Settings_Page
{
    public function boot(): void
    {
        add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
    }

    public function enqueue_assets(): void
    {
        if (!$this->is_settings_screen()) {
            return;
        }

        if (!current_user_can('manage_options')) {
            return;
        }

        wp_enqueue_script('formatrica-admin');
        wp_set_script_translations('formatrica-admin', 'formatrica', FORMATRICA_PATH . 'languages');

        if (wp_style_is('formatrica-admin-style', 'registered')) {
            wp_enqueue_style('formatrica-admin-style');
        }

        $email_settings = get_option('formatrica_settings', []);
        $email = is_array($email_settings['email'] ?? null) ? $email_settings['email'] : [];

        wp_localize_script(
            'formatrica-admin',
            'formatricaSettings',
            [
                'restUrl' => esc_url_raw(rest_url('formatrica/v1')),
                'nonce' => wp_create_nonce('wp_rest'),
                'defaults' => [
                    'from_name' => get_bloginfo('name'),
                    'from_email' => $this->default_from_email(),
                    'recipient' => get_option('admin_email'),
                ],
            ]
        );
    }

    public function render(): void
    {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to access this page.', 'formatrica'));
        }

        echo '<div class="wrap">';
        $icon_url = FORMATRICA_URL . 'assets/formatrica.svg';
        echo '<h1 class="wp-heading-inline"><img src="' . esc_url($icon_url) . '" alt="' . esc_attr__('Formatrica', 'formatrica') . '" style="width:24px;height:24px;margin-right:8px;vertical-align:middle;" />' . esc_html__('Forms Settings', 'formatrica') . '</h1>';
        echo '<hr class="wp-header-end" />';
        if (!wp_script_is('formatrica-admin', 'enqueued')) {
            echo '<div class="notice notice-warning"><p>' . esc_html__('Settings UI assets are not loaded. Run the asset build (npm install && npm run build) so the interface can render.', 'formatrica') . '</p></div>';
        }
        echo '<div id="formatrica-settings"></div>';
        echo '</div>';
    }

    private function is_settings_screen(): bool
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- admin screen check, no data modification
        return isset($_GET['page']) && $_GET['page'] === 'formatrica-settings';
    }

    private function default_from_email(): string
    {
        $domain = wp_parse_url(home_url(), PHP_URL_HOST);
        if (!is_string($domain) || empty($domain)) {
            $domain = 'example.com';
        }
        return 'noreply@' . preg_replace('/^www\./', '', $domain);
    }
}
