<?php

class BPLVoiceFeedback {
    protected static $shortcode_used = false;

    public function __construct() {
        add_action('init', ['BPLVF_Ajax_Controller', 'init']);
        add_action('plugins_loaded', [__CLASS__, 'load_dependencies']);
        add_filter('the_posts', [__CLASS__, 'detect_shortcode_usage']);

        // Load Admin Scripts
        add_action('admin_enqueue_scripts', [__CLASS__, 'load_admin_scripts']);

        // ShortCodes and Render
        add_shortcode('voice_feedback', [__CLASS__, 'bplvf_voice_feedbacks_shortcode']);
        add_shortcode('global_voice_feedback', [__CLASS__, 'bplvf_global_shortcode']);
        add_action('template_redirect', [__CLASS__, 'conditionally_add_footer_render']);

    }

    public static function detect_shortcode_usage($posts) {
        if (empty($posts)) return $posts;
    
        foreach ($posts as $post) {
            if (has_shortcode($post->post_content, 'voice_feedback')) {
                self::$shortcode_used = true;
                break;
            }
        }
    
        return $posts;
    }

    public static function conditionally_add_footer_render() {
        if (is_admin() || wp_doing_ajax()) {
            return;
        }
        
        $global_settings = get_option('global_voice_feedback');
        $applyGlobally = isset($global_settings['voiceFeedback']['applyGlobally']) ? $global_settings['voiceFeedback']['applyGlobally'] : true;
        
        if ($applyGlobally) {
            add_action('wp_footer', [__CLASS__, 'render_global_voice_block']);
        }
    }

    public static function render_global_voice_block() {
        echo self::bplvf_global_shortcode();
    }

    public static function load_dependencies() {
        require_once BPLVF_DIR_PATH . 'includes/class-bplvf-admin.php';
        require_once BPLVF_DIR_PATH . 'bplvf-block.php';
        require_once BPLVF_DIR_PATH . 'includes/class-bplvf-ajax-controller.php';
        require_once BPLVF_DIR_PATH . 'includes/functions.php';
        require_once BPLVF_DIR_PATH . 'includes/class-bplvf-rest.php';
        require_once BPLVF_DIR_PATH . 'includes/class-bplvf-handle-email-notification.php';
        require_once BPLVF_DIR_PATH . 'includes/class-bplvf-handle-feedback-upload.php';

        if(BPLVF_HAS_PRO) {
            require_once BPLVF_DIR_PATH . 'includes/class-bplvf-fs-license.php';
        }

        new BPLVF_Handle_Feedback_Upload();
    }

    public static function load_admin_scripts($screen) {
        wp_register_style(
            'bplvf-admin-style',
            false,
            [],
            BPLVF_VERSION
        );
        wp_enqueue_style( 'bplvf-admin-style' );
        $custom_css = "
            li a:has(.fs-submenu-item.voice-feedback.pricing.upgrade-mode),
            li a:has(.fs-submenu-item.voice-feedback.pricing.upgrade-mode):hover {
                background-color: #2563eb !important;
                color: transparent !important;
            }
            .fs-submenu-item.voice-feedback.pricing.upgrade-mode {
                color: white;
            }
        ";

         wp_add_inline_style( 'bplvf-admin-style', $custom_css );

        // Common data
        $localize_data = [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce'   => wp_create_nonce('bplvf_nonce')
        ];

        if ("toplevel_page_voice-feedback" === $screen) {
            
            $feedbacks = get_posts([
                'post_type'      => 'voice_recording',
                'posts_per_page' => -1,
                'post_status'    => 'publish',
            ]);

            $user_feedbacks = array_map(function($post) {
                return [
                    'id'                    => $post->ID,
                    'source_page_title'     => get_post_meta($post->ID, 'source_page_title', true),
                    'source_page_url'       => get_post_meta($post->ID,'source_page_url', true),
                    'audioUrl'              => get_post_meta($post->ID, 'voice_file_url', true),
                    'resolved'              => (bool) get_post_meta($post->ID, 'isResolve', true),
                    'createdAt'             => get_the_date('Y-m-d', $post),
                ];
            }, $feedbacks);


            wp_enqueue_script('bplvf-user-feedback-script', BPLVF_DIR_URL. 'build/user-feedback.js', ['react','react-dom','wp-components'], BPLVF_VERSION, true);
            wp_enqueue_style('bplvf-user-feedback-style', BPLVF_DIR_URL. 'build/user-feedback.css', [], BPLVF_VERSION);

            wp_localize_script('bplvf-user-feedback-script', 'bplvfUsersFeedback', [
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'nonce'   => wp_create_nonce('bplvf_voice_feedback_nonce'),
                'feedbacks' => $user_feedbacks,
            ]);
        }

        if ("voice-feedback_page_all-voice-feedback" === $screen) {
            wp_enqueue_script('bplvf-all-voice-feedback-script', BPLVF_DIR_URL. 'build/all-feedbacks.js', ['react','react-dom','wp-components'], BPLVF_VERSION, true);
            wp_enqueue_style('bplvf-all-voice-feedback-style', BPLVF_DIR_URL. 'build/all-feedbacks.css', [], BPLVF_VERSION);
    
            wp_localize_script('bplvf-all-voice-feedback-script', 'bplvfSettings', ['nonce'   => wp_create_nonce('wp_rest')]);
        }
    
        if ("voice-feedback_page_global-feedback-settings" === $screen) {
            wp_enqueue_script('bplvf-voice-feedback-settings-script', BPLVF_DIR_URL . 'build/settings.js', ['react', 'react-dom','wp-components'], BPLVF_VERSION, true);
            wp_enqueue_style('bplvf-voice-feedback-settings-style', BPLVF_DIR_URL . 'build/settings.css', [], BPLVF_VERSION);

            wp_localize_script('bplvf-voice-feedback-settings-script', 'bplvfSettings', ['nonce'   => wp_create_nonce('wp_rest')]);
        }

        if ("voice-feedback_page_bplvf-dashboard" === $screen) {
            $asset_file = include BPLVF_DIR_PATH . 'build/admin-dashboard.asset.php';
            wp_enqueue_script('bplvf-dashboard-script', BPLVF_DIR_URL . 'build/admin-dashboard.js', array_merge($asset_file['dependencies'], ['wp-util']), BPLVF_VERSION, true);
            wp_enqueue_style('bplvf-dashboard-style', BPLVF_DIR_URL . 'build/admin-dashboard.css', [], BPLVF_VERSION);
        }

        if ("voice-feedback_page_bplvf-global-settings" === $screen) {
            wp_enqueue_script('bplvf-feedback-settings-script', BPLVF_DIR_URL. 'build/feedback-settings.js', ['react','react-dom','wp-components'], BPLVF_VERSION, true);
            wp_enqueue_style('bplvf-feedback-settings-style', BPLVF_DIR_URL. 'build/feedback-settings.css', [], BPLVF_VERSION);
    
            wp_localize_script('bplvf-feedback-settings-script', 'bplvfSettings', ['nonce'   => wp_create_nonce('wp_rest')]);
        }


    }

    public static function bplvf_voice_feedbacks_shortcode($atts) {
        self::$shortcode_used = true;
        $atts = shortcode_atts(['id' => 0], $atts);
        $id   = (int) $atts['id'];
    
        $post = get_post($id);
        if (!$post || $post->post_type !== 'voice_feedback') {
            return '<p>Voice Feedback not found.</p>';
        }

        // Get block settings (from post content)
        $blocks = parse_blocks($post->post_content);
        $block_settings = [];

        foreach ($blocks as $block) {
            if (isset($block['blockName']) && $block['blockName'] === 'bplvf/voice-feedback') {
                $block_settings = $block['attrs'];
                break; 
            }
        }

        $meta_settings  = get_post_meta($post->ID, 'bplvf_settings', true);
        $meta_settings  = is_array($meta_settings) ? $meta_settings : [];

        $block_settings = is_array($block_settings) ? $block_settings : [];

        $replace_settings = array_replace_recursive($meta_settings, $block_settings);
        $settings = bplvf_block_settings($replace_settings);
        
    
        $block = [
            'blockName'    => 'bplvf/voice-feedback', 
            'attrs'        => $settings, 
            'innerBlocks'  => [],
            'innerHTML'    => '',
            'innerContent' => [],
        ];

        return render_block($block);
    }

    public static function bplvf_global_shortcode() { 
        self::$shortcode_used = true;
        $global_settings = get_option('global_voice_feedback', []);
        $merged  = bplvf_merge_with_defaults($global_settings);

        $block = [
            'blockName'    => 'bplvf/voice-feedback', 
            'attrs'        => $merged, 
            'innerBlocks'  => [],
            'innerHTML'    => '',
            'innerContent' => [],
        ];
        
        return render_block($block);
    }


}