<?php
/*
Plugin Name: Bangla Font CDN
Description: A powerful and easy-to-use plugin to use 10+ beautiful Bangla fonts on website with live preview, fallback font options, and advanced typography.
Version: 1.0
Author: Riduan Chowdhury
Author URI: https://www.bytesvibe.com/
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Text Domain: bangla-font-cdn
*/

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

/**
 * Initialize the Bangla Font CDN plugin
 */
class Bangla_Font_CDN {
    private $font_option_name = 'bangla_font_cdn_font';
    private $fallback_option_name = 'bangla_font_cdn_fallback';
    private $font_size_option_name = 'bangla_font_cdn_font_size';
    private $line_height_option_name = 'bangla_font_cdn_line_height';
    private $letter_spacing_option_name = 'bangla_font_cdn_letter_spacing';
    private $override_font_size_option_name = 'bangla_font_cdn_override_font_size';
    private $dismiss_notice_option_name = 'bangla_font_cdn_dismiss_notice';

    public function __construct() {
        // Register hooks
        add_action('wp_enqueue_scripts', [$this, 'enqueue_bangla_fonts']);
        add_action('admin_menu', [$this, 'add_admin_pages']);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_scripts']);
        add_action('admin_post_bangla_font_cdn_reset', [$this, 'handle_reset']);
    }

    /**
     * Enqueue the selected Bangla font and typography settings on the frontend
     */
    public function enqueue_bangla_fonts() {
        $selected_font = get_option($this->font_option_name, 'noto-serif-bengali');
        $fallback_fonts = get_option($this->fallback_option_name, 'sans-serif');
        $font_size = get_option($this->font_size_option_name, '16');
        $line_height = get_option($this->line_height_option_name, '1.5');
        $letter_spacing = get_option($this->letter_spacing_option_name, '0');
        $override_font_size = get_option($this->override_font_size_option_name, '0');

        // Define available fonts from local sources
        $fonts = [
            'adorsho-lipi' => [
                'name' => 'Adorsho Lipi',
                'url'  => plugins_url('fonts/adorsho-lipi/font.css', __FILE__),
            ],
            'apona-lohit' => [
                'name' => 'Apona Lohit',
                'url'  => plugins_url('fonts/apona-lohit/font.css', __FILE__),
            ],
            'baloo-da-2' => [
                'name' => 'Baloo Da 2',
                'url'  => plugins_url('fonts/baloo-da-2/font.css', __FILE__),
            ],
            'bangla' => [
                'name' => 'Bangla',
                'url'  => plugins_url('fonts/bangla/font.css', __FILE__),
            ],
            'ekushey-lohit' => [
                'name' => 'Ekushey Lohit',
                'url'  => plugins_url('fonts/ekushey-lohit/font.css', __FILE__),
            ],
            'kalpurush' => [
                'name' => 'Kalpurush',
                'url'  => plugins_url('fonts/kalpurush/font.css', __FILE__),
            ],
            'mukti' => [
                'name' => 'Mukti',
                'url'  => plugins_url('fonts/mukti/font.css', __FILE__),
            ],
            'noto-serif-bengali' => [
                'name' => 'Noto Serif Bengali',
                'url'  => plugins_url('fonts/noto-serif-bengali/font.css', __FILE__),
            ],
            'siyam-rupali' => [
                'name' => 'Siyam Rupali',
                'url'  => plugins_url('fonts/siyam-rupali/font.css', __FILE__),
            ],
            'solaiman-lipi' => [
                'name' => 'SolaimanLipi',
                'url'  => plugins_url('fonts/solaiman-lipi/font.css', __FILE__),
            ],
            'tiro-bangla' => [
                'name' => 'Tiro Bangla',
                'url'  => plugins_url('fonts/tiro-bangla/font.css', __FILE__),
            ],
        ];

        // Enqueue the selected font
        if (isset($fonts[$selected_font])) {
            $font = $fonts[$selected_font];
            wp_enqueue_style('bangla-font-cdn-' . $selected_font, $font['url'], [], '1.0');

            // Apply font and typography settings
            $custom_css = sprintf(
                "body, p, h1, h2, h3, h4, h5, h6, .entry-content { 
                    font-family: '%s', %s !important; 
                    line-height: %s; 
                    letter-spacing: %spx; 
                }",
                esc_html($font['name']),
                esc_html($fallback_fonts),
                floatval($line_height),
                floatval($letter_spacing)
            );
            if ($override_font_size) {
                $custom_css .= sprintf(
                    "body, p, h1, h2, h3, h4, h5, h6, .entry-content { 
                        font-size: %spx !important; 
                    }",
                    floatval($font_size)
                );
            }
            wp_add_inline_style('bangla-font-cdn-' . $selected_font, $custom_css);
        }
    }

    /**
     * Add settings and disclaimer pages to the admin menu
     */
    public function add_admin_pages() {
        add_menu_page(
            esc_html__('Bangla Font CDN', 'bangla-font-cdn'),
            esc_html__('Bangla Font CDN', 'bangla-font-cdn'),
            'manage_options',
            'bangla-font-cdn',
            [$this, 'render_settings_page'],
            'dashicons-editor-textcolor'
        );
        add_submenu_page(
            'bangla-font-cdn',
            esc_html__('Settings', 'bangla-font-cdn'),
            esc_html__('Settings', 'bangla-font-cdn'),
            'manage_options',
            'bangla-font-cdn',
            [$this, 'render_settings_page']
        );
        add_submenu_page(
            'bangla-font-cdn',
            esc_html__('Disclaimer', 'bangla-font-cdn'),
            esc_html__('Disclaimer', 'bangla-font-cdn'),
            'manage_options',
            'bangla-font-cdn-disclaimer',
            [$this, 'render_disclaimer_page']
        );
    }

    /**
     * Register settings
     */
    public function register_settings() {
        // Font selection
        register_setting('bangla_font_cdn_options', $this->font_option_name, [
            'sanitize_callback' => [$this, 'sanitize_font_selection'],
            'default'           => 'noto-serif-bengali',
        ]);

        // Fallback fonts
        register_setting('bangla_font_cdn_options', $this->fallback_option_name, [
            'sanitize_callback' => 'sanitize_text_field',
            'default'           => 'sans-serif',
        ]);

        // Typography settings
        register_setting('bangla_font_cdn_options', $this->font_size_option_name, [
            'sanitize_callback' => [$this, 'sanitize_positive_float'],
            'default'           => '16',
        ]);
        register_setting('bangla_font_cdn_options', $this->line_height_option_name, [
            'sanitize_callback' => [$this, 'sanitize_positive_float'],
            'default'           => '1.5',
        ]);
        register_setting('bangla_font_cdn_options', $this->letter_spacing_option_name, [
            'sanitize_callback' => [$this, 'sanitize_float'],
            'default'           => '0',
        ]);
        register_setting('bangla_font_cdn_options', $this->override_font_size_option_name, [
            'sanitize_callback' => [$this, 'sanitize_checkbox'],
            'default'           => '0',
        ]);

        // Dismiss notice
        register_setting('bangla_font_cdn_options', $this->dismiss_notice_option_name, [
            'sanitize_callback' => [$this, 'sanitize_checkbox'],
            'default'           => '0',
        ]);

        // Settings section
        add_settings_section(
            'bangla_font_cdn_general',
            esc_html__('Bangla Font Settings', 'bangla-font-cdn'),
            null,
            'bangla-font-cdn'
        );

        // Fields
        add_settings_field(
            'bangla_font_cdn_select',
            esc_html__('Select Bangla Font', 'bangla-font-cdn'),
            [$this, 'font_select_field'],
            'bangla-font-cdn',
            'bangla_font_cdn_general'
        );
        add_settings_field(
            'bangla_font_cdn_fallback',
            esc_html__('Fallback Fonts', 'bangla-font-cdn'),
            [$this, 'fallback_fonts_field'],
            'bangla-font-cdn',
            'bangla_font_cdn_general'
        );
        add_settings_field(
            'bangla_font_cdn_typography',
            esc_html__('Typography Settings', 'bangla-font-cdn'),
            [$this, 'typography_settings_field'],
            'bangla-font-cdn',
            'bangla_font_cdn_general'
        );
    }

    /**
     * Sanitize font selection
     */
    public function sanitize_font_selection($input) {
        $valid_fonts = [
            'adorsho-lipi', 'apona-lohit', 'baloo-da-2', 'bangla', 'ekushey-lohit',
            'kalpurush', 'mukti', 'noto-serif-bengali', 'siyam-rupali', 'solaiman-lipi',
            'tiro-bangla'
        ];
        return in_array($input, $valid_fonts) ? $input : 'noto-serif-bengali';
    }

    /**
     * Sanitize positive float
     */
    public function sanitize_positive_float($input) {
        $value = floatval($input);
        return $value > 0 ? $value : 1;
    }

    /**
     * Sanitize float (can be negative)
     */
    public function sanitize_float($input) {
        return floatval($input);
    }

    /**
     * Sanitize checkbox
     */
    public function sanitize_checkbox($input) {
        return $input === '1' ? '1' : '0';
    }

    /**
     * Render the font selection field
     */
    public function font_select_field() {
        $selected_font = get_option($this->font_option_name, 'noto-serif-bengali');
        $fonts = [
            'adorsho-lipi' => 'Adorsho Lipi',
            'apona-lohit' => 'Apona Lohit',
            'baloo-da-2' => 'Baloo Da 2',
            'bangla' => 'Bangla',
            'ekushey-lohit' => 'Ekushey Lohit',
            'kalpurush' => 'Kalpurush',
            'mukti' => 'Mukti',
            'noto-serif-bengali' => 'Noto Serif Bengali',
            'siyam-rupali' => 'Siyam Rupali',
            'solaiman-lipi' => 'SolaimanLipi',
            'tiro-bangla' => 'Tiro Bangla',
        ];
        ?>
        <div class="bangla-font-cdn-card">
            <select name="<?php echo esc_attr($this->font_option_name); ?>" id="bangla-font-select" aria-label="<?php esc_html_e('Select Bangla Font', 'bangla-font-cdn'); ?>">
                <?php foreach ($fonts as $value => $label) : ?>
                    <option value="<?php echo esc_attr($value); ?>" <?php selected($selected_font, $value); ?>>
                        <?php echo esc_html($label); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <p class="description"><?php esc_html_e('Choose a Bangla font from various sources to apply to your website.', 'bangla-font-cdn'); ?></p>
            <div id="font-preview">
                <h3><?php esc_html_e('Font Preview', 'bangla-font-cdn'); ?></h3>
                <p>আমি বাংলায় মাতি উল্লাসে, করি বাংলায় হাহাকার। আমি সব দেখে শুনে ক্ষেপে গিয়ে- করি বাংলায় চিৎকার।</p>
            </div>
        </div>
        <?php
    }

    /**
     * Render the fallback fonts field
     */
    public function fallback_fonts_field() {
        $fallback_fonts = get_option($this->fallback_option_name, 'sans-serif');
        ?>
        <div class="bangla-font-cdn-card">
            <input type="text" name="<?php echo esc_attr($this->fallback_option_name); ?>" value="<?php echo esc_attr($fallback_fonts); ?>" class="regular-text" aria-label="<?php esc_html_e('Fallback Fonts', 'bangla-font-cdn'); ?>" />
            <p class="description"><?php esc_html_e('Enter fallback fonts (e.g., Arial, sans-serif) in case the selected font fails to load.', 'bangla-font-cdn'); ?></p>
        </div>
        <?php
    }

    /**
     * Render the typography settings field
     */
    public function typography_settings_field() {
        $font_size = get_option($this->font_size_option_name, '16');
        $line_height = get_option($this->line_height_option_name, '1.5');
        $letter_spacing = get_option($this->letter_spacing_option_name, '0');
        $override_font_size = get_option($this->override_font_size_option_name, '0');
        ?>
        <div class="bangla-font-cdn-card">
            <h3><?php esc_html_e('Typography Settings', 'bangla-font-cdn'); ?></h3>
            <p>
                <label for="bangla-override-font-size">
                    <input type="checkbox" name="<?php echo esc_attr($this->override_font_size_option_name); ?>" id="bangla-override-font-size" value="1" <?php checked($override_font_size, '1'); ?> />
                    <?php esc_html_e('Override Theme Font Size', 'bangla-font-cdn'); ?>
                </label>
                <span class="description"><?php esc_html_e('Check to use the plugin’s font size instead of the theme’s.', 'bangla-font-cdn'); ?></span>
            </p>
            <p>
                <label for="bangla-font-size"><?php esc_html_e('Font Size (px)', 'bangla-font-cdn'); ?></label><br>
                <input type="number" name="<?php echo esc_attr($this->font_size_option_name); ?>" id="bangla-font-size" value="<?php echo esc_attr($font_size); ?>" min="1" step="0.1" class="small-text" aria-label="<?php esc_html_e('Font Size', 'bangla-font-cdn'); ?>" />
            </p>
            <p>
                <label for="bangla-line-height"><?php esc_html_e('Line Height', 'bangla-font-cdn'); ?></label><br>
                <input type="number" name="<?php echo esc_attr($this->line_height_option_name); ?>" id="bangla-line-height" value="<?php echo esc_attr($line_height); ?>" min="0.1" step="0.1" class="small-text" aria-label="<?php esc_html_e('Line Height', 'bangla-font-cdn'); ?>" />
            </p>
            <p>
                <label for="bangla-letter-spacing"><?php esc_html_e('Letter Spacing (px)', 'bangla-font-cdn'); ?></label><br>
                <input type="number" name="<?php echo esc_attr($this->letter_spacing_option_name); ?>" id="bangla-letter-spacing" value="<?php echo esc_attr($letter_spacing); ?>" step="0.1" class="small-text" aria-label="<?php esc_html_e('Letter Spacing', 'bangla-font-cdn'); ?>" />
            </p>
            <p class="description"><?php esc_html_e('Adjust typography settings for better readability.', 'bangla-font-cdn'); ?></p>
        </div>
        <?php
    }

    /**
     * Render the settings page
     */
    public function render_settings_page() {
        if (!current_user_can('manage_options')) {
            return;
        }
        $dismissed = get_option($this->dismiss_notice_option_name, '0');
        ?>
        <div class="wrap bangla-font-cdn-wrap">
            <h1><?php esc_html_e('Bangla Font CDN Settings', 'bangla-font-cdn'); ?></h1>
            <?php if ($dismissed !== '1') : ?>
                <div class="notice notice-warning is-dismissible" id="bangla-font-cdn-notice">
                    <p><strong><?php esc_html_e('Important Licensing Information', 'bangla-font-cdn'); ?>:</strong> <?php esc_html_e('The Bangla fonts provided by this plugin are sourced from various providers and included locally. Each font has its own license (e.g., SIL Open Font License, GNU GPL, or others). While many fonts are free for personal and commercial use, some may have restrictions for commercial projects. Before using any font in a commercial website, app, or product, please verify its license with the font provider or author. Failure to comply with licensing terms may result in legal issues. For commercial use, consider consulting a legal expert.', 'bangla-font-cdn'); ?></p>
                </div>
            <?php endif; ?>
            <form method="post" action="options.php">
                <?php
                settings_fields('bangla_font_cdn_options');
                do_settings_sections('bangla-font-cdn');
                submit_button();
                ?>
            </form>
            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" onsubmit="return confirm('<?php echo esc_js(esc_html__('Are you sure you want to reset all settings to their defaults?', 'bangla-font-cdn')); ?>');">
                <input type="hidden" name="action" value="bangla_font_cdn_reset" />
                <?php wp_nonce_field('bangla_font_cdn_reset_nonce'); ?>
                <button type="submit" class="button button-secondary"><?php esc_html_e('Reset to Defaults', 'bangla-font-cdn'); ?></button>
            </form>
        </div>
        <?php
    }

    /**
     * Render the disclaimer page
     */
    public function render_disclaimer_page() {
        if (!current_user_can('manage_options')) {
            return;
        }
        ?>
        <div class="wrap bangla-font-cdn-wrap">
            <h1><?php esc_html_e('Bangla Font CDN Disclaimer', 'bangla-font-cdn'); ?></h1>
            <div class="bangla-font-cdn-card">
                <h2><?php esc_html_e('Disclaimer for Font Usage', 'bangla-font-cdn'); ?></h2>
                <p><?php esc_html_e('The Bangla Font CDN plugin provides access to a variety of Bangla fonts sourced from various providers, included locally within the plugin.', 'bangla-font-cdn'); ?></p>
                <p><?php esc_html_e('Each font included in this plugin is subject to its own licensing terms, which may include the SIL Open Font License (OFL), GNU General Public License (GPL), or other licenses. While many of these fonts are free for both personal and commercial use, some may have specific restrictions, particularly for commercial applications such as websites, applications, or printed materials.', 'bangla-font-cdn'); ?></p>
                <p><?php esc_html_e('As the user of this plugin, you are solely responsible for ensuring that your use of these fonts complies with their respective licenses. This includes verifying whether a font is suitable for commercial use and obtaining any necessary permissions from the font author or provider. The plugin author, Riduan Chowdhury, and BytesVibe are not responsible for any legal or financial consequences arising from the misuse of these fonts.', 'bangla-font-cdn'); ?></p>
                <p><?php esc_html_e('We strongly recommend that you review the license for each font before using it in a commercial project. If you are unsure about a font’s licensing terms, contact the font provider or consult a legal expert to ensure compliance.', 'bangla-font-cdn'); ?></p>
                <p><?php esc_html_e('By using this plugin, you acknowledge and agree to these terms and assume full responsibility for complying with the font licenses.', 'bangla-font-cdn'); ?></p>
            </div>
        </div>
        <?php
    }

    /**
     * Handle reset action
     */
    public function handle_reset() {
        if (!current_user_can('manage_options') || !check_admin_referer('bangla_font_cdn_reset_nonce')) {
            wp_die(esc_html__('You do not have permission to perform this action.', 'bangla-font-cdn'));
        }

        // Reset all options to defaults
        update_option($this->font_option_name, 'noto-serif-bengali');
        update_option($this->fallback_option_name, 'sans-serif');
        update_option($this->font_size_option_name, '16');
        update_option($this->line_height_option_name, '1.5');
        update_option($this->letter_spacing_option_name, '0');
        update_option($this->override_font_size_option_name, '0');
        update_option($this->dismiss_notice_option_name, '0');

        // Generate nonce for success redirect
        $success_nonce = wp_create_nonce('bangla_font_cdn_reset_success');

        // Redirect back to settings page with a success message and nonce
        wp_redirect(add_query_arg([
            'page' => 'bangla-font-cdn',
            'reset' => 'success',
            '_wpnonce' => $success_nonce
        ], admin_url('admin.php')));
        exit;
    }

    /**
     * Enqueue admin scripts and styles for the settings and disclaimer pages
     */
    public function enqueue_admin_scripts($hook) {
        if ($hook !== 'toplevel_page_bangla-font-cdn' && $hook !== 'bangla-font-cdn_page_bangla-font-cdn-disclaimer') {
            return;
        }
        wp_enqueue_style('bangla-font-cdn-admin', plugins_url('css/admin-style.css', __FILE__), [], '1.0');
        wp_enqueue_script('bangla-font-cdn-admin', plugins_url('js/admin-script.js', __FILE__), ['jquery'], '1.0', true);

        // Pass font data to JavaScript
        $fonts = [
            'adorsho-lipi' => ['url' => plugins_url('fonts/adorsho-lipi/font.css', __FILE__)],
            'apona-lohit' => ['url' => plugins_url('fonts/apona-lohit/font.css', __FILE__)],
            'baloo-da-2' => ['url' => plugins_url('fonts/baloo-da-2/font.css', __FILE__)],
            'bangla' => ['url' => plugins_url('fonts/bangla/font.css', __FILE__)],
            'ekushey-lohit' => ['url' => plugins_url('fonts/ekushey-lohit/font.css', __FILE__)],
            'kalpurush' => ['url' => plugins_url('fonts/kalpurush/font.css', __FILE__)],
            'mukti' => ['url' => plugins_url('fonts/mukti/font.css', __FILE__)],
            'noto-serif-bengali' => ['url' => plugins_url('fonts/noto-serif-bengali/font.css', __FILE__)],
            'siyam-rupali' => ['url' => plugins_url('fonts/siyam-rupali/font.css', __FILE__)],
            'solaiman-lipi' => ['url' => plugins_url('fonts/solaiman-lipi/font.css', __FILE__)],
            'tiro-bangla' => ['url' => plugins_url('fonts/tiro-bangla/font.css', __FILE__)],
        ];
        wp_localize_script('bangla-font-cdn-admin', 'bangfocdData', [
            'fonts' => $fonts,
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('bangla_font_cdn_dismiss_nonce')
        ]);

        // Add inline script to show reset success message with nonce verification
    if (
    $hook === 'toplevel_page_bangla-font-cdn' &&
    isset($_GET['reset']) && $_GET['reset'] === 'success' &&
    isset($_GET['_wpnonce']) &&
    wp_verify_nonce(
        sanitize_text_field(wp_unslash($_GET['_wpnonce'])),
        'bangla_font_cdn_reset_success'
    )
) {
            wp_add_inline_script('bangla-font-cdn-admin', 'jQuery(document).ready(function($) { $("<div class=\"notice notice-success is-dismissible\"><p>' . esc_js(esc_html__('Settings have been reset to defaults.', 'bangla-font-cdn')) . '</p></div>").insertAfter(".bangla-font-cdn-wrap h1"); });');
        }
    }
}

// Handle AJAX request for dismissing notice
add_action('wp_ajax_bangla_font_cdn_dismiss_notice', function () {
    check_ajax_referer('bangla_font_cdn_dismiss_nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error('Unauthorized');
    }
    update_option('bangla_font_cdn_dismiss_notice', '1');
    wp_send_json_success();
});

// Instantiate the plugin
new Bangla_Font_CDN();
?>