<?php
/**
 * @link              https://ttswp.com/
 * @since             1.0.0
 * @package           TTSWP
 *
 * @wordpress-plugin
 * Plugin Name:       Text to Speech - TTSWP
 * Plugin URI:        https://ttswp.com/
 * Description:       The easiest Text-to-Speech plugin for WordPress. Add natural voices, boost accessibility, and engage visitors with an instant audio player.
 * Version:           3.2.20
 * Author:            Norse Digital Group LLC
 * Author URI:        https://ttswp.com/
 * License:           GPL-3.0+
 * License URI:       https://www.gnu.org/licenses/gpl-3.0.txt
 * Text Domain:       text-to-speech-tts
 * Domain Path:       /languages
 * Requires PHP:      7.2
 * Requires at least: 6.0
 */

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

// Define plugin constants
define('MEMENTOR_TTS_VERSION', '3.2.20');
define('MEMENTOR_TTS_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('MEMENTOR_TTS_PLUGIN_URL', plugin_dir_url(__FILE__));
define('MEMENTOR_TTS_PLUGIN_BASENAME', plugin_basename(__FILE__));
define('MEMENTOR_TTS_PLUGIN_FILE', __FILE__);

// Legacy PRO constants removed — plan gates now use ttswp_has_paid_plan() from SaaS connection

/**
 * Check if debug mode is enabled
 * Checks both the MEMENTOR_TTS_DEBUG constant (for developers) and the WordPress option (for users)
 *
 * @return bool True if debug mode is enabled, false otherwise
 */
function mementor_tts_is_debug_enabled() {
    return (defined('MEMENTOR_TTS_DEBUG') && MEMENTOR_TTS_DEBUG) || (get_option('mementor_tts_debug_mode', '0') === '1');
}

/**
 * Fire-and-forget wrapper that sends a remote debug event via the API client.
 * Safe to call from any request context — silently skips if the plugin is
 * disconnected, the toggle is off, or the API client is unavailable.
 *
 * @param string $event_type One of: generate_start, generate_success, generate_error,
 *                           regenerate_start, regenerate_success, regenerate_error,
 *                           content_extracted, content_truncated, selector_applied, other.
 * @param string $message    Short human-readable message (<=500 chars, auto-truncated).
 * @param array  $context    Arbitrary key/value context.
 * @param string $severity   debug|info|warning|error. Defaults to 'debug'.
 * @param int    $post_id    Optional post id.
 * @return void
 */
function ttswp_send_remote_debug_event( $event_type, $message, $context = array(), $severity = 'debug', $post_id = 0 ) {
    if ( get_option( 'mementor_tts_remote_debug_enabled', '0' ) !== '1' ) {
        return;
    }
    if ( ! class_exists( 'Mementor_TTS_Api_Client' ) ) {
        return;
    }

    try {
        $client = Mementor_TTS_Api_Client::get_instance();
        $client->send_remote_debug_event( array(
            'event_type' => $event_type,
            'severity'   => $severity,
            'message'    => $message,
            'context'    => $context,
            'post_id'    => $post_id,
        ) );
    } catch ( \Throwable $e ) {
        // Never let debug instrumentation break the request.
    }
}

/**
 * Ensure database tables exist on plugin load
 * This runs early to catch missing tables before any database queries
 *
 * @since 1.9.31
 */
function mementor_tts_check_tables_on_load() {
    // Only run in admin context
    if (!is_admin()) {
        return;
    }

    $required_db_version = '1.1.1';
    $current_db_version = get_option('mementor_tts_db_version', '0');
    $version_outdated = version_compare($current_db_version, $required_db_version, '<');

    $tables_verified = get_option('mementor_tts_tables_verified', '');
    $plugin_updated = ($tables_verified !== MEMENTOR_TTS_VERSION);

    // Skip if: plugin version hasn't changed AND db version is current AND daily check hasn't expired
    if (!$plugin_updated && !$version_outdated) {
        $last_check = get_option('mementor_tts_tables_check', 0);
        if ($last_check && (time() - $last_check) < DAY_IN_SECONDS) {
            return;
        }
    }

    global $wpdb;
    $table_name = $wpdb->prefix . 'mementor_tts_elements';
    $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)) === $table_name;

    if (!$table_exists || $version_outdated) {
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

        if (!class_exists('Mementor_TTS_Speech_Builder')) {
            require_once MEMENTOR_TTS_PLUGIN_DIR . 'includes/class-mementor-tts-speech-builder.php';
        }

        $speech_builder = Mementor_TTS_Speech_Builder::get_instance();
        $speech_builder->create_tables();

        error_log('[TTS] Created/updated database tables (version: ' . $required_db_version . ')');
    }

    update_option('mementor_tts_tables_verified', MEMENTOR_TTS_VERSION, false);
    update_option('mementor_tts_tables_check', time(), false);
}
add_action('plugins_loaded', 'mementor_tts_check_tables_on_load', 1);

/**
 * The core plugin class that is used to define internationalization,
 * admin-specific hooks, and public-facing site hooks.
 */
require_once MEMENTOR_TTS_PLUGIN_DIR . 'includes/class-mementor-tts.php';
require_once MEMENTOR_TTS_PLUGIN_DIR . 'includes/class-mementor-tts-connect.php';
Mementor_TTS_Connect::init();

/**
 * Activation Hook
 */
function mementor_tts_activate() {
	// Include WordPress upgrade functionality for dbDelta
	// This is one of the exceptions where it's appropriate to include a WordPress core file
	// because we're in the plugin activation hook and need dbDelta specifically
	require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
	
	// Now include and use our speech builder
	require_once MEMENTOR_TTS_PLUGIN_DIR . 'includes/class-mementor-tts-speech-builder.php';
	$speech_builder = Mementor_TTS_Speech_Builder::get_instance();
	$speech_builder->create_tables();
	
	// Create user credits table
	require_once MEMENTOR_TTS_PLUGIN_DIR . 'includes/class-mementor-tts-user-credits.php';
	$user_credits = Mementor_TTS_User_Credits::get_instance();
	$user_credits->create_table();
	
	// Migrate existing records to include integrity hashes
	$user_credits->migrate_integrity_hashes();
	
	// Create player statistics tables
	// Note: For existing users who update the plugin, tables are created via
	// maybe_create_statistics_tables() method called on admin_init hook
	require_once MEMENTOR_TTS_PLUGIN_DIR . 'includes/class-mementor-tts-player-statistics.php';
	$player_stats = Mementor_TTS_Player_Statistics::get_instance();
	$player_stats->create_tables();

	// Create transcriptions table
	require_once MEMENTOR_TTS_PLUGIN_DIR . 'includes/class-mementor-tts-transcriptions.php';
	$transcriptions = Mementor_TTS_Transcriptions::get_instance();
	$transcriptions->create_table();

	// Set default options
	if (!get_option('mementor_tts_settings')) {
		update_option('mementor_tts_settings', array(
			'post_types' => array('post'),
			'output_format' => 'mp3',
			'privacy_mode' => false,
			'model_id' => 'eleven_flash_v2_5'
		));
	}

	// Track install date (only on first activation)
	if ( ! get_option( 'mementor_tts_installed_at' ) ) {
		update_option( 'mementor_tts_installed_at', time(), false );
	}

	// Clean up removed telemetry system (added in 3.1.3)
	wp_clear_scheduled_hook('mementor_tts_send_remote_telemetry');
	delete_transient('mementor_tts_daily_usage');
	delete_option('mementor_tts_telemetry_consent');
	delete_option('mementor_tts_telemetry_consent_time');

	// Flush rewrite rules
	flush_rewrite_rules();
}

/**
 * Deactivation Hook
 */
function mementor_tts_deactivate() {
	// Clear all scheduled cron events
	wp_clear_scheduled_hook('mementor_tts_daily_cleanup');
	wp_clear_scheduled_hook('mementor_tts_cleanup_audio');
	wp_clear_scheduled_hook('mementor_tts_aggregate_player_stats');
	wp_clear_scheduled_hook('mementor_tts_aggregate_analytics');
	wp_clear_scheduled_hook('mementor_tts_send_remote_telemetry');

	// Clean up telemetry data
	delete_transient('mementor_tts_daily_usage');
	delete_option('mementor_tts_telemetry_consent');
	delete_option('mementor_tts_telemetry_consent_time');

	// Flush rewrite rules
	flush_rewrite_rules();
}

register_activation_hook(__FILE__, 'mementor_tts_activate');
register_deactivation_hook(__FILE__, 'mementor_tts_deactivate');

/**
 * Auto-deactivate the legacy PRO addon plugin if it's active.
 * Called on activation, upgrade, and once via admin_init (gated by the safety-net flag).
 */
function mementor_tts_deactivate_pro_plugin() {
    if ( ! function_exists( 'is_plugin_active' ) ) {
        include_once ABSPATH . 'wp-admin/includes/plugin.php';
    }

    $pro_plugin = 'text-to-speech-tts-pro/mementor-text-to-speech-pro.php';

    if ( is_plugin_active( $pro_plugin ) ) {
        deactivate_plugins( $pro_plugin );
        // Drives the one-time "PRO has been deactivated" admin notice.
        update_option( 'tts_legacy_pro_deactivated', true );
    }

    // Marks that the safety-net check has run at least once, so admin_init can stop firing it.
    update_option( 'mementor_tts_legacy_pro_safety_net_done', true );
}

// On plugin activation
register_activation_hook( __FILE__, 'mementor_tts_deactivate_pro_plugin' );

// On plugin upgrade
add_action( 'upgrader_process_complete', function ( $upgrader, $options ) {
    if ( 'update' === $options['action'] && 'plugin' === $options['type'] ) {
        mementor_tts_deactivate_pro_plugin();
    }
}, 10, 2 );

// Safety net for installs that skip activation/upgrade hooks (e.g. file-copy installs). Runs once, then stops.
add_action( 'admin_init', function () {
    if ( get_option( 'mementor_tts_legacy_pro_safety_net_done' ) ) {
        return;
    }
    mementor_tts_deactivate_pro_plugin();
} );

/**
 * Begins execution of the plugin.
 *
 * Since everything within the plugin is registered via hooks,
 * then kicking off the plugin from this point in the file does
 * not affect the page life cycle.
 *
 * @since    1.0.0
 */
function mementor_tts_plugin_init() {
    // Don't run the plugin on login, register, or password reset pages
    if (mementor_tts_is_login_page()) {
        return;
    }
    
    $plugin = new Mementor_Text_To_Speech();
    $plugin->run();
}

// Start the plugin after WordPress is fully loaded
add_action('plugins_loaded', 'mementor_tts_plugin_init');


/**
 * Check if current page is a login-related page
 *
 * @since    1.5.6
 * @return   bool    True if on login/register/password reset page
 */
function mementor_tts_is_login_page() {
    // Get the current page
    $current_page = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : '';
    
    // Check if we're on any login-related pages
    $login_pages = array(
        'wp-login.php',
        'wp-register.php',
        'wp-activate.php',
        'wp-signup.php'
    );
    
    foreach ($login_pages as $page) {
        if (strpos($current_page, $page) !== false) {
            return true;
        }
    }
    
    // Also check if this is an AJAX request from login page
    if (defined('DOING_AJAX') && DOING_AJAX) {
        $referer = wp_get_referer();
        if ($referer) {
            foreach ($login_pages as $page) {
                if (strpos($referer, $page) !== false) {
                    return true;
                }
            }
        }
    }
    
    return false;
}

/**
 * Register public-facing assets.
 * 
 * Register all the scripts, styles, and dependencies used on the frontend.
 * These will be enqueued conditionally based on where they are needed.
 *
 * @since    1.0.0
 */
function mementor_tts_register_assets() {
    // Don't register assets on login pages
    if (mementor_tts_is_login_page()) {
        return;
    }
    
    // Get the plugin version
    $plugin_version = defined('MEMENTOR_TTS_VERSION') ? MEMENTOR_TTS_VERSION : '1.0.0';
    
    // Define whether debug mode is enabled
    $debug_mode = get_option('mementor_tts_debug_mode', '0') === '1';
    
    // Register shared styles between admin and frontend
    wp_register_style(
        'mementor-tts-shared',
        plugin_dir_url(__FILE__) . 'public/css/mementor-tts-shared.css',
        array(),
        $plugin_version
    );

    // Register the frontend styles
    wp_register_style(
        'mementor-tts-public',
        plugin_dir_url(__FILE__) . 'public/css/mementor-tts-public.css',
        array('mementor-tts-shared', 'dashicons'),
        $plugin_version
    );

    // Register the player script
    wp_register_script(
        'mementor-tts-player',
        plugin_dir_url(__FILE__) . 'public/js/mementor-tts-public.js',
        array('jquery'),
        $plugin_version,
        true
    );
    
    // Register the statistics tracking script (loaded conditionally)
    wp_register_script(
        'mementor-tts-statistics',
        plugin_dir_url(__FILE__) . 'public/js/mementor-tts-statistics.js',
        array('jquery', 'mementor-tts-player'),
        $plugin_version,
        true
    );
    
    // Register the shortcode script
    wp_register_script(
        'mementor-tts-shortcode',
        plugin_dir_url(__FILE__) . 'public/js/mementor-tts-shortcode.js',
        array('jquery', 'mementor-tts-player'),
        $plugin_version,
        true
    );
    
    // Only register debug settings script if debug mode is enabled
    if ($debug_mode) {
        wp_register_script(
            'mementor-tts-debug-settings',
            plugin_dir_url(__FILE__) . 'public/js/mementor-tts-debug-settings.js',
            array(),
            $plugin_version,
            true
        );
        
        // Pass debug mode setting to JS immediately during registration
        wp_localize_script(
            'mementor-tts-debug-settings',
            'mementorTTSDebugSettings',
            array(
                'isDebug' => $debug_mode
            )
        );
    }
    
    
    // Register the player position script
    wp_register_script(
        'mementor-tts-player-position',
        plugin_dir_url(__FILE__) . 'public/js/mementor-tts-player-position.js',
        array('mementor-tts-player'),
        $plugin_version,
        true
    );
    
    // Register the player insertion script - responsible for injecting the player HTML into the content
    wp_register_script(
        'mementor-tts-player-insert',
        plugin_dir_url(__FILE__) . 'public/js/mementor-tts-player-insert.js',
        array('mementor-tts-player', 'mementor-tts-player-position'),
        $plugin_version,
        true
    );
    
    // Register the error recovery script - handles JS errors and ensures player initialization
    wp_register_script(
        'mementor-tts-error-recovery',
        plugin_dir_url(__FILE__) . 'public/js/mementor-tts-error-recovery.js',
        array('jquery'),
        $plugin_version,
        true
    );
    
    // Register jQuery wait script - ensures jQuery is loaded before initializing
    wp_register_script(
        'mementor-tts-jquery-wait',
        plugin_dir_url(__FILE__) . 'public/js/mementor-tts-jquery-wait.js',
        array(),
        $plugin_version,
        true
    );
    
    // Register simple info handler script
    wp_register_script(
        'mementor-tts-info-handler',
        plugin_dir_url(__FILE__) . 'public/js/mementor-tts-info-handler.js',
        array(),
        $plugin_version,
        true
    );
    
    // Register the shortcode management script for admin
    wp_register_script(
        'mementor-tts-shortcodes',
        plugin_dir_url(__FILE__) . 'admin/js/mementor-tts-shortcodes.js',
        array('jquery'),
        $plugin_version,
        true
    );
}
add_action('wp_enqueue_scripts', 'mementor_tts_register_assets', 5);
add_action('admin_enqueue_scripts', 'mementor_tts_register_assets', 5);

/**
 * Add data attributes to prevent script optimization/caching
 *
 * @since    1.0.0
 */
function mementor_tts_add_script_attributes($tag, $handle, $src) {
    // Only modify our scripts
    if (strpos($handle, 'mementor-tts') === false) {
        return $tag;
    }
    
    // Add data attributes to prevent optimization
    $tag = str_replace(' src=', ' data-no-optimize="1" data-no-defer="1" data-no-lazy="1" data-cfasync="false" data-no-minify="1" src=', $tag);
    
    return $tag;
}
add_filter('script_loader_tag', 'mementor_tts_add_script_attributes', 10, 3);

/**
 * Conditionally enqueue frontend assets when needed.
 * 
 * This function only loads the necessary CSS and JS for text-to-speech
 * functionality when needed, based on plugin settings and current content.
 *
 * @since    1.0.0
 */
function mementor_tts_maybe_enqueue_assets() {
    // Don't enqueue assets on login pages
    if (mementor_tts_is_login_page()) {
        return;
    }
    
    // Only enqueue debug settings script if debug mode is enabled
    $debug_mode = get_option('mementor_tts_debug_mode', '0') === '1';
    if ($debug_mode) {
        wp_enqueue_script('mementor-tts-debug-settings');
    }

    // Check if we should load assets
    $should_load = apply_filters('mementor_tts_should_load_assets', false);

    // If we should load assets, enqueue the main player script and styles
    if ($should_load) {
        wp_enqueue_script('mementor-tts-player');
        wp_enqueue_style('mementor-tts-shared');
        wp_enqueue_style('mementor-tts-public');
        
        // Localize the player script
        wp_localize_script(
            'mementor-tts-player',
            'mementorTTSPlayer',
            array(
                'nonce' => wp_create_nonce('mementor_tts_nonce'),
                'ajaxurl' => admin_url('admin-ajax.php'),
                'showTime' => (bool) get_option('mementor_tts_show_time', 1),
                'showVolume' => (bool) get_option('mementor_tts_show_volume', 1),
                'speedControl' => (bool) get_option('mementor_tts_speed_control', 0),
                'lazyLoad' => get_option('mementor_tts_lazy_load_player', '0') === '1',
                'isDebug' => (get_option('mementor_tts_debug_mode', '0') === '1')
            )
        );
        
        // Enqueue additional scripts
        wp_enqueue_script('mementor-tts-error-recovery');
        wp_enqueue_script('mementor-tts-player-position');
        wp_enqueue_script('mementor-tts-player-insert');
        // Use the simple info handler instead of jQuery wait
        wp_enqueue_script('mementor-tts-info-handler');
    }
    
}
add_action('wp_enqueue_scripts', 'mementor_tts_maybe_enqueue_assets', 10);

/**
 * Output custom CSS from Advanced settings.
 */
function mementor_tts_output_custom_css() {
    $custom_css = get_option('mementor_tts_custom_css', '');
    if (! empty(trim($custom_css))) {
        echo "\n<style id=\"mementor-tts-custom-css\">\n" . wp_strip_all_tags($custom_css) . "\n</style>\n";
    }
}
add_action('wp_head', 'mementor_tts_output_custom_css', 100);

/**
 * Add dynamic player styles based on user settings.
 * 
 * This function adds inline CSS to the enqueued stylesheet based on user customizations.
 * It runs after the main asset enqueuing to ensure the target stylesheet is already enqueued.
 *
 * @since    1.0.0
 */
function mementor_tts_add_dynamic_player_styles() {
    // Don't add styles on login pages
    if (mementor_tts_is_login_page()) {
        return;
    }
    
    // Only proceed if we should load assets
    if (!apply_filters('mementor_tts_should_load_assets', false)) {
        return;
    }

    // Only proceed if the main style is registered and enqueued
    if (!wp_style_is('mementor-tts-shared', 'enqueued')) {
        return;
    }

    $dynamic_styles = array();
    
    // Time display visibility
    if (!get_option('mementor_tts_show_time', 1)) {
        $dynamic_styles[] = "
        .mementor-tts-time-display,
        .mementor-tts-duration-display {
            display: none !important;
        }";
    }
    
    // Volume button visibility
    if (!get_option('mementor_tts_show_volume', 1)) {
        $dynamic_styles[] = "
        .mementor-tts-volume-button {
            display: none !important;
        }";
    }
    
    // Speed control visibility
    if (!get_option('mementor_tts_speed_control', 0)) {
        $dynamic_styles[] = "
        .mementor-tts-speed-button {
            display: none !important;
        }";
    }

    // Alignment styles with higher specificity
    $player_alignment = get_option('mementor_tts_player_alignment', 'left');
    
    // Default max-width from options
    $max_width = absint(get_option('mementor_tts_player_max_width', 100));
    $max_width_unit = get_option('mementor_tts_player_max_width_unit', '%');
    
    // Dynamic max-width CSS for custom class and content width
    $dynamic_styles[] = "
    /* High specificity selector to ensure our styles work everywhere */
    html body .mementor-tts-player-container.mementor-tts-width-content_width,
    html body .mementor-tts-player-container.mementor-tts-max-width-custom {
        --mementor-tts-max-width: " . esc_attr($max_width . $max_width_unit) . ";
        max-width: var(--mementor-tts-max-width, 100%) !important;
        width: 100%;
        box-sizing: border-box;
    }
    
    /* IE11 Fallback */
    @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
        html body .mementor-tts-max-width-custom {
            max-width: attr(data-max-width);
        }
    }";
    
    // Validate unit is one of the allowed values
    if (!in_array($max_width_unit, array('%', 'px', 'em', 'rem'))) {
        $max_width_unit = '%';
    }
    
    // Apply alignment with higher specificity
    switch ($player_alignment) {
        case 'left':
            $dynamic_styles[] = "
            html body .mementor-tts-player-container.mementor-tts-align-left {
                margin-left: 0;
                margin-right: auto;
                text-align: left;
            }";
            break;
        
        case 'center':
            $dynamic_styles[] = "
            html body .mementor-tts-player-container.mementor-tts-align-center {
                margin-left: auto;
                margin-right: auto;
                text-align: center;
            }";
            break;
        
        case 'right':
            $dynamic_styles[] = "
            html body .mementor-tts-player-container.mementor-tts-align-right {
                margin-left: auto;
                margin-right: 0;
                text-align: right;
            }";
            break;
    }
    
    // Apply container width styles based on setting
    $player_width = get_option('mementor_tts_player_width', 'content_width');
    
    switch ($player_width) {
        case 'content_width':
            $dynamic_styles[] = "
            html body .mementor-tts-player-container.mementor-tts-width-content_width {
                width: 100%;
            }";
            break;
            
        case 'full_width':
            $dynamic_styles[] = "
            html body .mementor-tts-player-container.mementor-tts-width-full_width {
                width: 100%;
                max-width: 100%;
                margin-left: 0;
                margin-right: 0;
            }
            
            /* Removed the problematic 100vw implementation that breaks layouts
               The container now respects its parent's constraints while still being full width */
            html body .mementor-tts-player-container.mementor-tts-width-full_width {
                box-sizing: border-box;
            }
            
            /* Override max-width constraint when using full width */
            html body .mementor-tts-player-container.mementor-tts-width-full_width.mementor-tts-max-width-custom {
                max-width: none !important;
            }
            
";
            break;
    }
    
    // Add color CSS variables
    $bg_color = sanitize_hex_color(get_option('mementor_tts_player_bg_color', '#f6f7fb'));
    $border_color = sanitize_hex_color(get_option('mementor_tts_player_border_color', '#dcdcde'));
    $text_color = sanitize_hex_color(get_option('mementor_tts_player_text_color', '#50575e'));
    $accent_color = sanitize_hex_color(get_option('mementor_tts_player_accent_color', '#2271b1'));
    $play_button_bg = sanitize_hex_color(get_option('mementor_tts_play_button_bg', '#ffffff'));
    $timer_color = sanitize_hex_color(get_option('mementor_tts_timer_color', '#50575e'));
    $progress_default = sanitize_hex_color(get_option('mementor_tts_progress_bar_default', '#e0e0e0'));
    $progress_playing = sanitize_hex_color(get_option('mementor_tts_progress_bar_playing', '#2271b1'));
    
    // Get customized sizes from options with sanitization
    $play_icon_size = absint(get_option('mementor_tts_play_icon_size', 24));
    $font_size = absint(get_option('mementor_tts_font_size', 14));
    $player_padding = absint(get_option('mementor_tts_player_padding', 15));
    
    $color_css = "
        :root {
            /* Theme Colors */
            --mementor-tts-bg-color: " . esc_attr($bg_color) . " !important;
            --mementor-tts-border-color: " . esc_attr($border_color) . " !important;
            --mementor-tts-text-color: " . esc_attr($text_color) . " !important;
            --mementor-tts-accent-color: " . esc_attr($accent_color) . " !important;
            --mementor-tts-accent-color-hover: " . esc_attr(mementor_tts_adjust_brightness($accent_color, -10)) . " !important;
            
            /* Component Colors */
            --mementor-tts-play-button-bg: " . esc_attr($play_button_bg) . " !important;
            --mementor-tts-play-button-bg-hover: " . esc_attr(mementor_tts_adjust_brightness($play_button_bg, -5)) . " !important;
            --mementor-tts-timer-color: " . esc_attr($timer_color) . " !important;
            --mementor-tts-progress-default: " . esc_attr($progress_default) . " !important;
            --mementor-tts-progress-playing: " . esc_attr($progress_playing) . " !important;
            
            /* Sizes */
            --mementor-tts-play-icon-size: " . esc_attr($play_icon_size) . "px !important;
            --mementor-tts-font-size: " . esc_attr($font_size) . "px !important;
            --mementor-tts-player-padding: " . esc_attr($player_padding) . "px !important;
        }
        
        /* Ensure font size and padding are applied with high specificity */
        html body .mementor-tts-custom-controls {
            font-size: " . esc_attr($font_size) . "px !important;
            padding: " . esc_attr($player_padding) . "px !important;
        }
        
        /* Apply font size to all text elements within the player */
        html body .mementor-tts-custom-controls .mementor-tts-time-display,
        html body .mementor-tts-custom-controls .mementor-tts-duration-display,
        html body .mementor-tts-custom-controls .mementor-tts-speed-button {
            font-size: " . esc_attr($font_size) . "px !important;
        }
        
        /* Override media query overrides for padding */
        @media screen and (max-width: 1024px) {
            html body .mementor-tts-custom-controls {
                padding: " . esc_attr($player_padding) . "px !important;
            }
        }
        
        @media screen and (max-width: 768px) {
            html body .mementor-tts-custom-controls {
                padding: " . esc_attr($player_padding) . "px !important;
            }
        }
        
        @media screen and (max-width: 480px) {
            html body .mementor-tts-custom-controls {
                padding: " . esc_attr($player_padding) . "px !important;
            }
        }
    ";
    
    // Add label styling if label is enabled
    $show_label = get_option('mementor_tts_show_player_label', '0');
    if ($show_label === '1' || $show_label === 1 || $show_label === true) {
        $label_size = absint(get_option('mementor_tts_player_label_size', '14'));
        $label_weight = absint(get_option('mementor_tts_player_label_weight', '400'));
        $label_color = sanitize_hex_color(get_option('mementor_tts_player_label_color', '#1d2327'));
        
        $dynamic_styles[] = "
        /* Dynamic label styling */
        .mementor-tts-player-label {
            font-size: " . esc_attr($label_size) . "px !important;
            font-weight: " . esc_attr($label_weight) . " !important;
            color: " . esc_attr($label_color) . " !important;
        }";
    }
    
    // Add margin settings (use intval to allow negative values)
    $margin_top = intval(get_option('mementor_tts_player_margin_top', 0));
    $margin_bottom = intval(get_option('mementor_tts_player_margin_bottom', 0));
    
    // Debug output
    if (defined('WP_DEBUG') && WP_DEBUG) {
        error_log('TTS CSS Generation: margin_top = ' . $margin_top . ', margin_bottom = ' . $margin_bottom);
    }
    
    // Always add margin styles, even if 0, to ensure they override any theme defaults
    // Use very high specificity to override all position-specific margins
    $color_css .= "
    /* Override all position-specific margins with custom values */
    html body .mementor-tts-player-container,
    html body .mementor-tts-player-container.mementor-tts-before-title,
    html body .mementor-tts-player-container.mementor-tts-before-title-js,
    html body .mementor-tts-player-container.mementor-tts-after-title-before-excerpt,
    html body .mementor-tts-player-container.mementor-tts-after-title-after-excerpt,
    html body .mementor-tts-player-container.mementor-tts-after-title,
    html body .mementor-tts-player-container.mementor-tts-after-title-js,
    html body .mementor-tts-player-container.mementor-tts-after-content,
    .entry-header + .mementor-tts-player-container,
    .entry-content + .mementor-tts-player-container,
    .excerpt + .mementor-tts-player-container,
    .mementor-tts-player-container + .entry-content,
    .mementor-tts-player-container + .excerpt,
    .elementor-widget-container .mementor-tts-player-container,
    .elementor-widget-theme-post-content .mementor-tts-player-container {
        margin-top: " . esc_attr($margin_top) . "px !important;
        margin-bottom: " . esc_attr($margin_bottom) . "px !important;
    }";
    
    // Add color CSS first
    wp_add_inline_style('mementor-tts-shared', $color_css);
    
    // Add the other styles to the page
    if (!empty($dynamic_styles)) {
        $dynamic_styles = array_map('wp_strip_all_tags', $dynamic_styles);
        wp_add_inline_style('mementor-tts-shared', implode("\n", $dynamic_styles));
    }
    
    // Add debug comment to help inspect generated CSS
    if (defined('WP_DEBUG') && WP_DEBUG) {
        add_action('wp_head', function() use ($margin_top, $margin_bottom) {
            echo "\n<!-- TTS Player Margin Debug: top=" . $margin_top . "px, bottom=" . $margin_bottom . "px -->\n";
        }, 999);
    }
}
add_action('wp_enqueue_scripts', 'mementor_tts_add_dynamic_player_styles', 20);

/**
 * Enqueue admin scripts on specific pages.
 * 
 * This function conditionally loads admin-specific scripts only on relevant admin pages
 * to avoid unnecessary asset loading throughout the admin dashboard.
 *
 * @since    1.0.0
 * @param    string    $hook    The current admin page hook.
 */
function mementor_tts_admin_enqueue_scripts($hook) {
    // Don't enqueue on login pages
    if (mementor_tts_is_login_page()) {
        return;
    }
    
    // Only enqueue on plugin pages
    if (strpos($hook, 'text-to-speech-tts') === false) {
        return;
    }
    
    // Special case for shortcodes page - load additional assets
    if (strpos($hook, 'text-to-speech-tts-shortcodes') !== false) {
        wp_enqueue_script('mementor-tts-shortcodes');
        
        // Add localization if needed for this script
        wp_localize_script(
            'mementor-tts-shortcodes',
            'mementorTTSShortcodes',
            array(
                'nonce' => wp_create_nonce('mementor_tts_nonce'),
                'ajaxurl' => admin_url('admin-ajax.php')
            )
        );
    }
}
add_action('admin_enqueue_scripts', 'mementor_tts_admin_enqueue_scripts');

/**
 * Add custom boolean sanitization function if it doesn't exist
 */
if (!function_exists('mementor_tts_sanitize_boolean')) {
    function mementor_tts_sanitize_boolean($value) {
        return (bool) $value;
    }
}

/**
 * Adjust color brightness
 *
 * @since    1.0.0
 * @param    string    $hex      Hex color code
 * @param    int       $steps    Steps to adjust brightness (negative for darker, positive for lighter)
 * @return   string              Adjusted hex color
 */
if (!function_exists('mementor_tts_adjust_brightness')) {
    function mementor_tts_adjust_brightness($hex, $steps) {
        // Remove # if present
        $hex = ltrim($hex, '#');
        
        // Convert to RGB
        $r = hexdec(substr($hex, 0, 2));
        $g = hexdec(substr($hex, 2, 2));
        $b = hexdec(substr($hex, 4, 2));
        
        // Adjust brightness
        $r = max(0, min(255, $r + $steps * 8));
        $g = max(0, min(255, $g + $steps * 8));
        $b = max(0, min(255, $b + $steps * 8));
        
        // Convert back to hex
        return '#' . sprintf('%02x%02x%02x', $r, $g, $b);
    }
}
