<?php
if( ! function_exists( 'hasium_install_premium_admin_notice' ) ) {
    /**
     * Display an admin notice for premium version link
     *
     * @since 1.0.1
     * @return void
     * @use admin_notices hooks
     */
    function hasium_install_premium_admin_notice() {

        echo sprintf(
            '<div class="notice success"><p>%s</p></div>',
            sprintf(
                __("Like Hasium free version? You can also buy our <a href='https://wphobby.com/pricing'>premium version</a>", "hasium")
            )
        );
    }
}

add_action( 'admin_notices', 'hasium_install_premium_admin_notice' );

/**
 * Load welcome admin css and js
 * @return void
 * @since  1.0.0
 */
function hasium_admin_styles_scripts() {
    if ( is_admin() ) {

        // Styles
        wp_enqueue_style( 'hasium-admin-style', get_template_directory_uri() . '/assets/css/admin.css', false );

        wp_register_script( 'hasium-admin-settings', get_template_directory_uri() . '/assets/js/hasium-admin-settings.js', array( 'jquery', 'wp-util', 'updates' ), '1.6.5', false );

        $localize = array(
            'ajaxUrl'                            => admin_url( 'admin-ajax.php' ),
            'btnActivating'                      => __( 'Activating Importer Plugin ', 'hasium' ) . '&hellip;',
            'hasiumSitesLink'                     => admin_url( 'admin.php?page=whdi-panel' ),
            'hasiumSitesLinkTitle'                => __( 'See Library', 'hasium' ),
            'recommendedPluiginActivatingText'   => __( 'Activating', 'hasium' ) . '&hellip;',
            'recommendedPluiginDeactivatingText' => __( 'Deactivating', 'hasium' ) . '&hellip;',
            'recommendedPluiginActivateText'     => __( 'Activate', 'hasium' ),
            'recommendedPluiginDeactivateText'   => __( 'Deactivate', 'hasium' ),
            'recommendedPluiginSettingsText'     => __( 'Settings', 'hasium' ),

        );
        wp_localize_script( 'hasium-admin-settings', 'hasium', apply_filters( 'hasium_theme_js_localize', $localize ) );

        // Script
        wp_enqueue_script( 'hasium-admin-settings' );
    }
}
add_action( 'admin_enqueue_scripts', 'hasium_admin_styles_scripts' );

function hasium_admin_menu(){
    if ( current_user_can( 'edit_theme_options' ) ) {

        add_theme_page(
            __('Hasium Options', 'hasium'),
            __('Hasium Options', 'hasium'),
            'administrator',
            'hasium-admin-menu',
            'hasium_welcome_page'
        );
        add_theme_page(
            'hasium-admin-menu',
            esc_html__('Welcome to Hasium','hasium'),
            esc_html__('Welcome','hasium'),
            'administrator',
            'hasium-admin-menu',
            'hasium_welcome_page'
        );
        add_theme_page(
            'hasium-admin-menu',
            esc_html__('Hasium Options','hasium'),
            esc_html__('Theme Options','hasium'),
            'manage_options',
            'customize.php'
        );
    }
}
add_action( 'admin_menu', 'hasium_admin_menu' );

function hasium_welcome_page(){
    require_once get_template_directory() . '/inc/admin/hasium-welcome.php';
}
/**
 * Required Plugin Activate
 *
 * @since 1.2.4
 */
function hasium_required_plugin_activate() {

    if ( ! current_user_can( 'install_plugins' ) || ! isset( $_POST['init'] ) || ! $_POST['init'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
        wp_send_json_error(
            array(
                'success' => false,
                'message' => __( 'No plugin specified', 'hasium' ),
            )
        );
    }

    $plugin_init = ( isset( $_POST['init'] ) ) ? esc_attr( $_POST['init'] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing

    $activate = activate_plugin( $plugin_init, '', false, true );

    if ( is_wp_error( $activate ) ) {
        wp_send_json_error(
            array(
                'success' => false,
                'message' => $activate->get_error_message(),
            )
        );
    }

    wp_send_json_success(
        array(
            'success' => true,
            'message' => __( 'Plugin Successfully Activated', 'hasium' ),
        )
    );

}

/**
 * Required Plugin Activate
 *
 * @since 1.2.4
 */
function hasium_required_plugin_deactivate() {

    if ( ! current_user_can( 'install_plugins' ) || ! isset( $_POST['init'] ) || ! $_POST['init'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
        wp_send_json_error(
            array(
                'success' => false,
                'message' => __( 'No plugin specified', 'hasium' ),
            )
        );
    }

    $plugin_init = ( isset( $_POST['init'] ) ) ? esc_attr( $_POST['init'] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing

    $deactivate = deactivate_plugins( $plugin_init, '', false );

    if ( is_wp_error( $deactivate ) ) {
        wp_send_json_error(
            array(
                'success' => false,
                'message' => $deactivate->get_error_message(),
            )
        );
    }

    wp_send_json_success(
        array(
            'success' => true,
            'message' => __( 'Plugin Successfully Deactivated', 'hasium' ),
        )
    );

}

/**
     * Save User Data
     *
     * @since 1.0.0
     */
function save_user_data() {

    if ( ! current_user_can( 'manage_options' ) ) {
         return;
    }

    $type = sanitize_text_field( $_POST['type'] );
    update_option( 'hasium-wizard-set-up', $type );

    switch ( $type ) {
        case 'skip':
            $return = __( 'User skip wizard opt-in!', 'hasium');
            break;
        case 'opt-in':
            $return = hasium_call_remote_api();
            break;
        default:
            break;
    }

    wp_send_json_success( $return );

}

/**
 * Call remote api
 *
 * @since 1.0.0
 * @return string
 */
function hasium_call_remote_api(){
	global $wp_version, $wpdb;
    $theme_details = array();
	if ( $wp_version >= 3.4 ) {
		$active_theme                   = wp_get_theme();
		$theme_details['theme_name']    = strip_tags( $active_theme->name );
		$theme_details['theme_version'] = strip_tags( $active_theme->version );
		$theme_details['author_url']    = strip_tags( $active_theme->{'Author URI'} );
    }

	$plugin_stat_data                     = array();
	$plugin_stat_data['plugin_slug']      = 'auto-robot-lite';
	$plugin_stat_data['type']             = 'standard_edition';
	$plugin_stat_data['version_number']   = HASIUM_THEME_VERSION;
	$plugin_stat_data['event']            = 'activate';
	$plugin_stat_data['domain_url']       = site_url();
	$plugin_stat_data['wp_language']      = defined( 'WPLANG' ) && WPLANG ? WPLANG : get_locale();
	$plugin_stat_data['email']            = get_option( 'admin_email' );
	$plugin_stat_data['wp_version']       = $wp_version;
	$plugin_stat_data['php_version']      = sanitize_text_field( phpversion() );
	$plugin_stat_data['mysql_version']    = $wpdb->db_version();
	$plugin_stat_data['max_input_vars']   = ini_get( 'max_input_vars' );
	$plugin_stat_data['operating_system'] = PHP_OS . '  (' . PHP_INT_SIZE * 8 . ') BIT';
	$plugin_stat_data['php_memory_limit'] = ini_get( 'memory_limit' ) ? ini_get( 'memory_limit' ) : 'N/A';
	$plugin_stat_data['extensions']       = get_loaded_extensions();
	$plugin_stat_data['themes']           = $theme_details;
	$url                                  = WPHOBBY_STATS_URL . '/index.php?rest_route=/wphobby/v1/user/post/';
	$response                             = wp_safe_remote_post(
		$url, array(
			'method'      => 'POST',
			'timeout'     => 5,
			'redirection' => 5,
			'httpversion' => '1.0',
			'blocking'    => true,
			'headers'     => array(),
			'body'        => json_encode($plugin_stat_data),
			)
		);

	if ( ! is_wp_error( $response ) ) {
		return $response['body'];
	}
	die( 'success' );

}

// AJAX.
add_action( 'wp_ajax_hasium-sites-plugin-activate', 'hasium_required_plugin_activate' );
add_action( 'wp_ajax_hasium-sites-plugin-deactivate', 'hasium_required_plugin_deactivate' );
add_action( 'wp_ajax_hasium_save_user_data', 'save_user_data' );

