<?php
/**
 * Product Grid Widget
 */

// If this file is called directly, abort.
if (!defined('ABSPATH')) {
    exit;
}

// Data handler (shared with other parts of the plugin)
require_once plugin_dir_path(__FILE__) . '../data/class-product-data-handler.php';

// Render functions, available-components helper, and settings mapper
require_once plugin_dir_path(__FILE__) . 'widget-product-grid/elementor-render.php';

class GGM_Commerce_Product_Grid_Widget extends \GGM_Commerce_Base_Widget {

    public function get_name() {
        return 'ggmc-product-grid';
    }

    public function get_title() {
        return 'Product Grid';
    }

    public function get_icon() {
        return 'eicon-gallery-grid';
    }

    public function get_categories() {
        return ['ggmc-widgets'];
    }

    public function get_script_depends() {
        return ['ggmc-product-grid'];
    }

    public function get_style_depends() {
        return ['ggmc-product-grid'];
    }

    /**
     * Get widget keywords
     */
    public function get_keywords() {
        return ['ggm-commerce', 'product', 'grid', 'products', 'shop'];
    }

    /**
     * Register controls — TAB_CONTENT and TAB_STYLE are loaded from subfolder files.
     */
    protected function register_controls() {
        require plugin_dir_path(__FILE__) . 'widget-product-grid/elementor-controls.php';
        require plugin_dir_path(__FILE__) . 'widget-product-grid/elementor-controls-style.php';
    }

    /**
     * Override get_raw_data to ensure component_order includes all components.
     * This is the lowest-level method that retrieves widget data from the database
     * and is used by Elementor's editor to populate the control panel.
     */
    public function get_raw_data($with_html_content = false) {
        $data = parent::get_raw_data($with_html_content);

        if (!isset($data['settings'])) {
            $data['settings'] = [];
        }

        $existing_order             = $data['settings']['component_order'] ?? [];
        $data['settings']['component_order'] = $this->ensure_all_components_in_order($existing_order);

        return $data;
    }

    /**
     * Override get_settings_for_display to ensure component_order includes all components.
     * This handles widgets saved before new components (like Image) were added.
     */
    public function get_settings_for_display($setting_key = null) {
        $settings = parent::get_settings_for_display($setting_key);

        // If requesting a specific key that isn't component_order, return directly
        if ($setting_key !== null && $setting_key !== 'component_order') {
            return $settings;
        }

        // If requesting component_order specifically
        if ($setting_key === 'component_order') {
            return $this->ensure_all_components_in_order($settings ?? []);
        }

        // Ensure component_order is always populated
        $existing_order             = $settings['component_order'] ?? [];
        $settings['component_order'] = $this->ensure_all_components_in_order($existing_order);

        return $settings;
    }

    /**
     * Ensure all components are present in the component order.
     * Missing components are inserted at their default position.
     * Components for inactive premium features are removed.
     */
    private function ensure_all_components_in_order($component_order) {
        if (!is_array($component_order)) {
            $component_order = [];
        }

        // Get available components (respects premium activation)
        $available_components = ggmc_product_grid_get_available_components();

        if (empty($component_order)) {
            return $available_components;
        }

        $available_ids = array_column($available_components, 'component_id');

        // Remove any components that are no longer available (premium deactivated)
        $component_order = array_filter($component_order, function ($component) use ($available_ids) {
            return isset($component['component_id']) && in_array($component['component_id'], $available_ids, true);
        });
        $component_order = array_values($component_order);

        $existing_ids = array_column($component_order, 'component_id');

        // Insert missing components at their default position
        foreach ($available_components as $default_index => $default_component) {
            if (!in_array($default_component['component_id'], $existing_ids, true)) {
                $insert_position = min($default_index, count($component_order));
                array_splice($component_order, $insert_position, 0, [$default_component]);
                $existing_ids = array_column($component_order, 'component_id');
            }
        }

        return $component_order;
    }

    /**
     * Render widget output.
     */
    protected function render() {
        ggmc_product_grid_render( $this );
    }

    /**
     * Get default styles for this widget.
     * Uses centralized configuration from default-widget-styles.php.
     */
    public static function get_static_default_styles() {
        return self::get_defaults_from_config();
    }
}
