<?php
/**
 * Name: Custom Fonts Manager
 * Description: Upload custom web fonts for body text and headings with live CSS preview to use brand typography, Google Fonts alternatives, or premium fonts
 * Category: Utilities
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Add Useful Functionality",
 *     "description": "Extend WordPress with helpful tools that make site management easier."
 *   },
 *   {
 *     "title": "Save Time",
 *     "description": "Automate or simplify tasks that would otherwise require manual work or additional tools."
 *   }
 * ]
 * Added: 2025-09-02
 * Tags: fonts, typography, custom-fonts, webfonts, design
 * WhereToFind: {
 *   "location": "Throughout Your Site",
 *   "url": "",
 *   "instructions": "Upload WOFF2/WOFF/TTF font files in module settings and assign to body text or headings. Custom fonts apply across entire site when enabled.",
 *   "newTab": false
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardCustomFontsManager {
    
    public function __construct() {
        add_action('wp_head', [$this, 'add_custom_fonts'], 1);
        add_filter('upload_mimes', [$this, 'allow_font_uploads']);
        add_filter('wp_check_filetype_and_ext', [$this, 'check_filetype_and_ext'], 10, 4);
    }
    
    public function allow_font_uploads($mimes) {
        // Allow font file uploads
        $mimes['woff'] = 'font/woff';
        $mimes['woff2'] = 'font/woff2';
        $mimes['ttf'] = 'font/ttf';
        $mimes['otf'] = 'font/otf';
        $mimes['eot'] = 'application/vnd.ms-fontobject';

        return $mimes;
    }

    public function check_filetype_and_ext($data, $file, $filename, $mimes) {
        // If already valid, return early
        if (!empty($data['ext']) && !empty($data['type'])) {
            return $data;
        }

        // Get file extension
        $filetype = wp_check_filetype($filename, $mimes);
        $ext = $filetype['ext'];
        $type = $filetype['type'];

        // Check if it's a font file
        if (in_array($ext, ['woff', 'woff2', 'ttf', 'otf', 'eot'], true)) {
            $data['ext'] = $ext;
            $data['type'] = $type;
            $data['proper_filename'] = $filename;
        }

        return $data;
    }
    
    public function add_custom_fonts() {
        // Get settings from JSON structure
        $settings = get_option('switchboard_custom-fonts-manager_settings', []);

        $body_name = isset($settings['body']['name']) ? $settings['body']['name'] : '';
        $body_woff2 = isset($settings['body']['woff2']) ? $settings['body']['woff2'] : '';
        $body_woff = isset($settings['body']['woff']) ? $settings['body']['woff'] : '';
        $body_ttf = isset($settings['body']['ttf']) ? $settings['body']['ttf'] : '';
        $body_enabled = isset($settings['body']['enabled']) ? $settings['body']['enabled'] : 0;

        $heading_name = isset($settings['heading']['name']) ? $settings['heading']['name'] : '';
        $heading_woff2 = isset($settings['heading']['woff2']) ? $settings['heading']['woff2'] : '';
        $heading_woff = isset($settings['heading']['woff']) ? $settings['heading']['woff'] : '';
        $heading_ttf = isset($settings['heading']['ttf']) ? $settings['heading']['ttf'] : '';
        $heading_enabled = isset($settings['heading']['enabled']) ? $settings['heading']['enabled'] : 0;
        
        if (empty($body_name) && empty($heading_name)) {
            return;
        }
        
        echo '<style id="switchboard-custom-fonts">';
        
        // Body font with fallback chain
        if (!empty($body_name) && (!empty($body_woff2) || !empty($body_woff) || !empty($body_ttf))) {
            echo "\n@font-face {";
            echo "\n    font-family: '" . esc_attr($body_name) . "';";
            echo "\n    src: ";
            
            $sources = [];
            if (!empty($body_woff2)) {
                $sources[] = "url('" . esc_url($body_woff2) . "') format('woff2')";
            }
            if (!empty($body_woff)) {
                $sources[] = "url('" . esc_url($body_woff) . "') format('woff')";
            }
            if (!empty($body_ttf)) {
                $sources[] = "url('" . esc_url($body_ttf) . "') format('truetype')";
            }
            
            echo implode(",\n         ", $sources) . ";"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- URLs are escaped with esc_url() above
            echo "\n    font-weight: normal;";
            echo "\n    font-style: normal;";
            echo "\n    font-display: swap;";
            echo "\n}";

            if ($body_enabled) {
                echo "\nbody, p, div, span, li, td, th, input, textarea, select, button {";
                echo "\n    font-family: '" . esc_attr($body_name) . "', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;";
                echo "\n}";
            }
        }
        
        // Heading font with fallback chain
        if (!empty($heading_name) && (!empty($heading_woff2) || !empty($heading_woff) || !empty($heading_ttf))) {
            echo "\n@font-face {";
            echo "\n    font-family: '" . esc_attr($heading_name) . "';";
            echo "\n    src: ";
            
            $sources = [];
            if (!empty($heading_woff2)) {
                $sources[] = "url('" . esc_url($heading_woff2) . "') format('woff2')";
            }
            if (!empty($heading_woff)) {
                $sources[] = "url('" . esc_url($heading_woff) . "') format('woff')";
            }
            if (!empty($heading_ttf)) {
                $sources[] = "url('" . esc_url($heading_ttf) . "') format('truetype')";
            }
            
            echo implode(",\n         ", $sources) . ";"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- URLs are escaped with esc_url() above
            echo "\n    font-weight: normal;";
            echo "\n    font-style: normal;";
            echo "\n    font-display: swap;";
            echo "\n}";

            if ($heading_enabled) {
                echo "\nh1, h2, h3, h4, h5, h6, .site-title, .entry-title {";
                echo "\n    font-family: '" . esc_attr($heading_name) . "', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;";
                echo "\n}";
            }
        }
        
        echo "\n</style>\n";
    }

    /**
     * Render settings panel
     *
     * @param array $settings Current module settings
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
                    // Get settings from JSON structure
                    $body_name = isset($settings['body']['name']) ? $settings['body']['name'] : '';
                    $body_woff2 = isset($settings['body']['woff2']) ? $settings['body']['woff2'] : '';
                    $body_woff = isset($settings['body']['woff']) ? $settings['body']['woff'] : '';
                    $body_ttf = isset($settings['body']['ttf']) ? $settings['body']['ttf'] : '';
                    $body_enabled = isset($settings['body']['enabled']) ? $settings['body']['enabled'] : 0;

                    $heading_name = isset($settings['heading']['name']) ? $settings['heading']['name'] : '';
                    $heading_woff2 = isset($settings['heading']['woff2']) ? $settings['heading']['woff2'] : '';
                    $heading_woff = isset($settings['heading']['woff']) ? $settings['heading']['woff'] : '';
                    $heading_ttf = isset($settings['heading']['ttf']) ? $settings['heading']['ttf'] : '';
                    $heading_enabled = isset($settings['heading']['enabled']) ? $settings['heading']['enabled'] : 0;
                    
                    $html = '
                        <input type="hidden" name="module" value="custom-fonts-manager">

                        <div class="sb-module-card sb-module-form-section" style="margin-bottom: 24px;">
                            <div class="sb-module-card-header">
                                <div class="sb-module-card-header-left">
                                    <h2 class="sb-module-card-title">' . esc_html__('Body Font', 'wpswitchboard') . '</h2>
                                    <p class="sb-module-card-desc">' . esc_html__('Used for paragraphs, lists, and general text', 'wpswitchboard') . '</p>
                                </div>
                            </div>
                            <div class="sb-module-card-body">
                                <div class="sb-module-form-group">
                                    <label for="setting_body_name" class="sb-module-form-label">' . esc_html__('Font Name', 'wpswitchboard') . '</label>
                                    <input type="text" name="setting_body_name" id="setting_body_name" value="' . esc_attr($body_name) . '" placeholder="' . esc_attr__('e.g., Inter, Open Sans', 'wpswitchboard') . '" class="sb-module-form-input">
                                    <p class="sb-module-form-help">' . esc_html__('Enter the name of your font (e.g., "Inter", "Open Sans")', 'wpswitchboard') . '</p>
                                </div>

                                <div class="sb-module-form-group">
                                    <label for="setting_body_woff2" class="sb-module-form-label">' . esc_html__('WOFF2 (Recommended)', 'wpswitchboard') . '</label>
                                    <div class="sb-sp-flex sb-sp-gap-2">
                                        <input type="url" name="setting_body_woff2" id="setting_body_woff2" value="' . esc_attr($body_woff2) . '" placeholder="https://example.com/font.woff2" class="sb-module-form-input sb-sp-flex-1">
                                        <button type="button" class="button button-secondary button-small upload-font-btn" data-target="setting_body_woff2">' . esc_html__('Upload', 'wpswitchboard') . '</button>
                                    </div>
                                    <p class="sb-module-form-help">' . esc_html__('Best performance - smallest file size, fastest loading', 'wpswitchboard') . '</p>
                                </div>

                                <div class="sb-module-form-group">
                                    <label for="setting_body_woff" class="sb-module-form-label">' . esc_html__('WOFF (Fallback)', 'wpswitchboard') . '</label>
                                    <div class="sb-sp-flex sb-sp-gap-2">
                                        <input type="url" name="setting_body_woff" id="setting_body_woff" value="' . esc_attr($body_woff) . '" placeholder="https://example.com/font.woff" class="sb-module-form-input sb-sp-flex-1">
                                        <button type="button" class="button button-secondary button-small upload-font-btn" data-target="setting_body_woff">' . esc_html__('Upload', 'wpswitchboard') . '</button>
                                    </div>
                                    <p class="sb-module-form-help">' . esc_html__('Fallback format for older browsers', 'wpswitchboard') . '</p>
                                </div>

                                <div class="sb-module-form-group">
                                    <label for="setting_body_ttf" class="sb-module-form-label">' . esc_html__('TTF (Legacy)', 'wpswitchboard') . '</label>
                                    <div class="sb-sp-flex sb-sp-gap-2">
                                        <input type="url" name="setting_body_ttf" id="setting_body_ttf" value="' . esc_attr($body_ttf) . '" placeholder="https://example.com/font.ttf" class="sb-module-form-input sb-sp-flex-1">
                                        <button type="button" class="button button-secondary button-small upload-font-btn" data-target="setting_body_ttf">' . esc_html__('Upload', 'wpswitchboard') . '</button>
                                    </div>
                                    <p class="sb-module-form-help">' . esc_html__('Legacy format for maximum compatibility', 'wpswitchboard') . '</p>
                                </div>

                                <div class="sb-module-form-group" style="margin-bottom: 0;">
                                    <label class="sb-module-form-label">' . esc_html__('Apply to Body Text', 'wpswitchboard') . '</label>
                                    <label class="sb-module-toggle' . (empty($body_name) || (empty($body_woff2) && empty($body_woff) && empty($body_ttf)) ? ' sb-toggle-disabled' : '') . '">
                                        <input type="checkbox" name="setting_body_enabled" id="setting_body_enabled" value="1" ' . checked($body_enabled, 1, false) . (empty($body_name) || (empty($body_woff2) && empty($body_woff) && empty($body_ttf)) ? ' disabled' : '') . '>
                                        <span class="sb-module-toggle-slider"></span>
                                    </label>
                                    <p class="sb-module-form-help">' . esc_html__('Automatically apply this font to all body text, paragraphs, lists, and general content', 'wpswitchboard') . '</p>
                                </div>
                            </div>
                        </div>

                        <div class="sb-module-card sb-module-form-section" style="margin-bottom: 24px;">
                            <div class="sb-module-card-header">
                                <div class="sb-module-card-header-left">
                                    <h2 class="sb-module-card-title">' . esc_html__('Heading Font', 'wpswitchboard') . '</h2>
                                    <p class="sb-module-card-desc">' . esc_html__('Used for titles and headings (h1-h6)', 'wpswitchboard') . '</p>
                                </div>
                            </div>
                            <div class="sb-module-card-body">
                                <div class="sb-module-form-group">
                                    <label for="setting_heading_name" class="sb-module-form-label">' . esc_html__('Font Name', 'wpswitchboard') . '</label>
                                    <input type="text" name="setting_heading_name" id="setting_heading_name" value="' . esc_attr($heading_name) . '" placeholder="' . esc_attr__('e.g., Poppins, Montserrat', 'wpswitchboard') . '" class="sb-module-form-input">
                                    <p class="sb-module-form-help">' . esc_html__('Enter the name of your font (e.g., "Poppins", "Montserrat")', 'wpswitchboard') . '</p>
                                </div>

                                <div class="sb-module-form-group">
                                    <label for="setting_heading_woff2" class="sb-module-form-label">' . esc_html__('WOFF2 (Recommended)', 'wpswitchboard') . '</label>
                                    <div class="sb-sp-flex sb-sp-gap-2">
                                        <input type="url" name="setting_heading_woff2" id="setting_heading_woff2" value="' . esc_attr($heading_woff2) . '" placeholder="https://example.com/font.woff2" class="sb-module-form-input sb-sp-flex-1">
                                        <button type="button" class="button button-secondary button-small upload-font-btn" data-target="setting_heading_woff2">' . esc_html__('Upload', 'wpswitchboard') . '</button>
                                    </div>
                                    <p class="sb-module-form-help">' . esc_html__('Best performance - smallest file size, fastest loading', 'wpswitchboard') . '</p>
                                </div>

                                <div class="sb-module-form-group">
                                    <label for="setting_heading_woff" class="sb-module-form-label">' . esc_html__('WOFF (Fallback)', 'wpswitchboard') . '</label>
                                    <div class="sb-sp-flex sb-sp-gap-2">
                                        <input type="url" name="setting_heading_woff" id="setting_heading_woff" value="' . esc_attr($heading_woff) . '" placeholder="https://example.com/font.woff" class="sb-module-form-input sb-sp-flex-1">
                                        <button type="button" class="button button-secondary button-small upload-font-btn" data-target="setting_heading_woff">' . esc_html__('Upload', 'wpswitchboard') . '</button>
                                    </div>
                                    <p class="sb-module-form-help">' . esc_html__('Fallback format for older browsers', 'wpswitchboard') . '</p>
                                </div>

                                <div class="sb-module-form-group">
                                    <label for="setting_heading_ttf" class="sb-module-form-label">' . esc_html__('TTF (Legacy)', 'wpswitchboard') . '</label>
                                    <div class="sb-sp-flex sb-sp-gap-2">
                                        <input type="url" name="setting_heading_ttf" id="setting_heading_ttf" value="' . esc_attr($heading_ttf) . '" placeholder="https://example.com/font.ttf" class="sb-module-form-input sb-sp-flex-1">
                                        <button type="button" class="button button-secondary button-small upload-font-btn" data-target="setting_heading_ttf">' . esc_html__('Upload', 'wpswitchboard') . '</button>
                                    </div>
                                    <p class="sb-module-form-help">' . esc_html__('Legacy format for maximum compatibility', 'wpswitchboard') . '</p>
                                </div>

                                <div class="sb-module-form-group" style="margin-bottom: 0;">
                                    <label class="sb-module-form-label">' . esc_html__('Apply to Headings', 'wpswitchboard') . '</label>
                                    <label class="sb-module-toggle' . (empty($heading_name) || (empty($heading_woff2) && empty($heading_woff) && empty($heading_ttf)) ? ' sb-toggle-disabled' : '') . '">
                                        <input type="checkbox" name="setting_heading_enabled" id="setting_heading_enabled" value="1" ' . checked($heading_enabled, 1, false) . (empty($heading_name) || (empty($heading_woff2) && empty($heading_woff) && empty($heading_ttf)) ? ' disabled' : '') . '>
                                        <span class="sb-module-toggle-slider"></span>
                                    </label>
                                    <p class="sb-module-form-help">' . esc_html__('Automatically apply this font to all headings (h1-h6) and titles', 'wpswitchboard') . '</p>
                                </div>
                            </div>
                        </div>

                        <div class="sb-module-card sb-module-form-section" style="margin-bottom: 24px;">
                            <div class="sb-module-card-header">
                                <div class="sb-module-card-header-left">
                                    <h2 class="sb-module-card-title">' . esc_html__('Generated CSS Preview', 'wpswitchboard') . '</h2>
                                    <p class="sb-module-card-desc">' . esc_html__('Preview the CSS that will be generated for your custom fonts', 'wpswitchboard') . '</p>
                                </div>
                            </div>
                            <div class="sb-module-card-body">
                                <pre id="font-css-preview" style="background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 6px; padding: 16px; margin: 0; font-family: \'Courier New\', monospace; font-size: 13px; color: #111827; white-space: pre-wrap; word-break: break-all; overflow-x: auto;">/* ' . esc_html__('CSS will appear here as you configure fonts', 'wpswitchboard') . ' */</pre>
                            </div>
                        </div>

                        <div class="sb-module-card sb-module-form-section">
                            <div class="sb-module-card-header">
                                <div class="sb-module-card-header-left">
                                    <h2 class="sb-module-card-title">' . esc_html__('How to Use Custom Fonts', 'wpswitchboard') . '</h2>
                                    <p class="sb-module-card-desc">' . esc_html__('Different ways to apply your custom fonts', 'wpswitchboard') . '</p>
                                </div>
                            </div>
                            <div class="sb-module-card-body">
                                <div style="margin-bottom: 16px;">
                                    <strong style="display: block; margin-bottom: 4px;">' . esc_html__('Option 1: Automatic Application', 'wpswitchboard') . '</strong>
                                    <p class="sb-module-form-help" style="margin: 0;">
                                        ' . esc_html__('Enable the toggle switches above to automatically apply fonts to body text or headings across your entire site.', 'wpswitchboard') . '
                                    </p>
                                </div>

                                <div style="margin-bottom: 16px;">
                                    <strong style="display: block; margin-bottom: 4px;">' . esc_html__('Option 2: Use in Custom CSS', 'wpswitchboard') . '</strong>
                                    <p class="sb-module-form-help" style="margin: 0 0 8px 0;">
                                        ' . esc_html__('Copy the CSS above and use the font names in your custom styles:', 'wpswitchboard') . '
                                    </p>
                                    <code style="display: block; background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 6px; padding: 12px; font-family: \'Courier New\', monospace; font-size: 13px; color: #111827;">
                                        .my-element { font-family: \'' . esc_attr($body_name ?: 'YourFontName') . '\', sans-serif; }
                                    </code>
                                </div>

                                <div style="margin-bottom: 16px;">
                                    <strong style="display: block; margin-bottom: 4px;">' . esc_html__('Option 3: Use in Page Builders', 'wpswitchboard') . '</strong>
                                    <p class="sb-module-form-help" style="margin: 0;">' .
                                    // translators: %s is the font name wrapped in a code tag
                                    sprintf(esc_html__('In Elementor, Divi, or other page builders, use the font name: %s', 'wpswitchboard'), '<code style="background: #f3f4f6; padding: 2px 6px; border-radius: 4px; font-size: 12px;">' . esc_html($body_name ?: 'YourFontName') . '</code>') . '
                                    </p>
                                </div>

                                <div>
                                    <strong style="display: block; margin-bottom: 8px;">' . esc_html__('Pro Tips', 'wpswitchboard') . '</strong>
                                    <ul style="margin: 0; padding-left: 20px; color: #64748b; font-size: 13px;">
                                        <li style="margin-bottom: 4px;">' . esc_html__('Upload WOFF2 format first for best performance (smaller file size, faster loading)', 'wpswitchboard') . '</li>
                                        <li style="margin-bottom: 4px;">' . esc_html__('Add WOFF and TTF as fallbacks for older browser support', 'wpswitchboard') . '</li>
                                        <li style="margin-bottom: 4px;">' . esc_html__('Font files are automatically added to your site\'s <head> section', 'wpswitchboard') . '</li>
                                        <li>' . esc_html__('The CSS preview updates in real-time as you add fonts', 'wpswitchboard') . '</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    ';
                echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML is built with escaped values
                    
                // ========================================
                // UTILITIES CATEGORY SETTINGS
                // ========================================
                
    }

    /**
     * Register data locations for cleanup system
     *
     * @return array Data storage locations
     */
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_custom-fonts-manager_settings',
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
        ];
    }
}

// Initialize and register with data system
$switchboard_instance = new SwitchboardCustomFontsManager();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
