<?php
declare(strict_types = 1);

namespace GPLoker\Inc;

use function __;
use function add_action;
use function add_filter;
use function class_exists;
use function count;
use function defined;
use function delete_post_meta;
use function file_get_contents;
use function flush_rewrite_rules;
use function get_current_user_id;
use function get_post_meta;
use function get_term_by;
use function is_admin;
use function is_array;
use function json_decode;
use function post_type_exists;
use function register_post_type;
use function set_theme_mod;
use function update_option;
use function update_post_meta;
use function update_user_meta;

class Import
{

    private static string $configDirectory = __DIR__ . '/Config';

    private static string $contentDirectory = __DIR__ . '/Content';

    private static string $pluginsDirectory = __DIR__ . '/Plugins';

    public function __construct()
    {
        if (class_exists('\OCDI_Plugin') && is_admin()) {

            $this->GPElementsTrick();

            add_filter('ocdi/register_plugins', [$this, 'pluginRequired']);
            add_filter('ocdi/import_files', [$this, 'contentImporting']);

            /**
             * Disable Redirect, Tour Guide or Wizard After Plugin Activation
             */
            add_action('ocdi/plugin_intaller_before_plugin_activation', [$this, 'keepSilentPlease']);
            add_action('ocdi/plugin_intaller_after_plugin_activation', [$this, 'keepSilentPlease']);

            add_action('ocdi/before_content_import', [$this, 'beforeImportingContent']);
            add_action('ocdi/after_import', [$this, 'afterImportingContent']);

            // optimize
            add_filter('ocdi/regenerate_thumbnails_in_content_import', '__return_false');
            add_filter('ocdi/time_for_one_ajax_call', [$this, 'setAjaxCallTime']);

        }
    }

    public static function init()
    {
        new self();
    }

    public function pluginRequired(array $plugins): array
    {
        $plugins[] = [
            'name'     => 'GP Premium',
            'slug'     => 'gp-premium',
            'source'   => self::$pluginsDirectory . '/gp-premium.zip',
            'required' => true,
        ];

        $plugins[] = [
            'name'     => 'AddToAny Share Buttons',
            'slug'     => 'add-to-any',
            'required' => true,
        ];

        $plugins[] = [
            'name'     => 'GenerateBlocks',
            'slug'     => 'generateblocks',
            'required' => true,
        ];

        $plugins[] = [
            'name'     => 'Yoast SEO',
            'slug'     => 'wordpress-seo',
            'required' => true,
        ];

        return $plugins;
    }

    public function contentImporting(array $content): array
    {
        /**
         * IMPORTANT !!!!
         *
         * before use content.xml make sure to replace "\u002d\u002d" to "--"
         * that make some error with var(--some-variable) on CSS embeded
         *
         */
        $content[] = [
            'import_file_name'                 => 'GP LokerPro',
            'categories'                       => ['General'],
            'local_import_file'                => self::$contentDirectory . '/demo.xml',
            'local_import_gp_premium'          => self::$configDirectory . '/gp-premium.json',
            'local_import_addtoany'            => [
                'option_name'  => 'addtoany_options',
                'option_value' => self::$configDirectory . '/addtoany.json'
            ],
            'local_import_permalink_structure' => '/%postname%/',
            'import_preview_image_url'         => 'https://gpawesome.com/gplokerpro/wp-content/themes/gplokerpro/screenshot.png',
            'preview_url'                      => 'https://gpawesome.com/gplokerpro',
        ];

        return $content;
    }

    public function beforeImportingContent(array $selectedImport): void
    {
        // set Config GP Premium
        if ($selectedImport['local_import_gp_premium']) {
            $GPPremiumConfigurations = file_get_contents($selectedImport['local_import_gp_premium']);
            $GPConfigs               = json_decode($GPPremiumConfigurations, true);

            if ( ! empty($GPConfigs['modules']) && is_array($GPConfigs['modules'])) {
                foreach ($GPConfigs['modules'] as $moduleName) {
                    update_option($moduleName, 'activated');
                }
            }

            if ( ! empty($GPConfigs['options']) && is_array($GPConfigs['options'])) {
                foreach ($GPConfigs['options'] as $optionName => $optionValue) {
                    update_option($optionName, $optionValue);
                }
            }
        }

    }

    public function keepSilentPlease(string $slug): void
    {

        if ($slug === 'generateblocks') {
            update_option('generateblocks_do_activation_redirect', false);
        }

        if ($slug === 'add-to-any') {
            update_user_meta(get_current_user_id(), 'dismissed_wp_pointers', 'addtoany_settings_pointer');
        }
    }

    public function afterImportingContent(array $selectedImport): void
    {
        // Assign menus to their locations.
        $main_menu = get_term_by('name', 'Menu 1', 'nav_menu');

        set_theme_mod('custom_logo', 24);

        set_theme_mod('nav_menu_locations', [
            'primary'  => $main_menu->term_id,
            'slideout' => $main_menu->term_id,
        ]);


        update_option('show_on_front', 'page');
        update_option('page_on_front', 34);
        update_option('page_for_posts', 39);

        /**
         * Set add-to-any settings
         */
        if ($selectedImport['local_import_addtoany']) {
            $addtoanyOptionName = $selectedImport['local_import_addtoany']['option_name'];
            $addtoanySettings   = file_get_contents($selectedImport['local_import_addtoany']['option_value']);
            $addtoanyValue      = json_decode($addtoanySettings, true);

            update_option($addtoanyOptionName, $addtoanyValue);
        }

        /**
         * Set WordPress Default Permalink
         */
        if ($selectedImport['local_import_permalink_structure']) {

            update_option('posts_per_page', 10);

            $css = file_get_contents(self::$configDirectory . '/inline.css');
            update_option('generate_dynamic_css_output', $css);

            update_option('permalink_structure', $selectedImport['local_import_permalink_structure']);
            flush_rewrite_rules();
        }

        // has sticky jobs
        $stickyJobs = Hooks::getAllStickyJobsId();
        foreach ($stickyJobs as $jobId) {
            $is_sticky = get_post_meta($jobId, 'gplokerpro_is_sticky');
            /**
             * Fixed Bugs
             * Handler bugs from importing demo
             *
             * Importing Demo create multiple post_meta with same meta key in one Post ID
             */
            if ( count($is_sticky) > 1 ) {
                $is_sticky = $is_sticky[1];
                delete_post_meta($jobId, 'gplokerpro_is_sticky');
                update_post_meta($jobId, 'gplokerpro_is_sticky', $is_sticky);
            }
        }
    }

    public function setAjaxCallTime(): int
    {
        return 180;
    }

    /**
     * Handle GP ELEMENT POST TYPE
     */
    private function GPElementsTrick()
    {
        add_action('init', [$this, 'setGPElementsTrick']);
    }

    public function setGPElementsTrick()
    {
        if ( ! defined('GP_PREMIUM_VERSION')) {
            return;
        }

        if (post_type_exists('gp_elements')) {
            return;
        }

        $labels = [
            'name'               => __('GP Elements', 'text_domain'),
            'singular_name'      => __('GP Element', 'text_domain'),
            'menu_name'          => __('GP Elements', 'text_domain'),
            'all_items'          => __('All GP Elements', 'text_domain'),
            'add_new_item'       => __('Add New GP Element', 'text_domain'),
            'edit_item'          => __('Edit GP Element', 'text_domain'),
            'new_item'           => __('New GP Element', 'text_domain'),
            'view_item'          => __('View GP Element', 'text_domain'),
            'search_items'       => __('Search GP Elements', 'text_domain'),
            'not_found'          => __('No GP Elements found', 'text_domain'),
            'not_found_in_trash' => __('No GP Elements found in Trash', 'text_domain'),
        ];

        $args = [
            'labels'          => $labels,
            'public'          => true,
            'menu_position'   => 5,
            'supports'        => ['title', 'editor', 'thumbnail', 'excerpt'],
            'has_archive'     => true,
            'capability_type' => 'post',
            'menu_icon'       => 'dashicons-admin-generic',
        ];

        register_post_type('gp_elements', $args);
    }

}
