<?php // admin related functions


/**
 * Get all master slider admin screen ids
 *
 * @return array
 */
function msp_get_screen_ids() {
	$the_screen_id = sanitize_title( MSWP_SLUG );

    return apply_filters( 'masterslider_admin_screen_ids', array(
    	'toplevel_page_' . $the_screen_id
    ) );
}




function msp_get_sliders_custom_css( $slider_status = 'published' ) {
	global $mspdb;
	$slider_status = sprintf( "status='%s'", $slider_status );
	$sliders_result = $mspdb->get_sliders( 0, 0, 'ID', 'DESC', $slider_status );

	$sliders_custom_css = array();

	if( $sliders_result ) {
		foreach ( $sliders_result as $slider ) {
			$sliders_custom_css[] = msp_get_slider_background_css( $slider['ID'] );
			$sliders_custom_css[] = $slider['custom_styles'];
		}
		// remove empty records from array
		$sliders_custom_css = array_filter( $sliders_custom_css );
	}

	return apply_filters( 'masterslider_get_sliders_custom_css', implode( "\n", $sliders_custom_css ), $sliders_custom_css, $sliders_result );
}


// get stored slider's custom css code from database
function msp_get_slider_custom_css( $slider_id ) {
	global $mspdb;
	$slider_custom_css = $mspdb->get_slider_field_val( $slider_id, 'custom_styles' );
	return $slider_custom_css ? $slider_custom_css : '';
}


function msp_get_slider_background_css( $slider_id ) {
	$slider_data = get_masterslider_parsed_data( $slider_id );

	$the_slider_bg  = empty( $slider_data['setting']['bg_color'] ) ? '' : $slider_data['setting']['bg_color'];
	$the_slider_bg .= empty( $slider_data['setting']['bg_image'] ) ? '' : sprintf( ' url( %s ) repeat top left', msp_get_the_absolute_media_url( $slider_data['setting']['bg_image'] ) );
	$the_slider_bg  = empty( $the_slider_bg ) ? '' : 'background:' . $the_slider_bg . ";";

	return empty( $the_slider_bg ) ? '' : sprintf( ".ms-parent-id-%d > .master-slider{ %s }", $slider_id, $the_slider_bg );
}


function msp_get_all_custom_css () {
	return apply_filters( 'masterslider_get_all_custom_css', msp_get_sliders_custom_css() );
}


/*-----------------------------------------------------------------------------------*/

/**
 * Get custom styles and store them in custom.css file or use inline css fallback
 * This function will be called by masterslider save handler
 *
 * @return void
 */
function msp_save_custom_styles() {

    $uploads   = wp_upload_dir();

	$css_dir   = apply_filters( 'masterslider_custom_css_dir', $uploads['basedir'] . '/' . MSWP_SLUG );
	$css_file  = $css_dir . '/custom.css';

    $css_terms = "/*
===============================================================
 # CUSTOM CSS
 - Please do not edit this file. this file is generated by server-side code
 - Every changes here will be overwritten
===============================================================*/\n
";
    // Get all custom css styles
    $css = msp_get_all_custom_css();

    /**
     * Initialize the WP_Filesystem
     */
    global $wp_filesystem;
    if ( empty( $wp_filesystem ) ) {
        require_once ( ABSPATH.'/wp-admin/includes/file.php' );
        WP_Filesystem();
    }

    if ( wp_mkdir_p( $css_dir ) && ! $wp_filesystem->put_contents( $css_file, $css_terms.$css, 0644 ) ) {
        // if the directory is not writable, try inline css fallback
        msp_update_option( 'custom_inline_style' , $css ); // save css rules as option to print as inline css
    } else {
    	$custom_css_ver = msp_get_option( 'masterslider_custom_css_ver', '1.0' );
    	$custom_css_ver = (float)$custom_css_ver + 0.1;
        msp_update_option( 'masterslider_custom_css_ver' , $custom_css_ver ); // disable inline css output
        msp_update_option( 'custom_inline_style' , '' );
    }

}


function msp_admin_notice_links_callback( $matches ){
    return sprintf( '<a href="%s">%s</a>', $matches[2], $matches[1] );
}

/**
 * Retrieves a URL using the HTTP GET method
 *
 * @return mixed|boolean    The body content
 */
function msp_remote_post( $url, $args = array() ) {
    $request = wp_remote_post( $url, $args );

    if ( ! is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) === 200 ) {
        return $request['body'];
    }
    return false;
}


/**
 * Display a notice for running the setup wizard
 *
 * @return void
 */
function msp_custom_admin_notice(){

    if( ! current_user_can( 'administrator' ) ){
        return;
    }
    echo MSP_Notices::get_instance()->get_notice( 'ms-notice-info-global' );
}
add_action( 'admin_notices', 'msp_custom_admin_notice' );


/**
 * Get total number of downloads by item slug
 *
 * @param  string $remote_url Remote URL to retrieve data from
 * @param  array  $body_args  Parameters to pass to the remote API address
 *
 * @return array|string       The API response
 */
function msp_get_averta_remote_api_data( $remote_url, $body_args ){
    $args = array(
        'timeout'    => ( ( defined('DOING_CRON') && DOING_CRON ) ? 30 : 10 ),
        'body'       => $body_args
    );

    $request = wp_remote_get( $remote_url, $args );

    if ( is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) !== 200 ) {
        return '...';
    }

    return $request['body'];
}


/**
 * A shortcode to retrieve data from API
 *
 * @return string
 */
function msp_api_stats_shortcode( $atts , $content = null ) {

    // parse attributes
    $atts = shortcode_atts(
        array(
            'branch'            => 'envato',
            'group'             => 'items',
            'cat'               => 'info',
            'action'            => 'stats',
            'item-id'           => '', // item id
            'item-name'         => '', // item name or slug
            'item-param'        => 'sales_number', // item param
            'format'            => '',
            'cache_in_minutes'  => 1440
        ),
        $atts,
        'averta-api'
    );

    if( empty( $atts['item-id'] ) && empty( $atts['item-name'] ) ){
        return 'item-id or item-name is required';
    }

    // sanitize the cache period
    $atts['cache_in_minutes'] = is_numeric( $atts['cache_in_minutes'] ) ? (int) $atts['cache_in_minutes'] : 180;

    // create a transient id base on the passed options
    $options_string_id = implode( '_' , $atts );

    if( $atts['cache_in_minutes'] > 0 && false !== ( $result = msp_get_transient( $options_string_id ) ) ){
        return $result;
    }

    // request data
    $remote_url   = 'https://api.averta.net/';
    $request_args = $atts;
    unset( $request_args['cache_in_minutes'] );

    $result = msp_get_averta_remote_api_data( $remote_url, $request_args );
    $result = apply_filters( 'auxin_averta_api_shortcode_result', $result, $atts );

    if( $atts['cache_in_minutes'] > 0 ){
        msp_set_transient( $options_string_id, $result, $atts['cache_in_minutes'] * MINUTE_IN_SECONDS );
    }

    return $result;
}

add_shortcode( 'msp-stats', 'msp_api_stats_shortcode' );


/**
 * Get the number of PRO users
 *
 * @return int
 */
function msp_get_pro_users_num(){
    return number_format_i18n( 35000 ). '+';
}


/**
 * Prints Pretty human-readable information about a variable (developer debug tool)
 * @param  mixed             The expression to be printed.
 * @param  boolean $dump     Whether to dump information about a variable or not
 * @param  boolean $return   When this parameter is set to TRUE, it will return the information rather than print it.
 * @return bool              When the return parameter is TRUE, this function will return a string. Otherwise, the return value is TRUE.
 */
if ( ! function_exists( 'axpp' ) ) {

	function axpp ( $expression, $dump = false, $return = false ) {
		if ( $return ) {
			return '<pre>' . print_r( $expression , true ) . '</pre>';
		} elseif ( $dump ) {
			echo '<pre>'; var_dump( $expression ); echo '</pre>';
		} else {
			echo '<pre style="margin-left:170px;">'; print_r ( $expression ); echo '</pre>';
		}
		return true;
	}

}

/**
 * Get clean css
 *
 * @param string $css
 * @return string
 */
function msp_get_clean_css( $css ) {
    if ( empty( $css ) ) {
        return '';
    }

    // Comprehensive regex to filter out various XSS vectors 
    $pattern = '/(expression|javascript|vbscript|moz-binding|@import|@charset|data:)/i'; 
    $css = preg_replace($pattern, '', $css);
    return strip_tags( $css );
}