<?php

namespace iwbvel\classes\requests;

defined('ABSPATH') || exit(); // Exit if accessed directly

use iwbvel\classes\helpers\Meta_Field as Meta_Field_Helper;
use iwbvel\classes\helpers\Sanitizer;
use iwbvel\classes\repositories\flush_message\Flush_Message;
use iwbvel\classes\repositories\meta_field\ACF_Plugin_Fields;
use iwbvel\classes\repositories\Column;
use iwbvel\classes\repositories\History;
use iwbvel\classes\repositories\Meta_Field;
use iwbvel\classes\repositories\Setting;
use iwbvel\classes\services\export\Export_Service;
use iwbvel\classes\services\history\HistoryUndoService;

class Post_Handler
{
    private static $instance;

    public static function register_callback()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    private function __construct()
    {
        add_action('admin_post_iwbvel_column_manager_new_preset', [$this, 'column_manager_new_preset']);
        add_action('admin_post_iwbvel_column_manager_edit_preset', [$this, 'column_manager_edit_preset']);
        add_action('admin_post_iwbvel_column_manager_delete_preset', [$this, 'column_manager_delete_preset']);
        add_action('admin_post_iwbvel_load_column_profile', [$this, 'load_column_profile']);
        add_action('admin_post_iwbvel_settings', [$this, 'settings']);
        add_action('admin_post_iwbvel_export_products', [$this, 'export_products']);
        add_action('admin_post_iwbvel_save_column_profile', [$this, 'save_column_profile']);
    }

    public function meta_fields()
    {
        if (!isset($_REQUEST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'])), 'iwbvel_post_nonce')) {
            die('403 Forbidden');
        }

        $meta_field_repository = Meta_Field::get_instance();
        $reserved_keys = $meta_field_repository->get_reserved_field_names();

        $meta_fields = [];
        $acf = ACF_Plugin_Fields::get_instance('product');
        $acf_fields = $acf->get_fields();
        if (isset($_POST['save_meta_fields']) && !empty($_POST['meta_field_key']) && is_array($_POST['meta_field_key'])) {
            for ($i = 0; $i < count($_POST['meta_field_key']); $i++) {
                if (!empty($_POST['meta_field_key'][$i])) {
                    $meta_field_key = strtolower(str_replace(' ', '_', sanitize_text_field(wp_unslash($_POST['meta_field_key'][$i]))));
                    if (in_array($meta_field_key, $reserved_keys)) {
                        continue;
                    }
                    if (!empty($acf_fields) && is_array($acf_fields) && array_key_exists($meta_field_key, $acf_fields)) {
                        $type = Meta_Field_Helper::get_field_type_by_acf_type($acf_fields[$meta_field_key]);
                        $main_type = (isset($type['main_type'])) ? $type['main_type'] : '';
                        $sub_type = isset($type['sub_type']) ? $type['sub_type'] : '';
                        $key_value = '';
                    } else {
                        $main_type = (!empty($_POST['meta_field_main_type'][$i])) ? sanitize_text_field(wp_unslash($_POST['meta_field_main_type'][$i])) : '';
                        $sub_type = (!empty($_POST['meta_field_sub_type'][$i])) ? sanitize_text_field(wp_unslash($_POST['meta_field_sub_type'][$i])) : '';
                        $key_value = (!empty($_POST['meta_field_key_value'][$i])) ? sanitize_text_field(wp_unslash($_POST['meta_field_key_value'][$i])) : '';
                    }

                    $meta_fields[sanitize_text_field(wp_unslash($meta_field_key))] = [
                        "key" => sanitize_text_field(wp_unslash($meta_field_key)),
                        "title" => (!empty($_POST['meta_field_title'][$i])) ? sanitize_text_field(wp_unslash($_POST['meta_field_title'][$i])) : sanitize_text_field(wp_unslash($meta_field_key)),
                        "main_type" => $main_type,
                        "sub_type" => $sub_type,
                        "key_value" => $key_value,
                    ];
                }
            }
        }

        $meta_field_repository->update($meta_fields);
        $column_repository = Column::get_instance();
        $column_repository->update_meta_field_items();
        $column_repository->set_columns();

        $active_column = $column_repository->get_active_columns();
        $fields = $column_repository->get_columns();
        $columns = [];
        if (!empty($active_column['fields'])) {
            foreach ($active_column['fields'] as $key => $column) {
                if (!isset($fields[$key])) {
                    continue;
                }

                $column['name'] = $fields[$key]['name'];
                $column['label'] = $fields[$key]['label'];
                $column['title'] = $fields[$key]['label'];
                $column['content_type'] = $fields[$key]['content_type'];
                if (isset($fields[$key]['fetch_type'])) {
                    $column['fetch_type'] = $fields[$key]['fetch_type'];
                }
                if (isset($fields[$key]['update_type'])) {
                    $column['update_type'] = $fields[$key]['update_type'];
                }
                if (isset($fields[$key]) && isset($fields[$key]['options'])) {
                    $column['options'] = $fields[$key]['options'];
                }

                $columns[$key] = $column;
            }
            $column_repository->set_active_columns($column_repository->get_active_columns()['name'], $columns);
        }

        $this->redirect([
            'message' => esc_html__('Success !', 'ithemeland-bulk-variation-editing-for-woocommerce'),
            'type' => 'success',
        ]);
    }

    public function column_manager_new_preset()
    {
        if (!isset($_REQUEST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'])), 'iwbvel_post_nonce')) {
            die('403 Forbidden');
        }

        if (isset($_POST['save_preset']) && !empty($_POST['field_name']) && is_array($_POST['field_name']) && !empty($_POST['preset_name'])) {
            $column_repository = Column::get_instance();
            $fields = $column_repository->get_columns();
            if (!empty($fields)) {
                $preset['name'] = sanitize_text_field(wp_unslash($_POST['preset_name']));
                $preset['date_modified'] = gmdate('Y-m-d H:i:s', time());
                $preset['key'] = 'preset-' . wp_rand(1000000, 9999999);
                if (!empty($_POST['field_name']) && is_array($_POST['field_name'])) {
                    for ($i = 0; $i < count($_POST['field_name']); $i++) {
                        if (!empty($_POST['field_name'][$i])) {
                            $field_name = sanitize_text_field(wp_unslash($_POST['field_name'][$i]));
                            if (isset($fields[$field_name])) {
                                $preset["fields"][$field_name] = [
                                    'name' => $field_name,
                                    'label' => (!empty($_POST['field_label'][$i])) ? sanitize_text_field(wp_unslash($_POST['field_label'][$i])) : $field_name,
                                    'title' => (!empty($_POST['field_title'][$i])) ? sanitize_text_field(wp_unslash($_POST['field_title'][$i])) : $field_name,
                                    'editable' => $fields[$field_name]['editable'],
                                    'content_type' => $fields[$field_name]['content_type'],
                                    'allowed_type' => $fields[$field_name]['allowed_type'],
                                    'update_type' => $fields[$field_name]['update_type'],
                                    'fetch_type' => $fields[$field_name]['fetch_type'],
                                    'background_color' => (!empty($_POST['field_background_color'][$i])) ? sanitize_text_field(wp_unslash($_POST['field_background_color'][$i])) : '',
                                    'text_color' => (!empty($_POST['field_text_color'][$i])) ? sanitize_text_field(wp_unslash($_POST['field_text_color'][$i])) : '',
                                ];
                                if (isset($fields[$field_name]['field_type'])) {
                                    $preset["fields"][$field_name]['field_type'] = $fields[$field_name]['field_type'];
                                }
                                if (isset($fields[$field_name]['sub_name'])) {
                                    $preset["fields"][$field_name]['sub_name'] = $fields[$field_name]['sub_name'];
                                }
                                if (isset($fields[$field_name]['sortable'])) {
                                    $preset["fields"][$field_name]['sortable'] = $fields[$field_name]['sortable'];
                                }
                                if (isset($fields[$field_name]['options'])) {
                                    $preset["fields"][$field_name]['options'] = $fields[$field_name]['options'];
                                }
                                $preset['checked'][] = $field_name;
                            }
                        }
                    }
                    $column_repository->update($preset);
                }
            }
        }
        $this->redirect([
            'message' => esc_html__('Success !', 'ithemeland-bulk-variation-editing-for-woocommerce'),
            'type' => 'success'
        ]);
    }

    public function column_manager_edit_preset()
    {
        if (!isset($_REQUEST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'])), 'iwbvel_post_nonce')) {
            die('403 Forbidden');
        }

        if (isset($_POST['edit_preset']) && !empty($_POST['preset_key']) && !empty($_POST['preset_name'])) {
            $column_repository = Column::get_instance();
            $fields = $column_repository->get_columns();
            if (!empty($fields)) {
                $preset["fields"] = [];
                $preset['name'] = sanitize_text_field(wp_unslash($_POST['preset_name']));
                $preset['date_modified'] = gmdate('Y-m-d H:i:s', time());
                $preset['key'] = sanitize_text_field(wp_unslash($_POST['preset_key']));
                if (!empty($_POST['field_name']) && is_array($_POST['field_name'])) {
                    for ($i = 0; $i < count($_POST['field_name']); $i++) {
                        if (!empty($_POST['field_name'][$i])) {
                            $field_name = sanitize_text_field(wp_unslash($_POST['field_name'][$i]));
                            if (isset($fields[$field_name])) {
                                $preset["fields"][$field_name] = [
                                    'name' => $field_name,
                                    'label' => (!empty($_POST['field_label'][$i])) ? sanitize_text_field(wp_unslash($_POST['field_label'][$i])) : $field_name,
                                    'title' => (!empty($_POST['field_title'][$i])) ? sanitize_text_field(wp_unslash($_POST['field_title'][$i])) : $field_name,
                                    'editable' => $fields[$field_name]['editable'],
                                    'content_type' => $fields[$field_name]['content_type'],
                                    'allowed_type' => $fields[$field_name]['allowed_type'],
                                    'update_type' => $fields[$field_name]['update_type'],
                                    'fetch_type' => $fields[$field_name]['fetch_type'],
                                    'background_color' => (!empty($_POST['field_background_color'][$i])) ? sanitize_text_field(wp_unslash($_POST['field_background_color'][$i])) : '',
                                    'text_color' => (!empty($_POST['field_text_color'][$i])) ? sanitize_text_field(wp_unslash($_POST['field_text_color'][$i])) : '',
                                ];
                                if (isset($fields[$field_name]['sortable'])) {
                                    $preset["fields"][$field_name]['sortable'] = $fields[$field_name]['sortable'];
                                }
                                if (isset($fields[$field_name]['sub_name'])) {
                                    $preset["fields"][$field_name]['sub_name'] = $fields[$field_name]['sub_name'];
                                }
                                if (isset($fields[$field_name]['options'])) {
                                    $preset["fields"][$field_name]['options'] = $fields[$field_name]['options'];
                                }
                                if (isset($fields[$field_name]['field_type'])) {
                                    $preset["fields"][$field_name]['field_type'] = $fields[$field_name]['field_type'];
                                }
                                $preset['checked'][] = $field_name;
                            }
                        }
                    }
                    $column_repository->update($preset);
                    $column_repository->set_active_columns($preset['key'], $preset['fields']);
                }
            }
        }
        $this->redirect([
            'message' => esc_html__('Success !', 'ithemeland-bulk-variation-editing-for-woocommerce'),
            'type' => 'success'
        ]);
    }

    public function column_manager_delete_preset()
    {
        if (!isset($_REQUEST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'])), 'iwbvel_post_nonce')) {
            die('403 Forbidden');
        }

        $column_repository = Column::get_instance();
        if (isset($_POST['delete_key'])) {
            if ($column_repository->get_active_columns()['name'] == $_POST['delete_key']) {
                $column_repository->delete_active_columns();
            }
            $column_repository->delete(sanitize_text_field(wp_unslash($_POST['delete_key'])));
        }

        $this->redirect([
            'message' => esc_html__('Success !', 'ithemeland-bulk-variation-editing-for-woocommerce'),
            'type' => 'success'
        ]);
    }

    public function load_column_profile()
    {
        if (!isset($_REQUEST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'])), 'iwbvel_post_nonce')) {
            die('403 Forbidden');
        }

        if (isset($_POST['preset_key'])) {
            $preset_key = sanitize_text_field(wp_unslash($_POST['preset_key']));
            $checked_columns = is_array($_POST["columns"]) ? Sanitizer::array($_POST["columns"]) : sanitize_text_field(wp_unslash($_POST["columns"])); //phpcs:ignore
            if (!empty($checked_columns) && is_array($checked_columns)) {
                $checked_columns = array_combine($checked_columns, $checked_columns);
                $column_repository = Column::get_instance();
                $columns = [];
                $fields = $column_repository->get_columns();
                $preset_columns = $column_repository->get_preset($preset_key);
                if (!empty($checked_columns) && is_array($checked_columns)) {
                    if (!empty($preset_columns['fields'])) {
                        foreach ($preset_columns['fields'] as $column_key => $preset_column) {
                            if (isset($checked_columns[$column_key])) {
                                $columns[$column_key] = $fields[$column_key];
                                $columns[$column_key]['title'] = (isset($fields[$column_key]['label'])) ? $fields[$column_key]['label'] : $column_key;
                                unset($checked_columns[$column_key]);
                            }
                        }
                    }
                    if (!empty($checked_columns)) {
                        foreach ($checked_columns as $diff_item) {
                            if (isset($fields[$diff_item])) {
                                $checked_column = [
                                    'name' => $fields[$diff_item]['name'],
                                    'label' => $fields[$diff_item]['label'],
                                    'title' => $fields[$diff_item]['label'],
                                    'editable' => $fields[$diff_item]['editable'],
                                    'content_type' => $fields[$diff_item]['content_type'],
                                    'allowed_type' => $fields[$diff_item]['allowed_type'],
                                    'update_type' => $fields[$diff_item]['update_type'],
                                    'fetch_type' => $fields[$diff_item]['fetch_type'],
                                    'background_color' => '#fff',
                                    'text_color' => '#444',
                                ];
                                if (isset($fields[$diff_item]['sortable'])) {
                                    $checked_column['sortable'] = ($fields[$diff_item]['sortable']);
                                }
                                if (isset($fields[$diff_item]['sub_name'])) {
                                    $checked_column['sub_name'] = ($fields[$diff_item]['sub_name']);
                                }
                                if (isset($fields[$diff_item]['options'])) {
                                    $checked_column['options'] = $fields[$diff_item]['options'];
                                }
                                if (isset($fields[$diff_item]['field_type'])) {
                                    $checked_column['field_type'] = $fields[$diff_item]['field_type'];
                                }
                                $columns[$diff_item] = $checked_column;
                            }
                        }
                    }
                }
                $column_repository->set_active_columns($preset_key, $columns);
            }
        }

        $this->redirect();
    }

    public function history_action()
    {
        if (!isset($_REQUEST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'])), 'iwbvel_post_nonce')) {
            die('403 Forbidden');
        }

        if (isset($_POST['delete'])) {
            $history_repository = History::get_instance();
            $history_repository->delete_history(intval($_POST['delete']));
            $this->redirect([
                'message' => esc_html__('Success !', 'ithemeland-bulk-variation-editing-for-woocommerce'),
                'type' => 'success'
            ]);
        }

        if (isset($_POST['revert'])) {
            $history_undo_service = new HistoryUndoService();
            $history_undo_service->set_data(['history_id' => intval($_POST['revert'])]);
            $history_undo_service->perform();

            if (!$history_undo_service->is_processing()) {
                $this->redirect([
                    'type' => 'success',
                    'message' => esc_html__('Success !', 'ithemeland-bulk-variation-editing-for-woocommerce'),
                ]);
            } else {
                $this->redirect();
            }
        }

        return false;
    }

    public function clear_all_history()
    {
        if (!isset($_REQUEST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'])), 'iwbvel_post_nonce')) {
            die('403 Forbidden');
        }

        $history_repository = History::get_instance();
        $history_repository->clear_all();
        $this->redirect([
            'message' => esc_html__('Success !', 'ithemeland-bulk-variation-editing-for-woocommerce'),
            'type' => 'success'
        ]);

        return false;
    }

    public function settings()
    {
        if (!isset($_REQUEST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'])), 'iwbvel_post_nonce')) {
            die('403 Forbidden');
        }

        if (isset($_POST['settings'])) {
            $setting_repository = Setting::get_instance();
            $setting_repository->update(Sanitizer::array($_POST['settings'])); //phpcs:ignore
        }

        $this->redirect([
            'message' => esc_html__('Success !', 'ithemeland-bulk-variation-editing-for-woocommerce'),
            'type' => 'success'
        ]);
    }

    public function export_products()
    {
        if (!isset($_REQUEST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'])), 'iwbvel_post_nonce')) {
            die('403 Forbidden');
        }

        if (empty($_POST['products']) || empty($_POST['fields'])) {
            $this->redirect([
                'message' => esc_html__('Error ! try again', 'ithemeland-bulk-variation-editing-for-woocommerce'),
                'type' => 'danger'
            ]);
        }

        $export_service = Export_Service::get_instance();
        $export_service->set_data([
            'delimiter' => (!empty($_POST['iwbvel_export_delimiter'])) ? sanitize_text_field(wp_unslash($_POST['iwbvel_export_delimiter'])) : '',
            'select_type' => sanitize_text_field(wp_unslash($_POST['products'])),
            'field_type' => sanitize_text_field(wp_unslash($_POST['fields'])),
            'selected_ids' => isset($_POST['item_ids']) ? Sanitizer::array($_POST['item_ids']) : [], //phpcs:ignore
        ]);
        $export_service->perform();

        $this->redirect();
    }

    private function redirect($notice = [], $page = 'main')
    {
        if (!empty($notice) && isset($notice['message'])) {
            $flush_message_repository = new Flush_Message();
            $flush_message_repository->set($notice);
        }
        wp_safe_redirect(IWBVEL_PLUGIN_MAIN_PAGE);
        die();
    }
}
