<?php
!defined('ABSPATH') && exit;

use Phox\core\admin\Dashboard_Menu;
use Phox\core\admin\Enqueue;
use Phox\core\License_Activation;

if( ! function_exists('wdes_platform_error_message') ) {
    function wdes_platform_error_message(int $error_code) : string
    {
        switch( $error_code ) {
            case 1:
                return 'You cannot activate the theme because you are missing some data.';
                break;
            case 2:
                return 'You cannot activate the theme because you did not have any products from us on your envato account.';
                break;
            case 3:
                return 'You cannot activate the theme because you did not have any Phox product on your envato account. You can buy Phox from <a href="https://themeforest.net/item/phox-responsive-hosting-wordpress-theme/22824456">here</a>';
                break;
            case 4:
                return 'This license is already registered by another domain. If you need to reuse this license on another domain, please read this article <a href="https://phox.whmcsdes.com/docs/how-do-i-unregister-a-license-on-a-website/">here</a>.';
                break;
            default:
                return 'You have unexpected errors. Please contact the support for <a href="https://whmcsdes.com/contact">here</a>.';
        }
    }
}

//Register Menu
/** @var Phox\core\admin\Dashboard_Menu $dashborad_menu */
/** @var string $icon */
/** @var int|float|null $position */
$dashborad_menu->register_main_menu(
    path: WDES_ADMIN_DIR . '/templates-parts/home-wizard.php',
    icon: $icon,
    position: $position
);


//Change Menu Name
/** @var Phox\core\admin\Dashboard_Menu $dashborad_menu */
$dashborad_menu->apply_new_menu_name('Dashboard');

//Register Sub Menu
$wizard_menu = new Dashboard_Menu(
    parent_slug: 'phox',
    page_title: 'Wizard',
    menu_slug: 'phox-wizard',
    menu_title: 'Wizard',
    capability: 'edit_theme_options'
);

//Register License
$license = new License_Activation();
$wizard_enqueue = new Enqueue();
$temp_login = new \Phox\core\admin\Temporary_Login();

if(isset($_GET['page']) && $_GET['page'] === 'phox-wizard' && isset($_GET['wdes-error-id'])){

    $wizard_menu->set_render_vars(['status' => false, 'message' =>wdes_platform_error_message($_GET['wdes-error-id'])]);

}

//install plugins
if( $license->does_activated() ){
    //check temp login user if find remove it
    $temp_login->remove_all_temporary_users();

    // Filter is applied inside a method which is hooked to 'init'.
    add_filter( 'tgmpa_load', function(){
        return true;
    }, 10 );

    add_action('init', function ()use($wizard_menu){
        $tgm_class = TGM_Plugin_Activation::get_instance();

        $plugins_need_require = array_filter($tgm_class->plugins, function ($plugin) use( $tgm_class) {
           return ! $tgm_class->is_plugin_active($plugin['slug']) && $plugin['required'] ;
        });

        if (! empty( $plugins_need_require ) || wp_doing_ajax()  ){
            $plugins_need_optional = array_filter($tgm_class->plugins, function ($plugin) use( $tgm_class) {
                return ! $tgm_class->is_plugin_active($plugin['slug']) && ! $plugin['required'] ;
            });

            $plugin_report = [
                'plugins' => [
                    'require' => $plugins_need_require,
                    'optional' => $plugins_need_optional,
                    'next_step_url' =>  add_query_arg(
                        array(
                            'page' => 'phox-wizard',
                        ),
                        admin_url('admin.php')
                    )
                ]
            ];

            $wizard_menu->set_render_vars($plugin_report);
        }else{

            $import_plugin_url = add_query_arg(
                array(
                    'page' => 'wdes-demo-import',
                ),
                admin_url('themes.php')
            );

            $theme_option_url = add_query_arg(
                array(
                    'page' => 'phox_options',
                ),
                admin_url('admin.php')
            );

            $dashborad_url = add_query_arg(
                array(
                    'page' => 'phox',
                ),
                admin_url('admin.php')
            );

            $import_doc_url = esc_url('https://phox.whmcsdes.com/docs/importing-phox-demos/');

            $finish_report = [
                'finish' => [
                    'import_url' => defined('OCDI_PATH') ? $import_plugin_url : $import_doc_url,
                    'theme_option_url' => esc_url($theme_option_url),
                    'dashboard_url' => $dashborad_url,
                    'ticket_url' => esc_url('https://whmcsdes.com/ca/submitticket.php?step=2&deptid=2')
                ]
            ];

            $wizard_menu->set_render_vars($finish_report);

            delete_transient('wdes_fresh_install');

        }

    });

    add_action( 'wp_ajax_wdes_wizard_plugins', function (){

        check_ajax_referer( 'wdes_wizard_plugins', 'wdes_wizard_plugins_nonce' );

        $tgm_class = TGM_Plugin_Activation::get_instance();

        $install_plugin_file = '';

        $plugins = $tgm_class->plugins;

        $method = $_GET;

        if ( empty( $method['slug'] ) ) {
            wp_send_json_error(
                array(
                    'slug'         => '',
                    'errorCode'    => 'no_plugin_specified',
                    'errorMessage' => __( 'No plugin specified.' ),
                ), 403
            );
        }

        $status = array(
            'install' => 'plugin',
            'slug'    => sanitize_key( wp_unslash( $method['slug'] ) ),
        );

        if ( ! current_user_can( 'install_plugins' ) ) {
            $status['errorMessage'] = __( 'Sorry, you are not allowed to install plugins on this site.' );
            wp_send_json_error( $status , 401 );
        }

        if( ! isset($plugins[$method['slug']])){
            $status['errorMessage'] = __( 'Sorry, This plugin does not exist.' );
            wp_send_json_error( $status , 401 );
        }

        require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
        require_once ABSPATH . 'wp-admin/includes/plugin-install.php';

        //install process
        if(! $tgm_class->is_plugin_installed($method['slug'])){
            $extrnal_repo = isset($tgm_class->plugins[ $method['slug'] ]['source']) && $tgm_class->plugins[ $method['slug'] ]['source'] !== 'repo' ? true : false;

            if($extrnal_repo){
                $api = new stdClass();

                $api->name = $tgm_class->plugins[ $method['slug'] ]['name'];
                $api->slug = $tgm_class->plugins[ $method['slug'] ]['slug'];
                $api->version = $tgm_class->plugins[ $method['slug'] ]['version'];
                $api->download_link = $tgm_class->plugins[ $method['slug'] ]['source'];
            }else{
                $api = plugins_api(
                    'plugin_information',
                    array(
                        'slug'   => sanitize_key( wp_unslash( $method['slug'] ) ),
                        'fields' => array(
                            'sections' => false,
                        ),
                    )
                );
            }

            if ( is_wp_error( $api ) ) {
                $status['errorMessage'] = $api->get_error_message();
                wp_send_json_error( $status , 403 );
            }

            $skin     = new WP_Ajax_Upgrader_Skin();
            $upgrader = new Plugin_Upgrader( $skin );
            $result   = $upgrader->install( $api->download_link );

            if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
                $status['debug'] = $skin->get_upgrade_messages();
            }

            if ( is_wp_error( $result ) ) {
                $status['errorCode']    = $result->get_error_code();
                $status['errorMessage'] = $result->get_error_message();
                wp_send_json_error( $status, 403 );
            } elseif ( is_wp_error( $skin->result ) ) {
                $status['errorCode']    = $skin->result->get_error_code();
                $status['errorMessage'] = $skin->result->get_error_message();
                wp_send_json_error( $status, 403 );
            } elseif ( $skin->get_errors()->has_errors() ) {
                $status['errorMessage'] = $skin->get_error_messages();
                wp_send_json_error( $status ,403 );
            } elseif ( is_null( $result ) ) {
                global $wp_filesystem;

                $status['errorCode']    = 'unable_to_connect_to_filesystem';
                $status['errorMessage'] = __( 'Unable to connect to the filesystem. Please confirm your credentials.' );

                // Pass through the error from WP_Filesystem if one was raised.
                if ( $wp_filesystem instanceof WP_Filesystem_Base && is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) {
                    $status['errorMessage'] = esc_html( $wp_filesystem->errors->get_error_message() );
                }

                wp_send_json_error( $status , 403 );
            }

            $install_status = install_plugin_install_status( $api );
            $install_plugin_file = $install_status['file'];
        }

        $plugin = $tgm_class->plugins[$method['slug']];

        $plugin['file_path'] = ! empty($install_plugin_file) ? $install_plugin_file : $plugin['file_path'];

        $status = array(
            'activate'   => 'plugin',
            'slug'       => wp_unslash( $plugin['slug'] ),
            'pluginName' => wp_unslash( $plugin['name'] ),
            'plugin'     => wp_unslash( $plugin['file_path'] ),
        );

        if ( ! current_user_can( 'activate_plugin', $status['plugin'] ) ) {
            $status['errorMessage'] = __( 'Sorry, you are not allowed to activate plugins on this site.' );
            wp_send_json_error( $status, 403 );
        }

        if ( $tgm_class->is_plugin_active($method['slug']) ) {
            $status['errorMessage'] = sprintf(
            /* translators: %s: Plugin name. */
                __( '%s is already active.' ),
                $status['pluginName']
            );
        }
        $activated = activate_plugin( $status['plugin'] );

        if ( is_wp_error( $activated ) ) {
            $status['errorMessage'] = $activated->get_error_message();
            wp_send_json_error( $status, 405 );
        }

        //remove redirect that happens after activate Elementor & Slider Rev plugin
        if ( $method['slug'] === 'elementor' )
            delete_transient( 'elementor_activation_redirect' );
        if ( $method['slug'] === 'revslider' )
            delete_transient( '_revslider_welcome_screen_activation_redirect' );

        wp_send_json_success( $status );

    });

}

$wizard_menu->register_sub_menu(WDES_ADMIN_DIR . '/templates-parts/wizard.php');

//Temporary Login
$login_token = [
    'auth' => '',
    'logged' => ''
];


//register Css &Js files
$wizard_enqueue->set_base_url(WDES_ADMIN_ASSETS_URI);
$wizard_enqueue->enqueue_media();
$wizard_enqueue->add_style('admin', 'admin-style', []);
$wizard_enqueue->add_style('wizard', 'wizard-style', []);
$wizard_enqueue->add_script('wizard', 'wizard-script', []);
if(isset($_GET['page']) && $_GET['page'] === 'phox-wizard'){
    if(!$license->does_activated()){
        $temp_login->create_temporary_login_session();
    }
    $login_token = $temp_login->get_meta();
    $wizard_enqueue->add_inline_script(
        handle: 'wdes-wizard',
        data: 'const wdesAdminAjaxLicenseActivation = ' .json_encode( [
            'nonce'         => $temp_login->create_wp_rest_nonce(),
            'plugins-nonce' => wp_create_nonce( 'wdes_wizard_plugins' ),
            'domain' => site_url(),
            'theme_version' => WDES_THEME_VERSION,
            'return_url'   => admin_url( 'admin.php?page=phox-wizard' ),
            'verify_url'   => rest_url('wdes/activate-license'),
            'source' => 'wordpress',
            'key' => $login_token['key'],
            'secret' => $login_token['secret'],
        ]).';',
        position: 'before'
    );

}

$wizard_enqueue->add_google_font(
    'Inter',
    [
        '400',
        '500',
        '600',
        '700'
    ]
);

$hook_suffix = isset($_GET['page']) && $_GET['page'] === 'phox' ? 'toplevel_page_phox' : 'phox_page_phox-wizard';
$wizard_enqueue->set_hook_suffix($hook_suffix);
//Fire when admin page load
$wizard_enqueue->enqueue_admin();


