<?php

namespace FluentPlayer\App\Hooks\Handlers;

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

use FluentPlayer\App\Helpers\Helper;
use FluentPlayer\Framework\Support\Arr;

class CustomCssJsHandler
{
    protected static $cssJsOutputDone = false;

    /**
     * Initialize the handler by adding the action hook
     */
    public static function handle()
    {
        add_action('fluent_player/before_render_media', [self::class, 'addCssJs'], 10);
    }

    /**
     * Handle outputting custom CSS and JS
     *
     * @param mixed $media Media object (optional)
     */
    public static function addCssJs($media = null)
    {
        if (self::$cssJsOutputDone) {
            return;
        }
        self::$cssJsOutputDone = true;

        $settings = Helper::getSettings();
        $css = Arr::get($settings, 'general.custom_css', '');
        $js = Arr::get($settings, 'general.custom_js', '');

        // Use your custom sanitize functions, if they exist:
        if (function_exists('wpfp_sanitize_css')) {
            $css = wpfp_sanitize_css($css);
        }
        if (function_exists('wpfp_sanitize_js')) {
            $js = wpfp_sanitize_js($js);
        }
     
        if ($css) {
            wp_register_style('fluent-player-custom-css', false, [], FLUENT_PLAYER_VERSION);
            wp_enqueue_style('fluent-player-custom-css');
            wp_add_inline_style('fluent-player-custom-css', $css);
        }

        if ($js) {
            add_action('wp_footer', function() use ($js) {
                echo '<script id="fluent_player_global_custom_js">';
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- JavaScript code is already sanitized with wpfp_sanitize_js()
                echo "(function(){try{" . $js . "}catch(e){console.error('Fluent Player global custom JS error',e);}})();";
                echo '</script>';
            }, 20);
        }
    }
}
