<?php
/**
 * Admin Page for Maple Local Fonts.
 *
 * @package Maple_Local_Fonts
 */

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

/**
 * Class MLF_Admin_Page
 *
 * Handles the admin settings page rendering.
 */
class MLF_Admin_Page {

    /**
     * Constructor.
     */
    public function __construct() {
        // Empty constructor - class is instantiated for rendering
    }

    /**
     * Handle settings form submission.
     */
    private function handle_settings_save() {
        if (!isset($_POST['mlf_save_settings'])) {
            return;
        }

        // Verify nonce
        if (!isset($_POST['mlf_settings_nonce']) || !wp_verify_nonce($_POST['mlf_settings_nonce'], 'mlf_save_settings')) {
            add_settings_error('mlf_settings', 'nonce_error', __('Security check failed.', 'maple-local-fonts'), 'error');
            return;
        }

        // Verify capability
        $capability = function_exists('mlf_get_capability') ? mlf_get_capability() : 'edit_theme_options';
        if (!current_user_can($capability)) {
            return;
        }

        // Save compatibility mode setting
        $compatibility_mode = isset($_POST['mlf_compatibility_mode']) && $_POST['mlf_compatibility_mode'] === '1';
        update_option('mlf_compatibility_mode', $compatibility_mode);

        // Clear font caches to apply new URL format
        delete_transient('mlf_imported_fonts_list');
        if (class_exists('WP_Theme_JSON_Resolver')) {
            WP_Theme_JSON_Resolver::clean_cached_data();
        }

        add_settings_error('mlf_settings', 'settings_saved', __('Settings saved.', 'maple-local-fonts'), 'success');
    }

    /**
     * Render the admin page.
     */
    public function render() {
        $capability = function_exists('mlf_get_capability') ? mlf_get_capability() : 'edit_theme_options';
        if (!current_user_can($capability)) {
            wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'maple-local-fonts'));
        }

        // Handle settings save
        $this->handle_settings_save();

        $registry = new MLF_Font_Registry();
        $installed_fonts = $registry->get_imported_fonts();
        ?>
        <div class="wrap mlf-wrap">
            <h1><?php esc_html_e('Maple Fonts', 'maple-local-fonts'); ?></h1>
            <?php settings_errors('mlf_settings'); ?>
            <p class="mlf-description"><?php esc_html_e('Import Google Fonts to your local server for privacy-friendly, GDPR-compliant typography.', 'maple-local-fonts'); ?></p>

            <div class="mlf-container">
                <!-- Import Section -->
                <div class="mlf-section mlf-import-section">
                    <h2><?php esc_html_e('Import from Google Fonts', 'maple-local-fonts'); ?></h2>

                    <form id="mlf-import-form" class="mlf-form">
                        <!-- Search Input -->
                        <div class="mlf-form-row">
                            <label for="mlf-font-search"><?php esc_html_e('Search Fonts', 'maple-local-fonts'); ?></label>
                            <div class="mlf-search-wrapper">
                                <input type="text"
                                       id="mlf-font-search"
                                       class="mlf-search-input"
                                       placeholder="<?php esc_attr_e('Enter font name...', 'maple-local-fonts'); ?>"
                                       autocomplete="off" />
                                <button type="button" class="button mlf-search-btn" id="mlf-search-btn">
                                    <?php esc_html_e('Search', 'maple-local-fonts'); ?>
                                </button>
                                <span class="spinner mlf-search-spinner" id="mlf-search-spinner"></span>
                            </div>
                            <p class="description"><?php esc_html_e('Enter at least 2 characters and click Search.', 'maple-local-fonts'); ?></p>
                        </div>

                        <!-- Search Results -->
                        <div class="mlf-search-results" id="mlf-search-results" style="display: none;">
                            <div class="mlf-results-list" id="mlf-results-list"></div>
                        </div>

                        <!-- Selected Font (hidden until a font is selected) -->
                        <div class="mlf-selected-font" id="mlf-selected-font" style="display: none;">
                            <div class="mlf-selected-font-header">
                                <span class="mlf-selected-label"><?php esc_html_e('Selected Font:', 'maple-local-fonts'); ?></span>
                                <span class="mlf-selected-name" id="mlf-selected-name"></span>
                                <button type="button" class="mlf-change-font" id="mlf-change-font">
                                    <?php esc_html_e('Change', 'maple-local-fonts'); ?>
                                </button>
                            </div>

                            <!-- Hidden input for font name -->
                            <input type="hidden" id="mlf-font-name" name="font_name" value="" />

                            <div class="mlf-form-row mlf-italic-row">
                                <label class="mlf-checkbox-label mlf-italic-toggle">
                                    <input type="checkbox" name="include_italic" id="mlf-include-italic" value="1" checked />
                                    <span><?php esc_html_e('Include Italic styles', 'maple-local-fonts'); ?></span>
                                </label>
                                <p class="description"><?php esc_html_e('Italic styles are useful for emphasized text. Uncheck to reduce download size.', 'maple-local-fonts'); ?></p>
                            </div>

                            <div class="mlf-form-row mlf-form-row-submit">
                                <button type="submit" class="button button-primary" id="mlf-download-btn">
                                    <?php esc_html_e('Download & Install', 'maple-local-fonts'); ?>
                                </button>
                                <span class="spinner" id="mlf-spinner"></span>
                            </div>
                        </div>

                        <div id="mlf-message" class="mlf-message" style="display: none;"></div>
                    </form>

                    <div class="mlf-info-note">
                        <span class="dashicons dashicons-info-outline"></span>
                        <span><?php esc_html_e('Weights 300-900 (Light to Black) will be downloaded. Variable fonts are used when available, which include all weights in a single efficient file.', 'maple-local-fonts'); ?></span>
                    </div>
                </div>

                <!-- Installed Fonts Section -->
                <div class="mlf-section mlf-installed-section">
                    <div class="mlf-section-header">
                        <h2><?php esc_html_e('Installed Fonts', 'maple-local-fonts'); ?></h2>
                        <?php if (!empty($installed_fonts)) : ?>
                            <button type="button" class="button mlf-check-updates-btn" id="mlf-check-updates">
                                <?php esc_html_e('Check for Updates', 'maple-local-fonts'); ?>
                            </button>
                        <?php endif; ?>
                    </div>

                    <?php if (empty($installed_fonts)) : ?>
                        <p class="mlf-no-fonts"><?php esc_html_e('No fonts installed yet. Search and select a font above to get started.', 'maple-local-fonts'); ?></p>
                    <?php else : ?>
                        <div id="mlf-font-list" class="mlf-font-list">
                            <?php foreach ($installed_fonts as $font) : ?>
                                <div class="mlf-font-item" data-font-id="<?php echo esc_attr($font['id']); ?>" data-font-name="<?php echo esc_attr($font['name']); ?>" data-font-version="<?php echo esc_attr($font['version']); ?>">
                                    <div class="mlf-font-info">
                                        <div class="mlf-font-header">
                                            <h3 class="mlf-font-name"><?php echo esc_html($font['name']); ?></h3>
                                            <span class="mlf-update-badge" style="display: none;"><?php esc_html_e('Update available', 'maple-local-fonts'); ?></span>
                                        </div>
                                        <p class="mlf-font-variants">
                                            <?php
                                            $variant_strings = [];
                                            foreach ($font['variants'] as $variant) {
                                                $variant_strings[] = sprintf('%s %s', $variant['weight'], $variant['style']);
                                            }
                                            echo esc_html(implode(', ', $variant_strings));
                                            ?>
                                        </p>
                                        <p class="mlf-font-meta">
                                            <?php if (!empty($font['version'])) : ?>
                                                <span class="mlf-font-version"><?php echo esc_html($font['version']); ?></span>
                                            <?php endif; ?>
                                            <?php if (!empty($font['last_modified'])) : ?>
                                                <span class="mlf-font-modified"><?php
                                                    /* translators: %s: date */
                                                    printf(esc_html__('Updated: %s', 'maple-local-fonts'), esc_html($font['last_modified']));
                                                ?></span>
                                            <?php endif; ?>
                                        </p>
                                    </div>
                                    <div class="mlf-font-actions">
                                        <button type="button" class="button mlf-update-btn" data-font-id="<?php echo esc_attr($font['id']); ?>" data-font-name="<?php echo esc_attr($font['name']); ?>" style="display: none;">
                                            <?php esc_html_e('Update', 'maple-local-fonts'); ?>
                                        </button>
                                        <button type="button" class="button mlf-delete-btn" data-font-id="<?php echo esc_attr($font['id']); ?>">
                                            <?php esc_html_e('Delete', 'maple-local-fonts'); ?>
                                        </button>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Settings Section -->
                <div class="mlf-section mlf-settings-section">
                    <h2><?php esc_html_e('Settings', 'maple-local-fonts'); ?></h2>
                    <form method="post" action="">
                        <?php wp_nonce_field('mlf_save_settings', 'mlf_settings_nonce'); ?>
                        <div class="mlf-form-row">
                            <label class="mlf-checkbox-label mlf-setting-toggle">
                                <input type="checkbox" name="mlf_compatibility_mode" value="1" <?php checked(get_option('mlf_compatibility_mode', true)); ?> />
                                <span><strong><?php esc_html_e('Compatibility Mode', 'maple-local-fonts'); ?></strong></span>
                            </label>
                            <p class="description">
                                <?php esc_html_e('Enable this if fonts are not loading on mobile devices or behind reverse proxies (Caddy, Nginx, Cloudflare). This serves fonts through WordPress for guaranteed header compatibility.', 'maple-local-fonts'); ?>
                            </p>
                        </div>
                        <div class="mlf-form-row mlf-form-row-submit">
                            <button type="submit" name="mlf_save_settings" class="button button-secondary">
                                <?php esc_html_e('Save Settings', 'maple-local-fonts'); ?>
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Info Section -->
                <div class="mlf-section mlf-info-section">
                    <?php if (wp_is_block_theme()) : ?>
                        <div class="mlf-info-box">
                            <span class="dashicons dashicons-editor-textcolor"></span>
                            <div>
                                <p><strong><?php esc_html_e('How to use your fonts', 'maple-local-fonts'); ?></strong></p>
                                <p>
                                    <?php
                                    printf(
                                        /* translators: %s: link to WordPress Editor */
                                        esc_html__('Go to %s to apply fonts to your site.', 'maple-local-fonts'),
                                        '<a href="' . esc_url(admin_url('site-editor.php?path=%2Fwp_global_styles')) . '">' . esc_html__('Appearance → Editor → Styles → Typography', 'maple-local-fonts') . '</a>'
                                    );
                                    ?>
                                </p>
                            </div>
                        </div>
                    <?php else : ?>
                        <div class="mlf-info-box mlf-info-box-classic">
                            <span class="dashicons dashicons-editor-textcolor"></span>
                            <div class="mlf-classic-theme-info">
                                <p><strong><?php esc_html_e('Classic Theme Detected', 'maple-local-fonts'); ?></strong></p>
                                <p><?php esc_html_e('Your theme does not support the Full Site Editor. To use imported fonts, add custom CSS to your theme:', 'maple-local-fonts'); ?></p>
                                <pre class="mlf-code-example">body {
    font-family: "Open Sans", sans-serif;
}
h1, h2, h3, h4, h5, h6 {
    font-family: "Open Sans", sans-serif;
}</pre>
                                <p class="description">
                                    <?php
                                    printf(
                                        /* translators: %s: link to Customizer */
                                        esc_html__('Add this CSS in %s or your theme\'s style.css file.', 'maple-local-fonts'),
                                        '<a href="' . esc_url(admin_url('customize.php')) . '">' . esc_html__('Appearance → Customize → Additional CSS', 'maple-local-fonts') . '</a>'
                                    );
                                    ?>
                                </p>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php
    }
}
