<?php

namespace iwbvel\classes\bootstrap;

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

use iwbvel\classes\controllers\IWBVEL_Bulk_Variations;
use iwbvel\classes\helpers\LangHelper;
use iwbvel\classes\requests\Ajax_Handler;
use iwbvel\classes\requests\Post_Handler;
use iwbvel\classes\helpers\Render;
use iwbvel\classes\helpers\Sanitizer;
use iwbvel\classes\repositories\Column;
use iwbvel\classes\repositories\Meta_Field;
use iwbvel\classes\repositories\Search;
use iwbvel\classes\repositories\Setting;
use iwbvel\classes\services\background_process\VariationBackgroundProcess;
use iwbvel\classes\services\history\HistoryRedoService;
use iwbvel\classes\services\history\HistoryUndoService;
use iwbvel\classes\services\product_delete\ProductDeleteService;
use iwbvel\classes\services\product_duplicate\ProductDuplicateService;
use iwbvel\classes\services\scheduler\Variation_Scheduler;
use iwbvel\framework\analytics\AnalyticsTracker;
use iwbvel\framework\onboarding\Onboarding;

class IWBVEL
{
    private static $instance;
    private static $is_initable;

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

    private function __construct()
    {
        if (!current_user_can('manage_woocommerce')) {
            return;
        }

        AnalyticsTracker::register();
        Onboarding::register();

        Ajax_Handler::register_callback();
        Post_Handler::register_callback();
        IWBVEL_Meta_Fields::init();

        add_filter('safe_style_css', function ($styles) {
            $styles[] = 'display';
            return $styles;
        });

        if (is_admin()) {
            add_action('admin_menu', [$this, 'add_menu']);
            add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);
        }
    }

    public function add_menu()
    {
        if (!defined('IWBVE_NAME') && !defined('WBEB_NAME')) {
            if (defined('WBEBL_NAME')) {
                add_submenu_page('wbebl', esc_html__('VBULKiT', 'ithemeland-bulk-variation-editing-for-woocommerce'), esc_html__('VBULKiT', 'ithemeland-bulk-variation-editing-for-woocommerce'), 'manage_woocommerce', 'iwbve', [new IWBVEL_Bulk_Variations(), 'index'], 1);
            } else {
                add_menu_page(esc_html__('VBULKiT', 'ithemeland-bulk-variation-editing-for-woocommerce'), wp_kses('VBULK<span style="color: #627ddd;font-weight: 900;">iT</span>', Sanitizer::allowed_html()), 'manage_woocommerce', 'iwbve', [new IWBVEL_Bulk_Variations(), 'index'], IWBVEL_IMAGES_URL . 'vbulkit-icon-wh20.svg', 59);
            }
        }
    }

    public static function woocommerce_required()
    {
        include IWBVEL_VIEWS_DIR . 'alerts/iwbvel_woocommerce_required.php';
    }

    public function add_admin_scripts($hook)
    {
        global $post;
        if ($hook == 'post-new.php' || $hook == 'post.php') {
            if ('product' === $post->post_type) {

                ob_start();
                include IWBVEL_VIEWS_DIR . 'product_edit/variations_tab_header.php';
                $variationHeader = ob_get_clean();

                wp_enqueue_script('iwbvel-product-edit', IWBVEL_JS_URL . 'product-edit-page.js', ['jquery'], IWBVEL_VERSION); //phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter 
                wp_localize_script('iwbvel-product-edit', 'iwbvelProductEditHtml', [
                    'variationsTabHeader' => $variationHeader
                ]);
            }
        }
    }

    // "Go Pro" page callback
    public function go_pro_page()
    {
        include_once IWBVEL_VIEWS_DIR . 'go_pro/go_pro.php';
        if (!empty($_GET['page']) && $_GET['page'] == 'iwbvel_go_pro') { //phpcs:ignore WordPress.Security.NonceVerification.Recommended 
            wp_enqueue_style('iwbvel-go-pro', IWBVEL_URL . 'views/go_pro/assets/css/style.css', [], IWBVEL_VERSION);
            wp_enqueue_style('iwbvel-main', IWBVEL_CSS_URL . 'style-core.css', [], IWBVEL_VERSION);
        }
    }

    // "Other Plugins" page callback
    public function other_plugins_page()
    {
        include_once IWBVEL_VIEWS_DIR . 'go_pro/other_plugins/other_plugins.php';
        if (!empty($_GET['page']) && $_GET['page'] == 'iwbvel_other_plugins') { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
            wp_enqueue_style('iwbvel-go-pro', IWBVEL_URL . 'views/go_pro/assets/css/style.css', [], IWBVEL_VERSION);
            wp_enqueue_style('iwbvel-main', IWBVEL_CSS_URL . 'style-core.css', [], IWBVEL_VERSION);
        }
    }


    private function reset_filter_data()
    {
        $reset_version = '1.0.0';
        $last_reset = get_option('iwbvel_reset_filter_data_version', null);

        if (empty($last_reset) || version_compare($last_reset, $reset_version, '<')) {
            $search_repository = Search::get_instance();
            $search_repository->update_current_data([
                'last_filter_data' => [],
            ]);

            update_option('iwbvel_reset_filter_data_version', $reset_version);
        }
    }

    public static function iwbvel_wp_init()
    {
        if (!self::is_initable()) {
            return false;
        }

        $version = get_option('iwbvel-version', '');
        if (empty($version) || $version != IWBVEL_VERSION) {
            self::create_tables();
            self::update_table();
            $column_repository = Column::get_instance();
            $column_repository->set_default_columns();
            $column_repository->sync_active_columns();
            update_option('iwbvel-version', IWBVEL_VERSION);
        }

        IWBVEL_Custom_Queries::init();
        VariationBackgroundProcess::init();
        if (!defined('DISABLE_WP_CRON') || (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON === false)) {
            Variation_Scheduler::init();
        }

        // load textdomain
        // load_plugin_textdomain('ithemeland-bulk-variation-editing-for-woocommerce', false, IWBVEL_LANGUAGES_DIR);
    }

    public function enqueue_scripts($page)
    {
        if (!empty($_GET['page']) && $_GET['page'] == 'iwbve') { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
            if (defined('WBEBL_NAME')) {
                if (\wbebl\framework\onboarding\Onboarding::is_completed()) {
                    $this->main_enqueue_scripts();
                } else {
                    $this->onboarding_enqueue_scripts();
                }
            } else {
                if (Onboarding::is_completed()) {
                    $this->main_enqueue_scripts();
                } else {
                    $this->onboarding_enqueue_scripts();
                }
            }
        }
    }

    private function main_enqueue_scripts()
    {
        if (!empty($_GET['page']) && $_GET['page'] == 'iwbve') { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $setting_repository = Setting::get_instance();
            $meta_field_repository = Meta_Field::get_instance();
            $search_repository = Search::get_instance();

            // Styles
            wp_enqueue_style('iwbvel-reset', IWBVEL_CSS_URL . 'reset.css', [], IWBVEL_VERSION);
            wp_enqueue_style('iwbvel-icomoon', IWBVEL_CSS_URL . 'icomoon.css', [], IWBVEL_VERSION);
            wp_enqueue_style('iwbvel-datepicker', IWBVEL_CSS_URL . 'bootstrap-material-datetimepicker.css', [], IWBVEL_VERSION);
            wp_enqueue_style('iwbvel-select2', IWBVEL_CSS_URL . 'select2.css', [], IWBVEL_VERSION);
            wp_enqueue_style('iwbvel-sweetalert', IWBVEL_CSS_URL . 'sweetalert.css', [], IWBVEL_VERSION);
            wp_enqueue_style('iwbvel-jquery-ui', IWBVEL_CSS_URL . 'jquery-ui.css', [], IWBVEL_VERSION);
            wp_enqueue_style('iwbvel-tipsy', IWBVEL_CSS_URL . 'jquery.tipsy.css', [], IWBVEL_VERSION);
            wp_enqueue_style('iwbvel-datetimepicker', IWBVEL_CSS_URL . 'jquery.datetimepicker.css', [], IWBVEL_VERSION);
            wp_enqueue_style('iwbvel-main', IWBVEL_CSS_URL . 'style.css', [], IWBVEL_VERSION);
            wp_enqueue_style('iwbvel-variations', IWBVEL_CSS_URL . 'variations.css', [], IWBVEL_VERSION);
            wp_enqueue_style('wp-color-picker');

            // "yith badge management" plugin
            if (class_exists('YITH_WCBM_Frontend')) {
                $yith_frontend = \YITH_WCBM_Frontend::get_instance();
                $yith_frontend->enqueue_scripts();
            }

            // "yith badge management" plugin
            if (function_exists('iThemeland_WooCommerce_Advanced_Product_Labels_Pro')) {
                wp_enqueue_style('icon_it_css', plugins_url('/assets/css/icon-picker.css', iThemeland_WooCommerce_Advanced_Product_Labels_Pro()->file), array(), iThemeland_WooCommerce_Advanced_Product_Labels_Pro()->version);
                wp_enqueue_style('it-woocommerce-advanced-product-labels-pro-front-end-css', plugins_url('/assets/front-end/css/it-woocommerce-advanced-product-labels-pro.css', iThemeland_WooCommerce_Advanced_Product_Labels_Pro()->file), array(), iThemeland_WooCommerce_Advanced_Product_Labels_Pro()->version);
                wp_enqueue_script('countdown-1-js', plugins_url('/assets/jquery-countdown/jquery.countdown.min.js', iThemeland_WooCommerce_Advanced_Product_Labels_Pro()->file), array('jquery'), iThemeland_WooCommerce_Advanced_Product_Labels_Pro()->version); //phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter 
                wp_enqueue_script('countdown-2-js', plugins_url('/assets/FlipClock/flipclock.min.js', iThemeland_WooCommerce_Advanced_Product_Labels_Pro()->file), array('jquery'), iThemeland_WooCommerce_Advanced_Product_Labels_Pro()->version); //phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter 
                wp_enqueue_script('tooltipster_it_js', plugins_url('/assets/tooltip/tooltipster.bundle.js', iThemeland_WooCommerce_Advanced_Product_Labels_Pro()->file), array('jquery'), iThemeland_WooCommerce_Advanced_Product_Labels_Pro()->version); //phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter 
                wp_enqueue_script('icon_it_js', plugins_url('/assets/js/icon-picker.js', iThemeland_WooCommerce_Advanced_Product_Labels_Pro()->file), array('jquery'), iThemeland_WooCommerce_Advanced_Product_Labels_Pro()->version); //phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter 
                wp_enqueue_script('it-customscrollbar-js', plugins_url('/assets/admin/js/jquery.mCustomScrollbar.concat.min.js', iThemeland_WooCommerce_Advanced_Product_Labels_Pro()->file), array('jquery'), iThemeland_WooCommerce_Advanced_Product_Labels_Pro()->version); //phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter 
                wp_enqueue_script('single-label-js', plugins_url('/assets/admin/js/single-label-option.js', iThemeland_WooCommerce_Advanced_Product_Labels_Pro()->file), array('jquery', 'it-customscrollbar-js'), iThemeland_WooCommerce_Advanced_Product_Labels_Pro()->version); //phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter 
            }

            // Scripts
            wp_enqueue_script('iwbvel-datetimepicker', IWBVEL_JS_URL . 'jquery.datetimepicker.js', ['jquery'], IWBVEL_VERSION); //phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter 
            wp_enqueue_script('iwbvel-functions', IWBVEL_JS_URL . 'functions.js', ['jquery'], IWBVEL_VERSION); //phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter 
            wp_enqueue_script('iwbvel-global-functions', IWBVEL_JS_URL . 'global-functions.js', ['jquery'], IWBVEL_VERSION); //phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter 
            wp_enqueue_script('iwbvel-variation-functions', IWBVEL_JS_URL . 'variation-functions.js', ['jquery'], IWBVEL_VERSION); //phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter 
            wp_enqueue_script('iwbvel-select2', IWBVEL_JS_URL . 'select2.min.js', ['jquery'], IWBVEL_VERSION); //phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter 
            wp_enqueue_script('iwbvel-moment', IWBVEL_JS_URL . 'moment-with-locales.min.js', ['jquery'], IWBVEL_VERSION); //phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter 
            wp_enqueue_script('iwbvel-tipsy', IWBVEL_JS_URL . 'jquery.tipsy.js', ['jquery'], IWBVEL_VERSION); //phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter 
            wp_enqueue_script('iwbvel-bootstrap_datepicker', IWBVEL_JS_URL . 'bootstrap-material-datetimepicker.js', ['jquery'], IWBVEL_VERSION); //phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter 
            wp_enqueue_script('iwbvel-sweetalert', IWBVEL_JS_URL . 'sweetalert.min.js', ['jquery'], IWBVEL_VERSION, true);
            wp_enqueue_script('iwbvel-main', IWBVEL_JS_URL . 'main.js', ['jquery'], IWBVEL_VERSION); //phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter 
            wp_enqueue_script('iwbvel-variation-events', IWBVEL_JS_URL . 'variation-events.js', ['jquery'], IWBVEL_VERSION); //phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter 
            wp_enqueue_script('iwbvel-global-events', IWBVEL_JS_URL . 'global-events.js', ['jquery'], IWBVEL_VERSION); //phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter 
            wp_localize_script('iwbvel-main', 'IWBVEL_DATA', [
                'ajax_url' => admin_url('admin-ajax.php'),
                'wc_product_edit_link' => admin_url("post.php?post={id}&action=edit"),
                'ajax_nonce' => wp_create_nonce('iwbvel_ajax_nonce'),
                'reserved_field_keys' => $meta_field_repository->get_reserved_field_names(),
                'background_process' => [
                    'max_process_count' => [
                        'product_create' => 100,
                        'product_restore' => 100,
                        'product_update' => 10,
                        'product_duplicate_count' => ProductDuplicateService::MAX_PROCESS_COUNT,
                        'product_duplicate_ids' => ProductDuplicateService::MAX_PROCESS_IDS,
                        'product_delete' => ProductDeleteService::MAX_PROCESS_COUNT,
                        'history_undo' => HistoryUndoService::MAX_PROCESS_COUNT,
                        'history_redo' => HistoryRedoService::MAX_PROCESS_COUNT,
                    ],
                    'loading_messages' => [
                        'processing' => Render::html(IWBVEL_VIEWS_DIR . 'background_process/processing_message.php'),
                        'stopping' => Render::html(IWBVEL_VIEWS_DIR . 'background_process/stopping_message.php'),
                    ]
                ],
                'strings' => [
                    'please_select_one_item' => esc_html__('Please select one product', 'ithemeland-bulk-variation-editing-for-woocommerce')
                ],
                'icons' => [
                    'loading_2' => esc_url(IWBVEL_IMAGES_URL . 'loading-2.gif'),
                    'sortUpAndDown' => '<img src="' . esc_url(IWBVEL_IMAGES_URL . 'sortable.png') . '" alt="">',
                    'sortUpToDown' => '<i class="dashicons dashicons-arrow-down"></i>',
                    'sortDownToUp' => '<i class="dashicons dashicons-arrow-up"></i>',
                ],
                'filter_option_values' => $search_repository->get_option_values(),
                'iwbvel_settings' => $setting_repository->get_settings()
            ]);

            wp_localize_script('iwbvel-variation-events', 'IWBVEL_VARIATION_DATA', [
                'html' => $this->get_variation_data_html(),
            ]);
            wp_localize_script('iwbvel-global-events', 'iwbvelTranslate', LangHelper::get_js_strings());
            wp_enqueue_media();
            wp_enqueue_editor();
            wp_enqueue_script('jquery-ui-sortable');
            wp_enqueue_script('jquery-ui-datepicker');
            wp_enqueue_script('wp-color-picker');
        }
    }

    private function onboarding_enqueue_scripts()
    {
        wp_enqueue_style('iwbvel-sweetalert', IWBVEL_CSS_URL . 'sweetalert.css', [], IWBVEL_VERSION);
        wp_enqueue_script('iwbvel-sweetalert', IWBVEL_JS_URL . 'sweetalert.min.js', ['jquery'], IWBVEL_VERSION); //phpcs:ignore 

        if (defined('WBEBL_NAME')) {
            wp_enqueue_style('iwbvel-onboarding', WBEBL_FW_URL . 'onboarding/assets/css/onboarding.css', [], WBEBL_VERSION);
            wp_enqueue_script('iwbvel-onboarding', WBEBL_FW_URL . 'onboarding/assets/js/onboarding.js', ['jquery'], WBEBL_VERSION); //phpcs:ignore 
        } else {
            wp_enqueue_style('iwbvel-onboarding', IWBVEL_FW_URL . 'onboarding/assets/css/onboarding.css', [], IWBVEL_VERSION);
            wp_enqueue_script('iwbvel-onboarding', IWBVEL_FW_URL . 'onboarding/assets/js/onboarding.js', ['jquery'], IWBVEL_VERSION); //phpcs:ignore 
        }

        wp_localize_script('iwbvel-onboarding', 'ithemeland_onboarding', [
            'nonce' => wp_create_nonce('ithemeland_onboarding_action'),
            'ajaxurl' => admin_url('admin-ajax.php'),
            'redirecting_text' => esc_html__('Redirecting...', 'ithemeland-bulk-variation-editing-for-woocommerce'),
            'skip_text' => esc_html__('Skip', 'ithemeland-bulk-variation-editing-for-woocommerce')
        ]);
    }

    private function get_variation_data_html()
    {
        ob_start();
        include IWBVEL_VIEWS_DIR . "variations/add_variations/bulk_actions/file-item.php";
        $file_item = ob_get_clean();

        ob_start();
        include IWBVEL_VIEWS_DIR . "variations/add_variations/variations-raw-table-row.php";
        $raw_table_row = ob_get_clean();

        return [
            'empty_table' => '<tr><td colspan="100%">No data available</td></tr>',
            'raw_table_row' => $raw_table_row,
            'file_item' => $file_item,
            'thumbnail_default' => esc_url(IWBVEL_IMAGES_URL . "/woocommerce-placeholder-150x150.png"),
            'thumbnail_default_full_size' =>  esc_url(IWBVEL_IMAGES_URL . "/woocommerce-placeholder.png"),
            'combine_item' => '<li class="iwbvel-attribute-selected-term-item {iwbvel-new-item}" data-attribute="" data-term="">
                <span class="iwbvel-combine-attribute-item-taxonomy"></span>
                <span class="iwbvel-combine-attribute-item-term"></span>
                <button type="button" class="iwbvel-attribute-selected-term-remove"><i class="iwbvel-icon-x"></i></button>
            </li>',
        ];
    }

    public static function activate()
    {
        // 
    }

    public static function deactivate()
    {
        // 
    }

    public static function is_initable()
    {
        if (!is_null(self::$is_initable)) {
            return self::$is_initable;
        }

        if (!class_exists('WooCommerce')) {
            self::woocommerce_required();
            self::$is_initable = false;
            return false;
        }

        if (defined('IWBVE_VERSION') && version_compare(IWBVE_VERSION, '2.0.0', '<')) {
            self::$is_initable = false;
            return false;
        }

        self::$is_initable = true;
        return true;
    }

    private static function create_tables()
    {
        global $wpdb;
        $history_table_name = esc_sql($wpdb->prefix . 'itbbc_history');
        $history_items_table_name = esc_sql($wpdb->prefix . 'itbbc_history_items');
        $query = '';
        $history_table = $wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($history_table_name));
        if (!$wpdb->get_var($history_table) == $history_table_name) { //phpcs:ignore
            $query .= "CREATE TABLE {$history_table_name} (" . // phpcs:ignore
                "id int(11) NOT NULL AUTO_INCREMENT,
                  user_id int(11) NOT NULL,
                  fields text NOT NULL,
                  operation_type varchar(32) NOT NULL,
                  operation_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
                  reverted tinyint(1) NOT NULL DEFAULT '0',
                  sub_system varchar(64) NOT NULL,
                  PRIMARY KEY (id),
                  INDEX (user_id)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
        }

        $history_items_table = $wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($history_items_table_name)); //phpcs:ignore
        if (!$wpdb->get_var($history_items_table) == $history_items_table_name) { //phpcs:ignore
            $query .= "CREATE TABLE {$history_items_table_name} (" . //phpcs:ignore
                "id int(11) NOT NULL AUTO_INCREMENT,
                      history_id int(11) NOT NULL,
                      historiable_id int(11) NOT NULL,
                      field longtext,
                      prev_value longtext,
                      new_value longtext,
                      prev_total_count int(11) NOT NULL DEFAULT 1,
                      new_total_count int(11) NOT NULL DEFAULT 1,
                      PRIMARY KEY (id),
                      INDEX (history_id),
                      INDEX (historiable_id)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";

            $query .= "ALTER TABLE {$history_items_table_name} ADD CONSTRAINT itbbc_history_items_history_id_relation FOREIGN KEY (history_id) REFERENCES {$history_table_name} (id) ON DELETE CASCADE ON UPDATE CASCADE;";
        } else {
            $result = $wpdb->get_results("SELECT DATA_TYPE as itbbc_field_type FROM information_schema.columns WHERE table_name = '{$history_items_table_name}' AND column_name = 'field'"); //phpcs:ignore
            if (!empty($result[0]->iwbve_field_type) && $result[0]->iwbve_field_type != 'longtext') {
                $wpdb->query("ALTER TABLE {$history_items_table_name} MODIFY field longtext"); //phpcs:ignore
            }
        }

        if (!empty($query)) {
            require_once(ABSPATH . '/wp-admin/includes/upgrade.php');
            dbDelta($query);
        }
    }

    private static function update_table()
    {
        global $wpdb;
        $history_items_table_name = esc_sql($wpdb->prefix . 'itbbc_history_items');
        $result = $wpdb->get_var("SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = '{$history_items_table_name}' AND COLUMN_NAME = 'prev_total_count'"); //phpcs:ignore
        if (empty($result)) {
            try {
                $wpdb->query("ALTER TABLE {$history_items_table_name} ADD prev_total_count INT(11) NOT NULL DEFAULT 1"); //phpcs:ignore
                $wpdb->query("ALTER TABLE {$history_items_table_name} ADD new_total_count INT(11) NOT NULL DEFAULT 1"); //phpcs:ignore
            } catch (\Exception $e) {
                update_option('iwbve_update_table_log', $e->getMessage());
            }
        }
    }
}
