<?php

/**
 * The public-facing functionality of the plugin.
 *
 * @link       https://webequipe.com
 * @since      1.0.0
 *
 * @package    Webequipe_Spin_Win_Wheel
 * @subpackage Webequipe_Spin_Win_Wheel/public
 */

/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the public-facing stylesheet and JavaScript.
 *
 * @package    Webequipe_Spin_Win_Wheel
 * @subpackage Webequipe_Spin_Win_Wheel/public
 * @author     Webequipe <support@webequipe.com>
 */

declare( strict_types=1 );

namespace Webequipe\SpinWinWheel\Frontend;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Shortcode handler class
 */
class Shortcode
{
    /**
     * Static variable to store CSS for inline style
     *
     * @var string
     */
    private static $inline_css = '';

    /**
     * Static variable to store inline scripts
     *
     * @var array
     */
    private static $inline_scripts = [];

    /**
         * Initializes the class
         */
    public function __construct()
    {
        add_shortcode( 'wsww-spin', [ $this, 'render_shortcode' ] );
        // Enqueue scripts when shortcode is present
        add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_shortcode_assets' ] );
        // Print inline CSS in footer after shortcode has run.
        add_action( 'wp_footer', [ $this, 'add_inline_css' ], 10 );
        add_action( 'wp_print_footer_scripts', [ $this, 'add_inline_scripts' ], 20 );
    }
    
    /**
     * Enqueue assets for shortcode
     */
    public function enqueue_shortcode_assets() {
        global $post;
        
        // Check if shortcode exists in content
        if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'wsww-spin' ) ) {
            // Enqueue D3 library first
            wp_enqueue_script( 'd3-v3' );
            
            // Enqueue Bootstrap JS (needed for modal)
            wp_enqueue_script(
                'wsww-bootstrap-js',
                WEBEQUIPE_SPIN_WIN_WHEEL_ASSETS . '/js/bootstrap.bundle.min.js',
                array( 'jquery' ),
                file_exists(WEBEQUIPE_SPIN_WIN_WHEEL_PATH . '/assets/js/bootstrap.bundle.min.js') ? filemtime(WEBEQUIPE_SPIN_WIN_WHEEL_PATH . '/assets/js/bootstrap.bundle.min.js') : '1.0.0',
                true
            );
            
            // Enqueue frontend scripts and styles in correct order
            wp_enqueue_style( 'wsww-bootstrap-style' ); // Bootstrap first
            wp_enqueue_style( 'wsww-spin-style' ); // Spinner wheel CSS (depends on Bootstrap)
            wp_enqueue_style( 'wsww-frontend-style' ); // Public CSS (depends on spin-style)
            wp_enqueue_script( 'wsww-frontend-script' );
            wp_enqueue_script( 'wsww-ajax-script' );
            
            // Localize script with updated data
            wp_localize_script(
                'wsww-ajax-script',
                'wswwSpinObj',
                array(
                    'ajaxurl'             => admin_url( 'admin-ajax.php' ),
                    'allow_multiple_spin' => get_option( 'wsww_setting_options_allow_multiple_spin', 0 ),
                    'error'              => __( 'Something went wrong', 'webequipe-spin-win-wheel' ),
                    'nonce'              => wp_create_nonce( 'wsww-email-enquiry-form' ),
                    'spinWinNonce'        => wp_create_nonce( 'wsww-spin-win-form' ),
                )
            );
        }
    }

    /**
     * Shortcode handler class
     *
     * @param array  $atts
     * @param string $content
     *
     * @return string
     */
    public function render_shortcode( $atts, $content = '' ) {
        static $already_rendered = false;
    
        // Prevent multiple shortcodes from rendering
        if ( $already_rendered ) {
            return '<div class="wsww-error" style="color:red;">' . esc_html__( 'Only one spin wheel is allowed per page.', 'webequipe-spin-win-wheel' ) . '</div>';
        }
    
        $already_rendered = true;
    
        // Ensure assets are enqueued (they should be enqueued by enqueue_shortcode_assets, but enqueue here as fallback)
        // Enqueue in correct order: Bootstrap -> Spin CSS -> Frontend CSS
        wp_enqueue_style( 'wsww-bootstrap-style' );
        wp_enqueue_style( 'wsww-spin-style' );
        wp_enqueue_style( 'wsww-frontend-style' );
        wp_enqueue_script( 'd3-v3' );
        // Enqueue Bootstrap JS (needed for modal)
        wp_enqueue_script(
            'wsww-bootstrap-js',
            WEBEQUIPE_SPIN_WIN_WHEEL_ASSETS . '/js/bootstrap.bundle.min.js',
            array( 'jquery' ),
            file_exists(WEBEQUIPE_SPIN_WIN_WHEEL_PATH . '/assets/js/bootstrap.bundle.min.js') ? filemtime(WEBEQUIPE_SPIN_WIN_WHEEL_PATH . '/assets/js/bootstrap.bundle.min.js') : '1.0.0',
            true
        );
        wp_enqueue_script( 'wsww-frontend-script' );
        wp_enqueue_script( 'wsww-ajax-script' );
    
        // Localize script with updated data (override the default from Assets class)
        wp_localize_script(
            'wsww-ajax-script',
            'wswwSpinObj',
            array(
                'ajaxurl'             => admin_url( 'admin-ajax.php' ),
                'allow_multiple_spin' => get_option( 'wsww_setting_options_allow_multiple_spin', 0 ),
                'error'              => __( 'Something went wrong', 'webequipe-spin-win-wheel' ),
                'nonce'              => wp_create_nonce( 'wsww-email-enquiry-form' ),
                'spinWinNonce'        => wp_create_nonce( 'wsww-spin-win-form' ),
            )
        );
        $data = shortcode_atts( [
            'id' => '',
        ], $atts );
    
        // Generate CSS for this spin wheel (stored in static variable)
        $this->generate_spin_css( $data );
    
        ob_start();
        include __DIR__ . '/partials/webequipe-spin-win-wheel-public-spin-wheel.php';
        return ob_get_clean();
    }
    
    /**
     * Add inline CSS during wp_footer hook
     * This runs after shortcode rendering, so CSS is already generated
     * Outputs CSS directly in footer as styles may already be printed in head
     *
     * @return void
     */
    public function add_inline_css() {
        if ( empty( self::$inline_css ) ) {
            return;
        }

        $handle = 'wsww-inline-style';

        if ( ! wp_style_is( $handle, 'registered' ) ) {
            wp_register_style( $handle, false, [], WEBEQUIPE_SPIN_WIN_WHEEL_VERSION );
        }

        wp_enqueue_style( $handle );
        // CSS is already properly escaped when built (using esc_attr() for values)
        // No need for wp_strip_all_tags() as CSS doesn't contain HTML
        wp_add_inline_style( $handle, self::$inline_css );
        wp_print_styles( $handle );

        self::$inline_css = '';
    }
    
    /**
     * Generate CSS for spin wheel variables and store in static variable
     *
     * @param array $data Shortcode data
     * @return void
     */
    private function generate_spin_css( $data ) {
        global $webequipe_sww_spin_shortcode_id, $webequipe_sww_spin_default_id;
        
        $webequipe_sww_spin_default_id = (int) get_option('wsww_setting_options_default');
        $webequipe_sww_spin_shortcode_id = ($webequipe_sww_spin_default_id !== 0) ? $webequipe_sww_spin_default_id : (isset($data['id']) ? $data['id'] : 0);
        
        if (empty($webequipe_sww_spin_shortcode_id)) {
            return;
        }
        
        $spin = webequipe_sww_get_spin($webequipe_sww_spin_shortcode_id);
        if (empty($spin) || is_wp_error($spin)) {
            return;
        }
        
        // Get spin settings
        $card_background = $spin->card_background ?? '';
        $card_color = $spin->card_color ?? '';
        $card_boder_radius = $spin->card_boder_radius ?? 0;
        $card_boder_padding = $spin->card_boder_padding ?? 0;
        $wheel_center_background = $spin->wheel_center_background ?? '';
        $wheel_center_boder_color = $spin->wheel_center_boder_color ?? '';
        $wheel_center_boder_width = $spin->wheel_center_boder_width ?? 0;
        $wheel_stroke_border_color = $spin->wheel_stroke_border_color ?? '';
        $wheel_stroke_border_size = $spin->wheel_stroke_border_size ?? 0;
        $wheel_stroke_font_size = $spin->wheel_stroke_font_size ?? 0;
        $wheel_stroke_font_family = $spin->wheel_stroke_font_family ?? '';
        $wheel_stroke_font_style = $spin->wheel_stroke_font_style ?? '';
        $from_button_color = $spin->from_button_color ?? '';
        $from_button_background_color = $spin->from_button_background_color ?? '';
        
        // Build CSS variables
        $css = ':root, .wsww-shortcode-wrapper {';
        $css .= '  --card_background: ' . esc_attr($card_background) . ';';
        $css .= '  --card_color: ' . esc_attr($card_color) . ';';
        $css .= '  --card_boder_radius: ' . (int) $card_boder_radius . 'px;';
        $css .= '  --card_boder_padding: ' . (int) $card_boder_padding . 'px;';
        $css .= '  --wheel_center_background: ' . esc_attr($wheel_center_background) . ';';
        $css .= '  --wheel_center_boder_color: ' . esc_attr($wheel_center_boder_color) . ';';
        $css .= '  --wheel_center_boder_width: ' . (int) $wheel_center_boder_width . 'px;';
        $css .= '  --wheel_stroke_border_color: ' . esc_attr($wheel_stroke_border_color) . ';';
        $css .= '  --wheel_stroke_border_size: ' . (int) $wheel_stroke_border_size . 'px;';
        $css .= '  --wheel_stroke_font_size: ' . (int) $wheel_stroke_font_size . 'px;';
        $css .= '  --wheel_stroke_font_family: ' . esc_attr($wheel_stroke_font_family) . ';';
        $css .= '  --wheel_stroke_font_style: ' . esc_attr($wheel_stroke_font_style) . ';';
        $css .= '  --from_button_color: ' . esc_attr($from_button_color) . ';';
        $css .= '  --from_button_background_color: ' . esc_attr($from_button_background_color) . ';';
        $css .= '}';
        
        // Minify CSS
        if (!function_exists('webequipe_sww_spin_minify_css')) {
            function webequipe_sww_spin_minify_css($css) {
                $css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css);
                $css = preg_replace('/\s+/', ' ', $css);
                $css = preg_replace('/\s*([{}:;,>+~])\s*/', '$1', $css);
                $css = str_replace(';}', '}', $css);
                return trim($css);
            }
        }
        
        $css = webequipe_sww_spin_minify_css($css);
        
        // Store CSS until footer output hooks run.
        self::$inline_css = $css;
    }

    /**
     * Add inline scripts during wp_print_footer_scripts hook
     * This runs after shortcode rendering, so scripts are already collected
     * Output scripts directly before the registered footer scripts are printed
     *
     * @return void
     */
    public function add_inline_scripts() {
        if ( empty( self::$inline_scripts ) ) {
            return;
        }

        if ( ! wp_script_is( 'wsww-frontend-script', 'enqueued' ) ) {
            return;
        }

        foreach ( self::$inline_scripts as $script ) {
            if ( empty( $script ) ) {
                continue;
            }

            wp_add_inline_script( 'wsww-frontend-script', $script, 'after' );
        }

        self::$inline_scripts = [];
    }

    /**
     * Store inline script content to be added via wp_add_inline_script()
     *
     * @param string $script_content The JavaScript code to add
     * @return void
     */
    public static function add_inline_script_content( $script_content ) {
        if ( empty( $script_content ) ) {
            return;
        }

        if ( wp_script_is( 'wsww-frontend-script', 'enqueued' ) ) {
            wp_add_inline_script( 'wsww-frontend-script', $script_content, 'after' );
            return;
        }

        self::$inline_scripts[] = $script_content;
    }


}
