<?php

/**
 * Core Setup and Loading Handler
 * 
 * @package cwpt
 * @since 1.0.0
 */

defined('ABSPATH') or die;

class CWPT_Core
{
    /**
     * Initialize icon select field
     * 
     * @return void
     */
    public static function init_icon_select()
    {
        if (!class_exists('CMBS_SerkanA_Plugin_IConSelectFA') && !function_exists('returnRayFaPre')) {
            require_once plugin_dir_path(dirname(__FILE__)) . 'libraries/cmb2-field-faiconselect/iconselect.php';
        }
    }

    /**
     * Load plugin dependencies when WooCommerce is loaded
     * 
     * @return void
     */
    public static function load()
    {
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/cwpt_functions.php';
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/cwpt-admin-tabs.php';
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/cwpt-templates.php';
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/cwpt-settings.php';
        
        if (!class_exists('CMB2')) {
            require_once dirname(dirname(__FILE__)) . '/libraries/cmb2/init.php';
        }

        if (!class_exists('cmb2_tabs\inc\CMB2_Tabs')) {
            require_once dirname(dirname(__FILE__)) . '/libraries/cmb2-tabs/plugin.php';
        }

        self::init_icon_select();

        // Ensure WooCommerce gallery features are enabled for custom layouts
        add_action('after_setup_theme', ['CWPT_Core', 'ensure_wc_gallery_support']);
        add_action('cmb2_admin_init', ['CWPT_Admin_Tabs', 'register_meta_boxes']);
        
        // Migration from old version
        if (is_admin() && get_option('cwpt_activated') && function_exists('rwmb_meta') && !get_option('cwpt_migirated')) {
            self::migrate_old_data();
        }

        // Let CMB2 handle group field saves (matches 1.3.8 behavior)

        // Add empty options group for custom product types
        add_action('woocommerce_product_options_general_product_data', function () {
            $ids = '';
            foreach (CWPT_Settings::get('name_ids') as $ID) {
                $ids .= ' show_if_' . $ID;
            }
            echo '<div class="options_group ' . esc_attr($ids) . ' clear"></div>';
        });
    }

    /**
     * Migrate old version data to new format
     * 
     * @return void
     */
    private static function migrate_old_data()
    {
        add_option('cwpt_migirated', true);

        $args = array(
            'post_type' => 'custom-product-type',
            'posts_per_page' => -1,
            'fields' => 'ids'
        );

        $custom_product_types = get_posts($args);

        if (empty($custom_product_types)) {
            return;
        }

        foreach ($custom_product_types as $post_id) {

            $meta_fields = array(
                'cwpt_product_type_name_singular',
                'cwpt_product_type_name_plural',
                'cwpt_custom_taxonomy',
                'cwpt_show_in_shop',
                'cwpt_enable_badge',
                'cwpt_badge_text',
                'cwpt_badge_background_color',
                'cwpt_badge_text_color',
                'cwpt_enable_custom_tab',
                'cwpt_custom_tab_label',
                'cwpt_custom_tab_text_fields'
            );

            $new_field = array(
                'iconselect' => isset($field['field_icon']) ? $field['field_icon'] : '',
                'type' => isset($field['field_type']) ? strtolower(str_replace(' ', '_', $field['field_type'])) : 'text',
                'label' => isset($field['field_label']) ? $field['field_label'] : '',
                'description' => isset($field['field_desc']) ? $field['field_desc'] : '',
                'options' => isset($field['field_options']) ? $field['field_options'] : '',
                'show_front' => isset($field['field_show_front']) ? $field['field_show_front'] : '',
                'front_position' => isset($field['field_position']) ? $field['field_position'] : '',
                'url' => isset($field['field_url']) ? $field['field_url'] : 'hide'
            );

            foreach ($meta_fields as $field) {
                $value = rwmb_meta($field, array(), $post_id);

                switch ($field) {
                    case 'cwpt_custom_tab_text_fields':
                        $field = 'cwpt_admin_tab_fields';

                        if (!empty($value) && is_array($value)) {
                            $new_value = array();
                            foreach ($value as $field) {
                                foreach ($field as $key => $val) {
                                    $new_key = strtolower(str_replace('field_', '', $key));

                                    if ($new_key == 'type') {
                                        $val = str_replace(' ', '_', strtolower($val));
                                    }

                                    $new_field[$new_key] = $val;
                                }
                                $new_value[] = $new_field;
                            }
                            update_post_meta($post_id, 'cwpt_admin_tab_fields', $new_value);
                        }
                        break;
                    case 'cwpt_enable_custom_tab':
                        $field = 'cwpt_enable_admin_fields';
                        $new_value = $value === 'Enabled' ? 'on' : '';
                        update_post_meta($post_id, 'cwpt_enable_admin_fields', $new_value);
                        break;

                    default:
                        if (!empty($value)) {
                            if ($value === 'Enabled' || $value === 'Show') {
                                $value = 'on';
                            } elseif ($value === 'Disabled' || $value === 'Hide') {
                                $value = '';
                            }
                            update_post_meta($post_id, $field, $value);
                        }
                        break;
                }
            }
        }
    }

    /**
     * Plugin activation hook
     * 
     * @return void
     */
    public static function install()
    {
        add_option('cwpt_activated', true);
        flush_rewrite_rules();
    }

    /**
     * Ensure WooCommerce gallery features are supported by the theme.
     *
     * @return void
     */
    public static function ensure_wc_gallery_support()
    {
        if (!function_exists('add_theme_support')) {
            return;
        }

        if (!current_theme_supports('wc-product-gallery-zoom')) {
            add_theme_support('wc-product-gallery-zoom');
        }
        if (!current_theme_supports('wc-product-gallery-lightbox')) {
            add_theme_support('wc-product-gallery-lightbox');
        }
        if (!current_theme_supports('wc-product-gallery-slider')) {
            add_theme_support('wc-product-gallery-slider');
        }
    }

    /**
     * Normalize front tab group data to ensure checkbox values persist.
     *
     * @param mixed $override
     * @param array $args
     * @param array $field_args
     * @param CMB2_Field $field
     * @return mixed
     */
    public static function normalize_front_tab_fields_save($override, $args, $field_args, $field)
    {
        if (empty($args['field_id']) || $args['field_id'] !== 'cwpt_front_tab_fields') {
            return $override;
        }
        if (empty($args['id']) || empty($args['type'])) {
            return $override;
        }
        if (!is_array($args['value'])) {
            return $override;
        }

        $value = $args['value'];
        foreach ($value as $index => $row) {
            if (!is_array($row)) {
                continue;
            }
            if (isset($row['type']) && $row['type'] === 'calendar') {
                $raw = $row['show_calendar_input'] ?? '';
                $value[$index]['show_calendar_input'] = in_array($raw, ['on', '1', 1, true], true) ? 'on' : 'off';
            }
        }

        return update_metadata($args['type'], $args['id'], $args['field_id'], $value);
    }
}