<?php
/**
 * Frontend Functionality
 *
 * @package ReplyIt_Chat_Widget
 */

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

class ReplyIt_Frontend {

    /**
     * Single instance
     */
    private static $instance = null;

    /**
     * Get instance
     */
    public static function instance() {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     */
    private function __construct() {
        add_action('wp_enqueue_scripts', [$this, 'enqueue_widget_script']);
        add_action('wp_footer', [$this, 'inject_widget_context'], 5);
    }

    /**
     * Enqueue widget script
     */
    public function enqueue_widget_script() {
        if (!ReplyIt_Core::is_configured() || !get_option('replyit_enabled')) {
            return;
        }

        $config = ReplyIt_Core::get_config();

        // Register and enqueue the widget loader script
        wp_register_script('replyit-widget-loader', '', [], REPLYIT_CHAT_VERSION, true);
        wp_enqueue_script('replyit-widget-loader');

        // Add inline script for widget initialization
        $widget_script = sprintf(
            "(function(w,d,s,o,f,js,fjs){
                w['ChatWidget']=o;w[o] = w[o] || function () { (w[o].q = w[o].q || []).push(arguments) };
                js = d.createElement(s), fjs = d.getElementsByTagName(s)[0];
                js.id = o; js.src = f; js.async = 1; fjs.parentNode.insertBefore(js, fjs);
            }(window, document, 'script', 'cw', '%s/widget.js'));
            cw('init', { widgetId: '%s', apiUrl: '%s' });",
            esc_js($config['api_url']),
            esc_js($config['widget_id']),
            esc_js($config['api_url'])
        );
        wp_add_inline_script('replyit-widget-loader', $widget_script);

        // Enqueue context sender script if WooCommerce is enabled
        if ($config['woocommerce_enabled'] && class_exists('WooCommerce')) {
            wp_enqueue_script(
                'replyit-widget-context',
                REPLYIT_CHAT_PLUGIN_URL . 'public/js/widget-context.js',
                ['jquery'],
                REPLYIT_CHAT_VERSION,
                true
            );

            // Pass config to context script
            wp_localize_script('replyit-widget-context', 'replyitConfig', [
                'widgetId' => $config['widget_id'],
                'apiSecret' => $config['api_secret'],
                'apiUrl' => $config['api_url'],
                'wooEnabled' => true
            ]);

            // Enqueue proactive messages script
            wp_enqueue_script(
                'replyit-woo-proactive',
                REPLYIT_CHAT_PLUGIN_URL . 'public/js/woocommerce-proactive.js',
                [],
                REPLYIT_CHAT_VERSION,
                true
            );

            // Prepare WooCommerce settings for proactive messages
            $cart = WC()->cart;
            $woo_settings = [
                'cart_abandon_enabled' => get_option('replyit_woocommerce_enabled', false),
                'cart_abandon_time' => get_option('replyit_cart_abandon_time', 3),
                'cart_has_items' => $cart && $cart->get_cart_contents_count() > 0,
                'product_page_enabled' => get_option('replyit_woocommerce_enabled', false),
                'product_page_delay' => get_option('replyit_product_page_delay', 20),
                'is_product_page' => is_product(),
                'checkout_help_enabled' => get_option('replyit_checkout_help_enabled', true),
                'is_checkout_page' => is_checkout()
            ];

            wp_localize_script('replyit-woo-proactive', 'replyitWooSettings', $woo_settings);
        }
    }

    /**
     * Inject WooCommerce context data as inline script
     */
    public function inject_widget_context() {
        if (!class_exists('WooCommerce') || !get_option('replyit_woocommerce_enabled')) {
            return;
        }

        $context = ReplyIt_Context::get_page_context();

        if (!empty($context)) {
            // Register and enqueue context script
            wp_register_script('replyit-woo-context', '', [], REPLYIT_CHAT_VERSION, true);
            wp_enqueue_script('replyit-woo-context');

            // Add context data as inline script
            $context_script = 'window.replyitWooContext = ' . wp_json_encode($context) . ';';
            wp_add_inline_script('replyit-woo-context', $context_script);
        }
    }
}
