<?php

namespace DEVELUXSCT\BulkManager;
if (!defined('ABSPATH')) {
    exit;
}

use DEVELUXSCT\HTMLGenerators\SearchProduct;
use DEVELUXSCT\HTMLGenerators\TemplateRenderer;

class Bulk
{
    public function __construct()
    {
        add_action('wp_ajax_develuxsct_search_product', [$this, 'search_product']);
        add_action('wp_ajax_develuxsct_save_tags', [$this, 'save_tags']);
        add_action('wp_ajax_develuxsct_save_categories', [$this, 'save_categories']);
        add_action('wp_ajax_develuxsct_append_product_to_list', [$this, 'append_product_to_list']);
        add_action('wp_ajax_develuxsct_update_included_products', [$this, 'update_included_products']);
        $this->global_relations_update();
    }

    public function global_relations_update(): void
    {
        //Update custom blocks
        $all_custom_blocks = get_posts([
            'post_type' => 'develux_custom_block'
        ]);
        if (!empty($all_custom_blocks)) {
            foreach ($all_custom_blocks as $blocks) {
                self::update_product_ids($blocks->ID);
            }
        }
    }

    public function search_product(): void
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'search_product')) {
            wp_send_json_error('Invalid nonce');
        }

        $develuxsct_allowed_html = TemplateRenderer::get_allowed_html();

        $all_product_ids = isset($_POST['all_product_ids']) ?  sanitize_text_field(wp_unslash($_POST['all_product_ids'])) : '';
        $action_type = isset($_POST['action_type']) ? sanitize_text_field(wp_unslash($_POST['action_type'])) : '';
        $search_request = isset($_POST['search_request']) ? sanitize_text_field(wp_unslash($_POST['search_request'])) : '';
        echo wp_kses(SearchProduct::search_result($search_request, $all_product_ids, $action_type), $develuxsct_allowed_html);
        wp_die();
    }

    public function save_tags(): void
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'save_tags')) {
            wp_send_json_error('Invalid nonce');
        }
        $tag_list = isset($_POST['tag_list']) ?  sanitize_text_field(wp_unslash($_POST['tag_list'])) : '';
        $label_id = isset($_POST['label_id']) ? sanitize_text_field(wp_unslash($_POST['label_id'])) : '';
        update_post_meta($label_id, 'develux_bulk_item_tag_ids', $tag_list);
        self::update_product_ids($label_id);
        wp_die();
    }

    public function save_categories(): void
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'save_categories')) {
            wp_send_json_error('Invalid nonce');
        }
        $cat_list = isset($_POST['cat_list']) ? sanitize_text_field(wp_unslash($_POST['cat_list'])) : '';
        $label_id = isset($_POST['label_id']) ? sanitize_text_field(wp_unslash($_POST['label_id'])) : '';
        update_post_meta($label_id, 'develux_bulk_item_cat_ids', $cat_list);
        self::update_product_ids($label_id);
        wp_die();
    }

    public function append_product_to_list(): void
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'append_product_to_list')) {
            wp_send_json_error('Invalid nonce');
        }
        $develuxsct_allowed_html = TemplateRenderer::get_allowed_html();
        $action_type = isset($_POST['action_type']) ? sanitize_text_field(wp_unslash($_POST['action_type'])) :'';
        $product_id = isset($_POST['product_id']) ? sanitize_text_field(wp_unslash($_POST['product_id'])) : '';
        $label_id = isset($_POST['label_id']) ? sanitize_text_field(wp_unslash($_POST['label_id'])) : "";
        $all_product_ids = isset($_POST['all_product_ids']) ? sanitize_text_field(wp_unslash($_POST['all_product_ids'])) : "";

        if ($action_type === 'include') {
            update_post_meta($label_id, 'develux_bulk_item_prod_included_ids', $all_product_ids);
        } elseif ($action_type === 'exclude') {
            update_post_meta($label_id, 'develux_bulk_item_prod_excluded_ids', $all_product_ids);
        }
        self::update_product_ids($label_id);

        echo wp_kses(SearchProduct::search_product($product_id), $develuxsct_allowed_html);

        wp_die();
    }

    public static function get_included_products($label_id): array
    {
        $product_ids = get_post_meta($label_id, 'develux_bulk_item_prod_included_ids', true);
        $product_ids_arr = explode(',', $product_ids);

        $products = get_posts([
            'post_type' => 'product',
            'include' => $product_ids_arr
        ]);
        return $products;
    }

    public static function get_excluded_products($label_id): array
    {
        $product_ids = get_post_meta($label_id, 'develux_bulk_item_prod_excluded_ids', true);
        $product_ids_arr = explode(',', $product_ids);

        $products = get_posts([
            'post_type' => 'product',
            'include' => $product_ids_arr
        ]);
        return $products;
    }

    public function update_included_products(): void
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'update_included_products')) {
            wp_send_json_error('Invalid nonce');
        }
        $action_type = isset($_POST['action_type']) ? sanitize_text_field(wp_unslash($_POST['action_type'])) : '';
        $label_id = isset($_POST['label_id']) ? sanitize_text_field(wp_unslash($_POST['label_id'])) : '';
        $all_product_ids = isset($_POST['all_product_ids']) ? sanitize_text_field(wp_unslash($_POST['all_product_ids'])) : '';
        if ($action_type === 'include') {
            update_post_meta($label_id, 'develux_bulk_item_prod_included_ids', $all_product_ids);
        } elseif ($action_type === 'exclude') {
            update_post_meta($label_id, 'develux_bulk_item_prod_excluded_ids', $all_product_ids);
        }
        self::update_product_ids($label_id);
        wp_die();
    }

    public static function update_product_ids($label_id): void
    {
        $all_product_ids = [];

        $product_included_ids = get_post_meta($label_id, 'develux_bulk_item_prod_included_ids', true);
        if (!empty($product_included_ids)) {
            foreach (explode(',', $product_included_ids) as $id) {
                $all_product_ids[$id] = $id;
            }
        }

        $tags_ids = get_post_meta($label_id, 'develux_bulk_item_tag_ids', true);
        if (!empty($tags_ids)) {
            foreach (explode(',', $tags_ids) as $category_id) {
                // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
                $products_ids_tag = get_posts(
                    [
                        'post_type' => 'product',
                        'numberposts' => -1,
                        'fields' => 'ids',
                        // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
                        'tax_query' => [
                            [
                                'taxonomy' => 'product_tag',
                                'field' => 'id',
                                'terms' => $category_id,
                                'include_children' => false
                            ],
                        ],
                    ]
                );
                foreach ($products_ids_tag as $id) {
                    $all_product_ids[$id] = $id;
                }
            }
        }

        $categories_ids = get_post_meta($label_id, 'develux_bulk_item_cat_ids', true);
        if (!empty($categories_ids)) {
            foreach (explode(',', $categories_ids) as $category_id) {
                // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
                $products_ids_cat = get_posts(
                    [
                        'post_type' => 'product',
                        'numberposts' => -1,
                        'fields' => 'ids',
                        // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
                        'tax_query' => [
                            [
                                'taxonomy' => 'product_cat',
                                'field' => 'id',
                                'terms' => $category_id,
                                'include_children' => false
                            ],
                        ],
                    ]
                );
                foreach ($products_ids_cat as $id) {
                    $all_product_ids[$id] = $id;
                }
            }
        }


        $product_excluded_ids = get_post_meta($label_id, 'develux_bulk_item_prod_excluded_ids', true);
        if (!empty($product_excluded_ids)) {
            $product_excluded_ids_arr = explode(',', $product_excluded_ids);
            foreach ($product_excluded_ids_arr as $id) {
                if (in_array($id, $product_excluded_ids_arr, true)) {
                    unset($all_product_ids[$id]);
                }
            }
        }

        update_post_meta($label_id, 'develux_bulk_item_all_products_ids', implode(',', $all_product_ids));
    }
}