<?php
/**
 * Admin Chat Box Shortcode Handler
 *
 * This class handles shortcodes for the chat widget
 *
 * @package ACB\Inc
 */

namespace ACB\Inc;

defined('ABSPATH') || die('Hey, what are you doing here? You silly human!');

/**
 * ACB_Shortcode Class
 *
 * @since 1.0.0
 */
class ACB_Shortcode {
    
    /**
     * Constructor
     */
    public function __construct() {
        add_action('init', [$this, 'register_shortcodes']);
        add_action('wp_enqueue_scripts', [$this, 'enqueue_shortcode_scripts']);
    }
    
    /**
     * Register shortcodes
     */
    public function register_shortcodes() {
        add_shortcode('acb_chat_widget', [$this, 'render_chat_widget']);
        add_shortcode('acb_chat', [$this, 'render_chat_widget']); // Alternative shortcode
    }
    
    /**
     * Render chat widget shortcode
     * 
     * @param array $atts Shortcode attributes
     * @return string HTML output
     */
    public function render_chat_widget($atts) {
        // Parse shortcode attributes
        $atts = shortcode_atts([
            'position' => 'bottom-right',
            'title' => 'Chat Support',
            'description' => 'Need help? Chat with our team!',
            'color' => '#5A5EB9',
            'enabled' => 'true',
            'id' => uniqid('acb_widget_')
        ], $atts, 'acb_chat_widget');
        
        // Sanitize attributes
        $position = sanitize_text_field($atts['position']);
        $title = sanitize_text_field($atts['title']);
        $description = sanitize_text_field($atts['description']);
        $color = sanitize_hex_color($atts['color']) ?: '#5A5EB9';
        $enabled = filter_var($atts['enabled'], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
        if ($enabled === null) {
            $enabled = ($atts['enabled'] !== 'false' && $atts['enabled'] !== '0');
        }
        $widget_id = sanitize_text_field($atts['id']);
        
        // Check if widget is enabled
        if (!$enabled) {
            return '';
        }
        
        // Validate position
        $allowed_positions = ['bottom-right', 'bottom-left', 'top-right', 'top-left', 'inline'];
        if (!in_array($position, $allowed_positions, true)) {
            $position = 'bottom-right';
        }
        
        // Check if Firebase is configured
        $firebase_config = get_option('firebaseConfig', []);
        if (empty($firebase_config) || empty($firebase_config['apiKey'])) {
            return '<div class="acb-widget-error" style="padding: 15px; background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; border-radius: 4px; margin: 10px 0;">Chat widget is not configured. Please configure Firebase settings in the admin panel.</div>';
        }
        
        // Enqueue scripts for this specific widget
        $this->enqueue_widget_scripts($widget_id);
        
        // Generate unique container ID
        $container_id = 'acb-shortcode-widget-' . $widget_id;
        
        // Inline styles for positioning
        $inline_styles = $this->get_position_styles($position, $color);
        
        // Widget HTML
        ob_start();
        ?>
        <div id="<?php echo esc_attr($container_id); ?>" 
             class="acb-shortcode-widget acb-position-<?php echo esc_attr($position); ?>"
             data-position="<?php echo esc_attr($position); ?>"
             data-title="<?php echo esc_attr($title); ?>"
             data-description="<?php echo esc_attr($description); ?>"
             data-color="<?php echo esc_attr($color); ?>"
             data-widget-id="<?php echo esc_attr($widget_id); ?>"
             style="<?php echo esc_attr($inline_styles); ?>">
        </div>
        <?php
        
        return ob_get_clean();
    }
    
    /**
     * Get position-specific CSS styles
     * 
     * @param string $position Widget position
     * @param string $color Primary color
     * @return string CSS styles
     */
    private function get_position_styles($position, $color) {
        $styles = [];
        
        switch ($position) {
            case 'bottom-right':
                $styles[] = 'position: fixed';
                $styles[] = 'bottom: 20px';
                $styles[] = 'right: 20px';
                $styles[] = 'z-index: 9999';
                break;
                
            case 'bottom-left':
                $styles[] = 'position: fixed';
                $styles[] = 'bottom: 20px';
                $styles[] = 'left: 20px';
                $styles[] = 'z-index: 9999';
                break;
                
            case 'top-right':
                $styles[] = 'position: fixed';
                $styles[] = 'top: 20px';
                $styles[] = 'right: 20px';
                $styles[] = 'z-index: 9999';
                break;
                
            case 'top-left':
                $styles[] = 'position: fixed';
                $styles[] = 'top: 20px';
                $styles[] = 'left: 20px';
                $styles[] = 'z-index: 9999';
                break;
                
            case 'inline':
                $styles[] = 'position: relative';
                $styles[] = 'display: block';
                $styles[] = 'margin: 20px 0';
                break;
        }
        
        // Add color variables
        $styles[] = '--acb-primary-color: ' . $color;
        
        return implode('; ', $styles);
    }
    
    /**
     * Enqueue scripts for shortcode widgets
     */
    public function enqueue_shortcode_scripts() {
        // Only enqueue if shortcode is used on the page
        global $post;
        
        if (is_a($post, 'WP_Post') && (has_shortcode($post->post_content, 'acb_chat_widget') || has_shortcode($post->post_content, 'acb_chat'))) {
            $this->enqueue_widget_scripts();
        }
    }
    
    /**
     * Enqueue widget scripts and styles
     * 
     * @param string $widget_id Optional widget ID for specific targeting
     */
    private function enqueue_widget_scripts($widget_id = '') {
        $plugin_url = plugin_dir_url(dirname(__FILE__));
        
        // Enqueue shortcode widget styles
        wp_enqueue_style(
            'acb-shortcode-widget-style',
            $plugin_url . 'build/shortcode-index.css',
            [],
            '1.0.0'
        );
        
        wp_enqueue_style(
            'font-awesome', 
            $plugin_url . 'assets/library/all.min.css', 
            [], 
            '5.15.4'
        );

        // Enqueue shortcode widget script
        wp_enqueue_script(
            'acb-shortcode-widget-script',
            $plugin_url . 'build/shortcode-index.js',
            ['jquery', 'wp-element'],
            '1.0.0',
            true
        );

        // Pass Firebase config and settings to frontend
        $firebase_config = get_option('firebaseConfig', []);
        $widget_settings = $this->get_widget_settings();
        
        // Sanitize Firebase config before passing to frontend
        $sanitized_config = $this->sanitize_firebase_config($firebase_config);
        
        wp_localize_script('acb-shortcode-widget-script', 'appLocalizer', [
            'apiUrl' => home_url('/wp-json'),
            'nonce' => wp_create_nonce('acb_nonce'),
            'adminAjax' => admin_url('admin-ajax.php'),
            'config' => $sanitized_config,
        ]);
        wp_localize_script('acb-shortcode-widget-script', 'acb_widget_settings', $widget_settings);
        
        // Script will automatically initialize shortcode widgets
    }
    
    /**
     * Get widget settings from database
     * 
     * @return array Widget settings
     */
    private function get_widget_settings() {
        global $wpdb;
        $table_settings = $wpdb->prefix . 'acb_settings';
        
        $settings = [];
        $settings_keys = [
            'frontend_widget_enabled',
            'widget_position', 
            'widget_title',
            'widget_description',
            'widget_primary_color'
        ];
        
        foreach ($settings_keys as $key) {
            $value = $wpdb->get_var(
                $wpdb->prepare("SELECT setting_value FROM $table_settings WHERE setting_key = %s", $key)
            );
            
            switch ($key) {
                case 'frontend_widget_enabled':
                    $settings[$key] = $value !== null ? (bool) $value : true;
                    break;
                case 'widget_position':
                    $settings[$key] = $value !== null ? $value : 'bottom-right';
                    break;
                case 'widget_title':
                    $settings[$key] = $value !== null ? $value : 'Chat Support';
                    break;
                case 'widget_description':
                    $settings[$key] = $value !== null ? $value : 'Need help? Chat with our team!';
                    break;
                case 'widget_primary_color':
                    $settings[$key] = $value !== null ? $value : '#5A5EB9';
                    break;
                default:
                    $settings[$key] = $value;
            }
        }
        
        return $settings;
    }
    
    /**
     * Sanitize Firebase config for frontend use
     * 
     * @param array $config Firebase configuration
     * @return array Sanitized configuration
     */
    private function sanitize_firebase_config($config) {
        if (!is_array($config)) {
            return [];
        }

        $sanitized = [];
        $allowed_keys = ['apiKey', 'authDomain', 'projectId', 'storageBucket', 'messagingSenderId', 'appId'];
        
        foreach ($allowed_keys as $key) {
            if (isset($config[$key])) {
                $sanitized[$key] = sanitize_text_field($config[$key]);
            }
        }
        
        return $sanitized;
    }
    

}