<?php
/**
 * GGM Commerce Quick View Class
 *
 * Handles AJAX rendering of Quick View popup content with product context.
 * Premium component - requires 'quick-view' activation in license settings.
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class GGM_Commerce_Quick_View {

    /**
     * Instance of this class
     */
    private static $instance = null;

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

    /**
     * Constructor - register AJAX handlers
     */
    public function __construct() {
        // AJAX handlers for both logged-in and guest users
        add_action('wp_ajax_ggm_commerce_quick_view', array($this, 'render_quick_view'));
        add_action('wp_ajax_nopriv_ggm_commerce_quick_view', array($this, 'render_quick_view'));

        // Hook into widget activation to create popup template
        add_action('ggm_commerce_widget_activated', array($this, 'on_widget_activated'));
    }

    /**
     * Handle widget activation - create Quick View popup template if activated
     *
     * @param string $widget_slug The slug of the widget that was activated
     */
    public function on_widget_activated($widget_slug) {
        if ($widget_slug !== 'quick-view') {
            return;
        }

        // Create the Quick View popup template
        if (class_exists('GGM_Commerce_Page_Builder')) {
            \GGM_Commerce_Page_Builder::create_quick_view_popup();
        }
    }

    /**
     * Check if Quick View feature is activated
     */
    public static function is_activated() {
        if (!class_exists('GGM_Commerce_License')) {
            return false;
        }
        return \GGM_Commerce_License::instance()->is_widget_activated('quick-view');
    }

    /**
     * AJAX handler - render Quick View popup content
     */
    public function render_quick_view() {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'ggm_commerce_quick_view_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed'));
        }

        // Check if Quick View is activated
        if (!self::is_activated()) {
            wp_send_json_error(array('message' => 'Quick View feature is not activated'));
        }

        // Get product ID
        $product_id = isset($_POST['product_id']) ? absint($_POST['product_id']) : 0;
        if (!$product_id) {
            wp_send_json_error(array('message' => 'Product ID is required'));
        }

        // Validate product exists
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $product = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}ggmc_products WHERE id = %d",
            $product_id
        ));

        if (!$product) {
            wp_send_json_error(array('message' => 'Product not found'));
        }

        // Set global product context for widgets
        $GLOBALS['ggmc_current_product_id'] = $product_id;

        // Render the popup content — use Elementor Pro popup if available, otherwise native render
        if ( class_exists( '\ElementorPro\Plugin' ) ) {
            $html = $this->render_quick_view_elementor( $product_id );
        } else {
            $html = $this->render_quick_view_native( $product );
        }

        if (empty($html)) {
            wp_send_json_error(array('message' => 'Failed to render Quick View content'));
        }

        wp_send_json_success(array(
            'html' => $html,
            'product_id' => $product_id,
            'product_name' => $product->name,
            'product_url' => GGM_Commerce_Helpers::get_product_details_url($product_id)
        ));
    }

    /**
     * Render Quick View via Elementor popup template.
     *
     * @param int $product_id Product ID (global context already set).
     * @return string Rendered HTML.
     */
    private function render_quick_view_elementor( $product_id ) {
        $popup_id = get_option( 'ggm_commerce_quick_view_popup_id' );

        if ( ! $popup_id || get_post_status( $popup_id ) !== 'publish' ) {
            if ( class_exists( 'GGM_Commerce_Page_Builder' ) ) {
                \GGM_Commerce_Page_Builder::create_quick_view_popup();
                $popup_id = get_option( 'ggm_commerce_quick_view_popup_id' );
            }
        }

        if ( ! $popup_id || get_post_status( $popup_id ) !== 'publish' ) {
            return '';
        }

        ob_start();
        $elementor = \Elementor\Plugin::instance();
        if ( $elementor->frontend ) {
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            echo $elementor->frontend->get_builder_content_for_display( $popup_id, true );
        }
        return ob_get_clean();
    }

    /**
     * Render Quick View natively using the block adapter and existing render functions.
     * No Elementor dependency — mirrors the Quick View popup layout.
     *
     * @param object $product Product row from ggmc_products.
     * @return string Rendered HTML.
     */
    private function render_quick_view_native( $product ) {
        // Load render functions.
        $widgets_dir = plugin_dir_path( dirname( __FILE__ ) ) . 'widgets/tags/';
        require_once $widgets_dir . 'widget-product-image/elementor-render.php';
        require_once $widgets_dir . 'widget-product-name/elementor-render.php';
        require_once $widgets_dir . 'widget-product-price/elementor-render.php';
        require_once $widgets_dir . 'widget-product-stock/elementor-render.php';
        require_once $widgets_dir . 'widget-product-description/elementor-render.php';
        require_once $widgets_dir . 'widget-add-to-cart/elementor-render.php';
        require_once $widgets_dir . 'widget-product-details-link/elementor-render.php';

        // Load the block adapter.
        if ( ! class_exists( 'GGMC_Block_Adapter' ) ) {
            require_once plugin_dir_path( dirname( __FILE__ ) ) . 'blocks/class-block-adapter.php';
        }

        ob_start();
        ?>
        <div class="ggmc-quick-view-native" style="display:flex;flex-wrap:wrap;gap:30px;padding:30px;">
            <div class="ggmc-quick-view-image" style="flex:0 0 40%;max-width:40%;">
                <?php
                $adapter = new \GGMC_Block_Adapter( array(), $product );
                ggmc_product_image_render( $adapter );
                ?>
            </div>
            <div class="ggmc-quick-view-info" style="flex:1;min-width:0;display:flex;flex-direction:column;gap:12px;">
                <?php
                $adapter = new \GGMC_Block_Adapter( array( 'html_tag' => 'h2' ), $product );
                ggmc_product_name_render( $adapter );

                $adapter = new \GGMC_Block_Adapter( array(), $product );
                ggmc_product_price_render( $adapter );

                $adapter = new \GGMC_Block_Adapter( array(), $product );
                ggmc_product_stock_render( $adapter );

                $adapter = new \GGMC_Block_Adapter( array( 'description_type' => 'short', 'show_read_more' => '' ), $product );
                ggmc_product_description_render( $adapter );

                $adapter = new \GGMC_Block_Adapter( array( 'show_quantity' => 'yes', 'button_text' => 'Add to Cart' ), $product );
                ggmc_add_to_cart_render( $adapter );

                $adapter = new \GGMC_Block_Adapter( array( 'link_text' => 'View Full Details →', 'link_style' => 'text', 'close_popup' => 'yes' ), $product );
                ggmc_product_details_link_render( $adapter );
                ?>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }

    /**
     * Get Quick View popup template ID
     */
    public static function get_popup_id() {
        return get_option('ggm_commerce_quick_view_popup_id');
    }
}

/**
 * Initialize Quick View functionality
 */
function ggm_commerce_quick_view() {
    return GGM_Commerce_Quick_View::instance();
}

// Initialize immediately since file is loaded after plugins_loaded
// The file is required during 'init' hook in goose-commerce.php
ggm_commerce_quick_view();
