<?php

class LSDRC_OCDI extends LSDRC_Base
{
    protected $cdn = 'https://cdn.webilia.com/u/c/listdomer';

    public function init()
    {
        // Demo Importer
        add_filter('ocdi/import_files', [$this, 'demos']);

        // Plugins
        add_filter('ocdi/register_plugins', [$this, 'plugins']);

        // Before Import
        add_action('ocdi/before_widgets_import', [$this, 'prepare']);

        // After Import
        add_action('ocdi/after_import', [$this, 'config'], 10);

        // Menu Setup
        add_filter('ocdi/plugin_page_setup', [$this, 'menu']);

        // Page
        add_filter('ocdi/plugin_intro_text', [$this, 'intro']);
        add_filter('ocdi/plugin_page_title', [$this, 'title']);
        add_filter('ocdi/import_successful_buttons', function(array $buttons = [])
        {
            if (!is_array($buttons) || !count($buttons)) return [];

            // Update Theme Settings URL
            if (isset($buttons[0]['href']))
            {
                $buttons[0]['href'] = admin_url('admin.php?page=listdomer-settings');
                $buttons[0]['target'] = '';
            }

            return $buttons;
        });
    }

    /**
     * Register Demos for Demo Importer
     * @return array
     */
    public function demos(): array
    {
        $content = 'content.xml';

        $pro = class_exists(LSD_Base::class) && LSD_Base::isPro();
        if ($pro) $content = 'content-pro.xml';

        return [
            [
                'key' => 'demo1',
                'import_file_name' => esc_html__('General Directory', 'listdomer-core'),
                'categories' => [
                    esc_html__('General', 'listdomer-core'),
                ],
                'import_file_url' => $this->cdn . '/d1/v1/' . $content,
                'import_widget_file_url' => $this->cdn . '/d1/v1/widgets.wie',
                'import_customizer_file_url' => $this->cdn . '/d1/v1/customizer.dat',
                'import_redux' => [
                    [
                        'file_url' => $this->cdn . '/d1/v1/redux.json',
                        'option_name' => 'listdomer_theme_settings',
                    ],
                ],
                'import_preview_image_url' => $this->cdn . '/d1/v1/preview.png',
                'preview_url' => 'https://api.webilia.com/go/listdomer-demo',
                'logo' => $this->cdn . '/d1/v1/logo.png',
                'site_icon' => $this->cdn . '/d1/v1/site-icon.webp',
                'listdom' => $this->cdn . '/d1/v1/listdom.json',
                'elementor' => $this->cdn . '/d1/v1/elementor-kit.zip',
            ],
            [
                'key' => 'demo2',
                'import_file_name' => esc_html__('Real Estate Directory', 'listdomer-core'),
                'categories' => [
                    esc_html__('Real Estate', 'listdomer-core'),
                ],
                'import_file_url' => $this->cdn . '/d2/v1/' . $content,
                'import_widget_file_url' => $this->cdn . '/d2/v1/widgets.wie',
                'import_customizer_file_url' => $this->cdn . '/d2/v1/customizer.dat',
                'import_redux' => [
                    [
                        'file_url' => $this->cdn . '/d2/v1/redux.json',
                        'option_name' => 'listdomer_theme_settings',
                    ],
                ],
                'import_preview_image_url' => $this->cdn . '/d2/v1/preview.png',
                'preview_url' => 'https://api.webilia.com/go/real-estate-demo',
                'logo' => $this->cdn . '/d2/v1/logo.png',
                'site_icon' => $this->cdn . '/d2/v1/site-icon.webp',
                'listdom' => $this->cdn . '/d2/v1/listdom.json',
                'elementor' => $this->cdn . '/d2/v1/elementor-kit.zip',
            ],
            [
                'key' => 'demo3',
                'import_file_name' => esc_html__('Business Directory', 'listdomer-core'),
                'categories' => [
                    esc_html__('General', 'listdomer-core'),
                ],
                'import_file_url' => $this->cdn . '/d3/v1/' . $content,
                'import_widget_file_url' => $this->cdn . '/d3/v1/widgets.wie',
                'import_customizer_file_url' => $this->cdn . '/d3/v1/customizer.dat',
                'import_redux' => [
                    [
                        'file_url' => $this->cdn . '/d3/v1/redux.json',
                        'option_name' => 'listdomer_theme_settings',
                    ],
                ],
                'import_preview_image_url' => $this->cdn . '/d3/v1/preview.png',
                'preview_url' => 'https://api.webilia.com/go/business-directory-demo',
                'logo' => $this->cdn . '/d3/v1/logo.png',
                'site_icon' => $this->cdn . '/d3/v1/site-icon.webp',
                'listdom' => $this->cdn . '/d3/v1/listdom.json',
                'elementor' => $this->cdn . '/d3/v1/elementor-kit.zip',
            ],
        ];
    }

    public function plugins($plugins): array
    {
        $demo_plugins = [
            [
                'name' => 'Listdom',
                'slug' => 'listdom',
                'required' => true,
                'preselected' => true,
            ],
            [
                'name' => 'Elementor',
                'slug' => 'elementor',
                'required' => true,
                'preselected' => true,
            ],
            [
                'name' => 'Vertex Addons for Elementor',
                'slug' => 'addons-for-elementor-builder',
                'source' => 'https://cdn.webilia.com/u/s/addons-for-elementor-builder.zip',
                'required' => true,
                'preselected' => true,
            ],
        ];

        if (
            (isset($_GET['step']) && $_GET['step'] === 'import')
            || wp_doing_ajax()
        )
        {
            // Real Estate Directory
            if ((isset($_GET['import']) && $_GET['import'] === '1') || wp_doing_ajax())
            {
                $demo_plugins[] = [
                    'name' => 'Listdom Real Estate Toolkit',
                    'description' => esc_html__('A powerful toolkit that equips Listdom with real estate features for modern property listings.', 'listdomer-core'),
                    'slug' => 'listdom-tkre',
                    'source' => $this->cdn . '/d2/v1/listdom-tkre.zip',
                    'required' => true,
                    'preselected' => true,
                ];

                $demo_plugins[] = [
                    'name' => 'WooCommerce',
                    'slug' => 'woocommerce',
                    'required' => true,
                    'preselected' => true,
                ];
            }

            // Business Directory
            if ((isset($_GET['import']) && $_GET['import'] === '2') || wp_doing_ajax())
            {
                $demo_plugins[] = [
                    'name' => 'Business Toolkit',
                    'description' => esc_html__('A feature-rich toolkit for building and customizing business and listing directories with Listdom.', 'listdomer-core'),
                    'slug' => 'listdom-tkbu',
                    'source' => $this->cdn . '/d3/v1/listdom-tkbu.zip',
                    'required' => true,
                    'preselected' => true,
                ];

                $demo_plugins[] = [
                    'name' => 'WooCommerce',
                    'slug' => 'woocommerce',
                    'required' => true,
                    'preselected' => true,
                ];
            }
        }

        return array_merge($plugins, $demo_plugins);
    }

    public function prepare($demo)
    {
        $sidebars_widgets = get_option('sidebars_widgets');

        $empty_widgets = [];
        foreach ($sidebars_widgets as $sidebar => $widgets) $empty_widgets[$sidebar] = [];

        update_option('sidebars_widgets', $empty_widgets);
    }

    public function config($demo)
    {
        // Demo Key
        $key = $demo['key'] ?? 'demo1';

        // Assign Menus
        $main = get_term_by('name', 'Top Menu', 'nav_menu');
        $footer = get_term_by('name', 'Footer', 'nav_menu');

        set_theme_mod('nav_menu_locations', [
            'menu-1' => $main->term_id,
            'menu-2' => $footer->term_id,
        ]);

        /**
         * Import Listdom Settings
         */
        if (class_exists('LSD_IX_Settings') && isset($demo['listdom']) && wp_http_validate_url($demo['listdom']))
        {
            $listdom_path = download_url($demo['listdom'], 60);
            if (!is_wp_error($listdom_path)) LSD_IX_Settings::import($listdom_path);
        }

        // General Demo
        if ($key === 'demo1' && class_exists('LSD_Options'))
        {
            // Assign front page and posts page (blog page)
            $this->wp_pages('Home');

            /**
             * Search Forms
             */
            $this->searches([
                'Home Search Form' => 'Search Results',
            ]);

            /**
             * General Settings
             */
            $this->pages([
                'submission_page' => 'Manage Listings',
            ]);

            /**
             * Listing Category
             */
            $this->listings([
                'Sample House' => 'Real Estate',
                'Sample Auto Repair' => 'Auto Repairs',
                'Sample Restaurant' => 'Restaurant',
                'Sample Digital Agency' => 'Business',
                'Sample Barber Shop' => 'Beauty Salon',
                'Sample Hotel' => 'Hotel',
                'Sample Clinic' => 'Bank',
                'Sample Business' => 'Business',
                'Sample Bank' => 'Bank',
            ]);
        }
        // Real Estate Demo
        else if ($key === 'demo2' && class_exists('LSD_Options'))
        {
            // Assign front page and posts page (blog page)
            $this->wp_pages('Vertical Search Form Homepage');

            /**
             * Search Forms
             */
            $this->searches([
                'Homepage Vertical Search Form' => 'Search Results',
                'Homepage "Rent" Search Form' => 'Search Results',
                'Homepage "Lease" Search Form' => 'Search Results',
                'Homepage "Buy" Search Form' => 'Search Results',
            ]);

            /**
             * General Settings
             */
            $this->pages([
                'submission_page' => 'Dashboard',
            ]);

            /**
             * Listing Category
             */
            $this->listings([
                'Newly Renovated House for Rent' => 'House',
                'Gated Community House for Sale' => 'Apartment',
                'Smart Home with Advanced Features' => 'Apartment',
                'Duplex House in Prime Neighborhood' => 'House',
                'Modern Family Home for Sale' => 'House',
                'Rooftop Restaurant with Great Ambiance' => 'Restaurant',
                'Luxury Resort for Investment' => 'Hotel',
                'Corporate Office for Lease' => 'Office Space',
                'Fine Dining Space Available' => 'Restaurant',
                'Cozy Country Bungalow' => 'Bungalow',
                'Beachfront Bungalow Retreat' => 'Bungalow',
                'Charming Bungalow for Sale' => 'Bungalow',
                'Spacious 2BHK Apartment' => 'Apartment',
                'Studio Apartment for Lease' => 'Bungalow',
                'Serviced Apartment' => 'Apartment',
                'Luxury Condo for Rent' => 'Apartment',
                'Countryside Retreat for Sale' => 'Bungalow',
                'Beachfront Property for Sale' => 'Bungalow',
                'Spacious Townhouse for Sale' => 'Bungalow',
                'Exclusive Penthouse for Lease' => 'House',
                'Luxury Villa for Sale' => 'House',
                'Budget-Friendly Room for Rent' => 'House',
                'Commercial Space for Lease' => 'Hotel',
                'Office Space for Rent' => 'Office Space',
                'Great House For Sale' => 'House',
                'Hanna Restaurant' => 'Restaurant',
                'Famous Peterson House' => 'Condominium',
                'Flat Apartment (VIP)' => 'Apartment',
                'Beautiful House' => 'House',
                'House For Rent' => 'House',
                'Great Opportunity Apply NOW!' => 'Bungalow',
                'Silent Area Apartment' => 'Bungalow',
                'Classic Apartment' => 'Apartment',
                'Marshall House' => 'Bungalow',
                'Hertok Hotel' => 'Hotel',
                'Office Space' => 'Office Space',
            ]);
        }
        // Business Directory Demo
        else if ($key === 'demo3' && class_exists('LSD_Options'))
        {
            // Assign front page and posts page (blog page)
            $this->wp_pages('Home');

            /**
             * Search Forms
             */
            $this->searches([
                'Header Search Form' => 'Search Results',
            ]);

            /**
             * General Settings
             */
            $this->pages([
                'submission_page' => 'Manage Listings',
            ]);

            /**
             * Listing Category
             */
            $this->listings([
                'Sample House' => 'Real Estate',
                'Sample Auto Repair' => 'Auto Repairs',
                'Sample Restaurant' => 'Restaurant',
                'Sample Digital Agency' => 'Business',
                'Sample Barber Shop' => 'Beauty Salon',
                'Sample Hotel' => 'Hotel',
                'Sample Clinic' => 'Bank',
                'Sample Business' => 'Business',
                'Sample Bank' => 'Bank',
            ]);
        }

        // Listings Geo-point
        if (class_exists(LSD_Main::class) && method_exists(LSD_Main::class, 'update_geopoints'))
        {
            LSD_Main::update_geopoints();
        }

        // Vertex Config
        if (class_exists('\AFEB\System'))
        {
            // Auth Page
            $auth_page = LSDRC_Base::get_post_by_title('Authentication', 'page');

            // Forgot Password Page
            $forgot_page = LSDRC_Base::get_post_by_title('Forgot Password', 'page');

            // Vertex Config
            $settings = get_option('afeb-settings', []);
            $settings['widgets']['login_register'] = [
                'default_login_page' => $auth_page && isset($auth_page->ID) ? $auth_page->ID : '',
                'default_register_page' => $auth_page && isset($auth_page->ID) ? $auth_page->ID : '',
                'default_lostpass_page' => $forgot_page && isset($forgot_page->ID) ? $forgot_page->ID : '',
            ];

            update_option('afeb-settings', $settings);
        }

        // Elementor Kit
        if (class_exists(\Elementor\Plugin::class) && isset($demo['elementor']) && wp_http_validate_url($demo['elementor']))
        {
            try
            {
                if (!function_exists('download_url')) require_once ABSPATH . 'wp-admin/includes/file.php';

                $kit_path = download_url($demo['elementor'], 60);
                if (!is_wp_error($kit_path))
                {
                    $elementor = \Elementor\Plugin::$instance->app->get_component('import-export');
                    $elementor->import_kit($kit_path, ['referrer' => 'remote']);

                    if ($kit_path && is_string($kit_path) && file_exists($kit_path)) unlink($kit_path);
                }
            }
            catch (Exception $e) {}
        }

        // Import Logo
        if (isset($demo['logo']) && trim($demo['logo']) && class_exists('LSD_IX') && class_exists('LSD_File'))
        {
            $ix = new LSD_IX();
            $logo_id = $ix->attach_by_buffer(LSD_File::download($demo['logo']), basename($demo['logo']));

            set_theme_mod('custom_logo', $logo_id);
        }

        // Import Site Icon
        if (isset($demo['site_icon']) && trim($demo['site_icon']) && class_exists('LSD_IX') && class_exists('LSD_File'))
        {
            $ix = new LSD_IX();
            $icon_id = $ix->attach_by_buffer(LSD_File::download($demo['site_icon']), basename($demo['site_icon']));

            update_option('site_icon', $icon_id, true);
        }

        // Nav Menu Widget
        $nav_menus = get_option('widget_nav_menu', []);
        if (is_array($nav_menus) && count($nav_menus))
        {
            // New Menus
            $new_menus = [];

            foreach ($nav_menus as $nvk => $nav_menu)
            {
                if (!is_numeric($nvk))
                {
                    $new_menus[$nvk] = $nav_menu;
                    continue;
                }

                // Menu
                $title = $nav_menu['title'] ?? '';
                $menu = wp_get_nav_menu_object($title);

                // Add new Menu ID
                if ($menu->term_id) $nav_menu['nav_menu'] = $menu->term_id;

                // New Menus
                $new_menus[$nvk] = $nav_menu;
            }

            // New Menus
            update_option('widget_nav_menu', $new_menus);
        }

        // Listdom Personalized
        if (class_exists('LSD_Personalize')) LSD_Personalize::generate();

        // Listdomer Personalized
        if (class_exists('LSDR_Personalize')) LSDR_Personalize::generate();

        // Permalinks
        $this->permalinks();
    }

    private function searches(array $modules = [])
    {
        if (!class_exists(LSD_Base::class)) return;

        foreach ($modules as $f => $p)
        {
            // Form
            $form = LSDRC_Base::get_post_by_title($f, LSD_Base::PTYPE_SEARCH);

            if ($form && isset($form->ID))
            {
                // Search Results Page
                $results_page = LSDRC_Base::get_post_by_title($p, 'page');

                $options = get_post_meta($form->ID, 'lsd_form', true);

                $options['page'] = $results_page && isset($results_page->ID) ? $results_page->ID : '';
                $options['shortcode'] = '';

                update_post_meta($form->ID, 'lsd_form', $options);
            }
        }
    }

    private function listings(array $listings = [])
    {
        if (!class_exists(LSD_Base::class)) return;

        foreach ($listings as $listing_title => $category_title)
        {
            // Listing
            $listing = LSDRC_Base::get_post_by_title($listing_title, LSD_Base::PTYPE_LISTING);

            // Category
            $category = get_term_by('name', $category_title, LSD_Base::TAX_CATEGORY);

            // Set Category
            if (isset($listing->ID) && isset($category->term_id))
            {
                wp_set_post_terms($listing->ID, is_taxonomy_hierarchical(LSD_Base::TAX_CATEGORY) ? $category->term_id : $category_title, LSD_Base::TAX_CATEGORY);
                update_post_meta($listing->ID, 'lsd_primary_category', $category->term_id);
            }
        }
    }

    private function pages(array $pages = [])
    {
        if (!class_exists('LSD_Options')) return;

        // Listdom Settings
        $settings = LSD_Options::settings();

        foreach ($pages as $k => $p)
        {
            // Page
            $page = LSDRC_Base::get_post_by_title($p, 'page');
            $settings[$k] = $page && isset($page->ID) ? $page->ID : '';
        }

        update_option('lsd_settings', $settings);
    }

    private function wp_pages(string $home)
    {
        $front_page = LSDRC_Base::get_post_by_title($home, 'page');
        $blog_page = LSDRC_Base::get_post_by_title('Blog', 'page');

        update_option('show_on_front', 'page');
        update_option('page_on_front', $front_page->ID);
        update_option('page_for_posts', $blog_page->ID);
    }

    public function permalinks()
    {
        /** @var WP_Rewrite $wp_rewrite */
        global $wp_rewrite;

        $wp_rewrite->set_permalink_structure('/%postname%/');
        $wp_rewrite->flush_rules();
    }

    public function menu($setup)
    {
        $setup['parent_slug'] = 'admin.php';
        $setup['page_title'] = esc_html__('Demo Import', 'listdomer-core');
        $setup['menu_title'] = esc_html__('Demo Import', 'listdomer-core');
        $setup['menu_slug'] = 'listdomer';

        return $setup;
    }

    public function intro($intro): string
    {
        return '<div class="ocdi__intro-text"><p class="about-description">'
            . esc_html__('Importing demo data (post, pages, images, theme settings, etc.) is the quickest and easiest way to set up your new theme. It allows you to simply edit everything instead of creating content and layouts from scratch.', 'listdomer-core') .
            '</p>
        </div>';
    }

    public function title($title): string
    {
        return '<div class="ocdi__title-container">
			<h1 class="ocdi__title-container-title">' . esc_html__('Listdomer Demo Importer', 'listdomer-core') . '</h1>
			<a href="https://ocdi.com/user-guide/" target="_blank" rel="noopener noreferrer">
				<img class="ocdi__title-container-icon" src="' . plugins_url() . '/one-click-demo-import/assets/images/icons/question-circle.svg" alt="Questionmark icon">
			</a>
		</div>';
    }
}
