<?php
/**
 * Product Table Widget
 */

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

require_once plugin_dir_path(__FILE__) . '../data/class-product-data-handler.php';
require_once plugin_dir_path(__FILE__) . 'widget-product-table/elementor-render.php';

class GGM_Commerce_Widget_Product_Table_Refactored extends \GGM_Commerce_Base_Widget {

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

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

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

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

    public function get_script_depends() {
        return ['ggmc-cart', 'ggmc-product-table'];
    }

    /**
     * Register widget controls by including the content and style files.
     */
    protected function register_controls() {
        require plugin_dir_path(__FILE__) . 'widget-product-table/elementor-controls.php';
        require plugin_dir_path(__FILE__) . 'widget-product-table/elementor-controls-style.php';
    }

    /**
     * Override get_raw_data to ensure column_order includes all columns.
     * 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);

        // Ensure settings array exists
        if (!isset($data['settings'])) {
            $data['settings'] = [];
        }

        // Initialize column_order if not set, or ensure all columns are present
        $existing_order = $data['settings']['column_order'] ?? [];
        $data['settings']['column_order'] = $this->ensure_all_columns_in_order($existing_order);

        return $data;
    }

    /**
     * Override get_settings_for_display to ensure column_order includes all columns.
     * This handles widgets saved before new columns 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 column_order, return directly
        if ($setting_key !== null && $setting_key !== 'column_order') {
            return $settings;
        }

        // If requesting column_order specifically
        if ($setting_key === 'column_order') {
            // $settings here is the value of column_order (could be null or array)
            return $this->ensure_all_columns_in_order($settings ?? []);
        }

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

        return $settings;
    }

    /**
     * Ensure all columns are present in the column order.
     * Missing columns are inserted at their default position.
     * Columns for inactive premium features are removed.
     */
    private function ensure_all_columns_in_order($column_order) {
        // Ensure we have an array to work with
        if (!is_array($column_order)) {
            $column_order = [];
        }

        // Get available columns (respects premium activation)
        $available_columns = ggmc_product_table_get_available_columns();

        // If no existing order, return the default columns
        if (empty($column_order)) {
            return $available_columns;
        }

        $available_ids = array_column($available_columns, 'column_id');

        // First, remove any columns that are no longer available (premium deactivated)
        $column_order = array_filter($column_order, function ($column) use ($available_ids) {
            return isset($column['column_id']) && in_array($column['column_id'], $available_ids, true);
        });
        // Re-index the array
        $column_order = array_values($column_order);

        // Get existing column IDs after filtering
        $existing_ids = array_column($column_order, 'column_id');

        // Find missing columns and their default positions
        foreach ($available_columns as $default_index => $default_column) {
            if (!in_array($default_column['column_id'], $existing_ids, true)) {
                // Insert at the default position (or at the end if beyond current length)
                $insert_position = min($default_index, count($column_order));
                array_splice($column_order, $insert_position, 0, [$default_column]);
                // Update existing_ids for next iteration
                $existing_ids = array_column($column_order, 'column_id');
            }
        }

        return $column_order;
    }

    /**
     * Render the widget output.
     */
    protected function render() {
        ggmc_product_table_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();
    }
}
