<?php

namespace CodeConfig\EAW\Pages;

use CodeConfig\EAW\Utils\Helpers;
use CodeConfig\EAW\Utils\Singleton;

defined('ABSPATH') || exit('No direct script access allowed');

class ProductPage
{
    use Singleton;

    protected $attr_taxonomies;
    protected $product_attr_type;


    public function doHooks()
    {
        add_action('woocommerce_init', [$this, 'onWooCommerceInit']);
    }

    private function isEnableProductVariations()
    {
        return Helpers::getSetting('pvEnable');
    }

    public function onWooCommerceInit()
    {
        if (!$this->isEnableProductVariations()) {
            return;
        }

        $this->attr_taxonomies = wc_get_attribute_taxonomies();

        foreach ($this->attr_taxonomies as $tax) {
            $this->registerAttributeHooks($tax);
        }

        $this->registerCommonHooks();
    }

    protected function registerAttributeHooks($tax)
    {
        $taxonomy                = "pa_{$tax->attribute_name}";
        $this->product_attr_type = $tax->attribute_type;

        add_action("{$taxonomy}_add_form_fields", [$this, 'addAttributeFields']);
        add_action("{$taxonomy}_edit_form_fields", [$this, 'editAttributeFields'], 10, 2);
        add_filter("manage_edit-{$taxonomy}_columns", [$this, 'addAttributeColumn']);
        add_filter("manage_{$taxonomy}_custom_column", [$this, 'addAttributeColumnContent'], 10, 3);
    }

    protected function registerCommonHooks()
    {
        add_filter('product_attributes_type_selector', [$this, 'addAttributeTypes']);
        add_action('created_term', [$this, 'saveTermMeta'], 10, 3);
        add_action('edit_term', [$this, 'saveTermMeta'], 10, 3);
        add_action('woocommerce_product_options_attributes', [$this, 'renderAttributePopups']);
        add_action('woocommerce_product_option_terms', [$this, 'renderProductOptionTerms'], 20, 2);
        add_filter('woocommerce_product_data_tabs', [$this, 'addSwatchesSettingsTab']);
        add_action('woocommerce_product_data_panels', [$this, 'renderSwatchesSettingsPanel']);
        add_action('woocommerce_process_product_meta', [$this, 'saveCustomFields'], 10, 2);
    }


    public function addAttributeTypes($types)
    {

        $more_types = [
            'color' => __('Color', 'essential-addons-for-woocommerce'),
            'image' => __('Image', 'essential-addons-for-woocommerce'),
            'label' => __('Button/Label', 'essential-addons-for-woocommerce'),
            'radio' => __('Radio', 'essential-addons-for-woocommerce'),
        ];

        $types = array_merge($types, $more_types);

        return $types;
    }


    public function addAttributeFields($taxonomy)
    {

        $attribute_type = $this->getAttributeType($taxonomy);
        $this->productAttributeFields($taxonomy, $attribute_type, 'new');
    }



    public function editAttributeFields($term, $taxonomy)
    {
        $attribute_type  = $this->getAttributeType($taxonomy);
        $term_fields     = [];
        $term_type_field = get_term_meta($term->term_id, "product_$taxonomy", true);

        $term_fields = [
            'term_type_field' => $term_type_field ?: '',
        ];
        $this->productAttributeFields($taxonomy, $attribute_type, $term_fields);
    }


    public function addAttributeColumn($columns)
    {
        $new_columns = [];

        if (isset($columns['cb'])) {
            $new_columns['cb'] = $columns['cb'];
            unset($columns['cb']);
        }

        $new_columns['thumb'] = '';

        $columns = array_merge($new_columns, $columns);

        return $columns;
    }

    public function addAttributeColumnContent($columns, $column, $term_id)
    {
        // Get and sanitize taxonomy from request
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is a display column callback, not a form submission
        $taxonomy = isset($_REQUEST['taxonomy']) ? sanitize_key(wp_unslash($_REQUEST['taxonomy'])) : '';

        $attr_type = $this->getAttributeType($taxonomy);

        $value = get_term_meta($term_id, "product_$taxonomy", true);

        switch ($attr_type) {
            case 'color':
                printf('<span class="th-term-color-preview" style="background-color:%s;"></span>', esc_attr($value));
                break;

            case 'image':
                $image = $value ? wp_get_attachment_image_src($value) : '';
                $image = $image ? $image[0] : '';
                printf('<img class="swatch-preview swatch-image" src="%s" width="44px" height="44px" alt="preview-image">', esc_url($image));
                break;

            case 'label':
                printf('<div class="swatch-preview swatch-label">%s</div>', esc_html($value));
                break;
        }
    }

    public function getAttributeType($taxonomy)
    {
        foreach ($this->attr_taxonomies as $tax) {
            if ("pa_{$tax->attribute_name}" == $taxonomy) {
                return $tax->attribute_type;
            }
        }
    }

    public function productAttributeFields($taxonomy, $type, $value)
    {
        $this->renderAttributeField($type, $value, $taxonomy);
    }

    private function renderAttributeField($type, $value, $taxonomy)
    {

        $data = [
            'label'    => ucfirst($type),
            'name'     => 'product_' . esc_attr($taxonomy),
            'taxonomy' => esc_attr($taxonomy),
            'value'    => is_array($value) && isset($value['term_type_field']) ? $value['term_type_field'] : $value,
        ];


        if ($type === 'image') {
            $image         = is_array($value) && !empty($value['term_type_field']) ? wp_get_attachment_image_src($value['term_type_field']) : '';
            $data['image'] = $image ? esc_url($image[0]) : CCPEAW_ASSETS . '/admin/images/product-variation/placeholder.svg';
        }

        ccpeaw_get_template("/products/{$type}", ['data' => $data], 'field');
    }

    public function saveTermMeta($term_id, $tt_id, $taxonomy)
    {
        // Verify nonce for term meta save
        if (!isset($_POST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'update-tag_' . $term_id)) {
            // Try alternative nonce for add term
            if (!isset($_POST['_wpnonce_add-tag']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce_add-tag'])), 'add-tag')) {
                return;
            }
        }

        // phpcs:disable WordPress.Security.NonceVerification.Missing -- Nonce verified above
        if (isset($_POST["product_$taxonomy"]) && !empty($_POST["product_$taxonomy"])) {
            $term_value = wc_clean(sanitize_text_field(wp_unslash($_POST["product_$taxonomy"])));
            update_term_meta($term_id, "product_$taxonomy", $term_value);
        }
        // phpcs:enable WordPress.Security.NonceVerification.Missing
    }


    public function renderAttributePopups()
    {

        $data = ['image' => CCPEAW_ASSETS . '/admin/images/product-variation/placeholder.svg'];
        ccpeaw_get_template("/products/attribute", ['data' => $data], 'popup');
    }


    public function renderProductOptionTerms($attribute_taxonomy, $i)
    {
        if ('select' !== $attribute_taxonomy->attribute_type) {
            global $thepostid;

            $taxonomy   = wc_attribute_taxonomy_name($attribute_taxonomy->attribute_name);
            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- This is a display callback, nonce verified by WooCommerce
            $product_id = is_null($thepostid) && isset($_POST['post_id']) ? absint(wp_unslash($_POST['post_id'])) : $thepostid;

            $args = apply_filters('woocommerce_product_attribute_terms', [
                'taxonomy'   => $taxonomy,
                'orderby'    => 'name',
                'hide_empty' => false,
            ]);

            $all_terms = get_terms($args);

            $data = [
                'taxonomy'           => $taxonomy,
                'attribute_taxonomy' => $attribute_taxonomy,
                'attribute_type'     => $attribute_taxonomy->attribute_type,
                'i'                  => $i,
                'product_id'         => $product_id,
                'all_terms'          => $all_terms,
            ];

            ccpeaw_get_template("/products/attribute", ['data' => $data], 'terms');
        }
    }


    public function addSwatchesSettingsTab($tabs)
    {
        $tabs['ccpeaw_swatches_settings']     = [
            'label'    => __('Swatches Settings', 'essential-addons-for-woocommerce'),
            'target'   => 'ccpeaw-product-attribute-settings',
            'class'    => ['variations_tab', 'show_if_variable',],
            'priority' => 65,
        ];

        return $tabs;
    }


    public function renderSwatchesSettingsPanel()
    {
        global $post, $thepostid, $product_object;

        $saved_settings = get_post_meta($thepostid, 'th_custom_attribute_settings', true);
        $type_options   = [
            'select' => __('Select', 'essential-addons-for-woocommerce'),
            'color'  => __('Color', 'essential-addons-for-woocommerce'),
            'label'  => __('Button/Label', 'essential-addons-for-woocommerce'),
            'image'  => __('Image', 'essential-addons-for-woocommerce'),
            'radio'  => __('Radio', 'essential-addons-for-woocommerce')
        ];



        $attributes = $product_object->get_attributes();
        $data       = [
            'saved_settings'      => $saved_settings,
            'type_options'        => $type_options,
            'attributes'          => $attributes,
            'thepostid'           => $thepostid,
            'controller'          => $this,
        ];

        ccpeaw_get_template("/products/custom-swatches", ['data' => $data], 'settings');
    }

    public function customAttributeSettingsField($attribute, $post_id)
    {
        $attribute_name = sanitize_title($attribute->get_name());
        $type           = $this->getCustomFieldsSettings($post_id, $attribute_name, 'type');

        $this->outputField('label', $type, $attribute, $post_id);
        $this->outputField('image', $type, $attribute, $post_id);
        $this->outputField('color', $type, $attribute, $post_id);
    }

    private function outputField($fieldType, $type, $attribute, $post_id)
    {
        $data = [
            'attribute'  => $attribute,
            'type'       => $type,
            'post_id'    => $post_id,
            'controller' => $this,
        ];

        ccpeaw_get_template("/products/output-{$fieldType}", ['data' => $data], 'field');
    }



    public function getCustomFieldsSettings($post_id, $attribute = false, $term = false, $term_key = false)
    {
        $saved_settings = get_post_meta($post_id, 'th_custom_attribute_settings', true);

        if (is_array($saved_settings)) {
            if ($attribute) {
                if (isset($saved_settings[$attribute])) {
                    $attr_settings = $saved_settings[$attribute];



                    if (is_array($attr_settings) && $term) {
                        if ($term === 'type' || $term === 'radio-type') {
                            $term_types =  (isset($attr_settings[$term])) ? $attr_settings[$term] : false;

                            return $term_types;
                        } else {
                            $term_settings = isset($attr_settings[$term]) ? $attr_settings[$term] : '';
                            if (is_array($term_settings) && $term_key) {
                                $settings_value = isset($term_settings[$term_key]) ? $term_settings[$term_key] : '';

                                return  $settings_value;
                            } else {
                                return false;
                            }
                        }
                    }

                    return $attr_settings;
                }

                return false;
            }

            return $saved_settings;
        } else {
            return false;
        }
    }

    public function saveCustomFields($post_id, $post)
    {
        // Verify nonce
        if (!isset($_POST['woocommerce_meta_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['woocommerce_meta_nonce'])), 'woocommerce_save_data')) {
            return;
        }

        $product             = wc_get_product($post_id);
        $local_attr_settings = [];

        foreach ($product->get_attributes() as $attribute) {

            if ($attribute->is_taxonomy() == false) {

                $attr_settings         = [];
                $attr_name             = sanitize_title($attribute->get_name());
                $type_key              = "th_attribute_type_$attr_name";
                // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified above
                $attr_settings['type'] = isset($_POST[$type_key]) ? sanitize_text_field(wp_unslash($_POST[$type_key])) : '';

                if ($attr_settings['type'] == 'radio') {
                    $radio_style_key             = sanitize_title("{$attr_name}_radio_button_style");
                    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified above
                    $attr_settings['radio-type'] = isset($_POST[$radio_style_key]) ? sanitize_text_field(wp_unslash($_POST[$radio_style_key])) : '';
                } else {
                    $term_settings = [];
                    foreach ($attribute->get_options() as $term) {
                        $term_settings['name'] = $term;

                        if ($attr_settings['type'] == 'color') {
                            $color_type_key              = sanitize_title($attr_name . '_color_type_' . $term);
                            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified above
                            $term_settings['color_type'] = isset($_POST[$color_type_key]) ? sanitize_text_field(wp_unslash($_POST[$color_type_key])) : '';
                        }

                        $term_key                    = sanitize_title($attr_settings['type'] . '_' . $attr_name . '_term_' . $term);
                        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified above
                        $term_settings['term_value'] = isset($_POST[$term_key]) ? sanitize_text_field(wp_unslash($_POST[$term_key])) : '';
                        $attr_settings[$term]        = $term_settings;
                    }
                }

                $local_attr_settings[$attr_name] = $attr_settings;
            }
        }

        update_post_meta($post_id, 'th_custom_attribute_settings', $local_attr_settings);
    }
}
