<?php

    /*
    *
    *   Customizer Output
    *   ------------------------------------------------
    *   Swift Framework
    *   Copyright Swift Ideas 2015 - http://www.swiftideas.com
    *   @since v1.0.0
    *   
    *
    *   uplift_custom_css_debug_mode()
    *	uplift_get_css_output_method()
    *	uplift_get_custom_css_filename()
    *	uplift_custom_css_enqueue()
    *	uplift_custom_css_enqueue_fs()
    *	uplift_custom_css_enqueue_ajax()
    *	uplift_custom_css_ajax_output()
    *	uplift_custom_css_head_output()
    *	uplift_get_custom_css()
    *	uplift_get_custom_css_transient_key()
    *	uplift_get_cached_css()
    *	uplift_set_cached_css()
    *	uplift_delete_cached_css()
    *	uplift_generate_custom_css()
    *	uplift_save_custom_css_to_fs()
    *
    */    
    
    
    /**
    * Clear custom css cache on theme options, customizer save, and theme update/change
    *
    */
    add_action( 'redux/options/sf_uplift_options/saved', 'uplift_delete_cached_css' );
    add_action( 'customize_save_after', 'uplift_delete_cached_css' );
    add_action( 'after_switch_theme', 'uplift_delete_cached_css' );
    add_action( 'delete_site_transient_update_themes', 'uplift_delete_cached_css' );
    
    /**
    * Debug mode for custom css output
    *
    * return @bool
    */
    function uplift_custom_css_debug_mode() {
        return ( defined( 'UPLIFT_CUSTOM_CSS_DEBUG' ) && UPLIFT_CUSTOM_CSS_DEBUG === true ) || isset( $_GET['uplift_custom_css_nocache'] );
    }
    
    
    /**
    * Get the css output method from theme options
    *
    * return @string
    */
    function uplift_get_css_output_method() {
    	$uplift_options = uplift_get_theme_opts();
    	$styles_output = $uplift_options['dynamic_styles_output'];
    	
        return isset( $styles_output ) ? $styles_output : 'fs';
    }
    
    
    /**
    * Get the filename for the custom css file
    *
    * return @string
    *
    */
    function uplift_get_custom_css_filename() {
        return apply_filters( "uplift_custom_css_filename", 'uplift-custom' ) . '.css';
    }
    
    
    /**
    * Enqueue the custom css file if set to fs or ajax output
    */
    function uplift_custom_css_enqueue() {
    	if ( uplift_get_css_output_method() == 'fs' ) {
            uplift_custom_css_enqueue_fs();
        }

        if ( uplift_get_css_output_method() == 'ajax' ) {
            uplift_custom_css_enqueue_ajax();
        }
    }
    add_action( 'wp_enqueue_scripts', 'uplift_custom_css_enqueue' );

	
	/**
	* Enqueue the custom css from the filesystem
	*/
    function uplift_custom_css_enqueue_fs() {
        
        $upload_dir = wp_upload_dir();

        $filename = uplift_get_custom_css_filename();

        $filepath = trailingslashit( $upload_dir['basedir'] ) . 'swiftframework/' . $filename;

        if ( ! is_file( $filepath ) ) {

            // regenerate the CSS and save to filesystem
            uplift_generate_custom_css();

        }

        // file should now exist
        if ( is_file( $filepath ) ) {

            $css_url = trailingslashit( $upload_dir['baseurl'] ) . 'swiftframework/' . $filename;

            $protocol = is_ssl() ? 'https://' : 'http://';

            // ensure we're using the correct protocol
            $css_url = str_replace( array( "http://", "https://" ), $protocol, $css_url );

            wp_enqueue_style( 'uplift-custom', $css_url, false, substr( md5( filemtime( $filepath ) ), 0, 6 ) );

        } else {

            // enqueue via AJAX for this request
            uplift_custom_css_enqueue_ajax();

        }
    }
    
    
    /**
    * Enqueue the custom css via AJAX
    */
    function uplift_custom_css_enqueue_ajax() {
        wp_enqueue_style( 'uplift-custom', admin_url('admin-ajax.php') . '?action=uplift_custom_css', false, NULL );    
    }

    
    /**
    * Generate the custom css for ajax output
    */
    function uplift_custom_css_ajax_output() {

        header("Content-type: text/css; charset: UTF-8");

        echo uplift_get_custom_css();

        wp_die();
    }    
    add_action( 'wp_ajax_uplift_custom_css', 'uplift_custom_css_ajax_output' );
    add_action( 'wp_ajax_nopriv_uplift_custom_css', 'uplift_custom_css_ajax_output' );
	
	
	/**
	* Output the custom css to the head tag
	*/
	function uplift_custom_css_head_output() {

        if ( uplift_get_css_output_method() == 'head' ) {

            $css = uplift_get_custom_css();

            echo '<style type="text/css">' . str_replace( array( "  ", "\n" ), '', $css ) . "</style>\n";

        }

    }
	add_action( 'wp_head', 'uplift_custom_css_head_output', 9998 );
	
	
	/**
	* Get the custom css if cached, or generate it
	*/
	function uplift_get_custom_css() {

        if ( ( $css = uplift_get_cached_css() ) && ! uplift_custom_css_debug_mode() ) {
			
            return $css;

        } else {

            return uplift_generate_custom_css();

        }

    }
    
    
    /**
    * Get the custom css transient key
    */
    function uplift_get_custom_css_transient_key() {
        return apply_filters( 'uplift_custom_css_transient_key', 'uplift-custom-css' );
    }
    
    
    /**
    * Get the cached css
    */
    function uplift_get_cached_css() {
    	return get_transient( uplift_get_custom_css_transient_key() );    	
    }
    
    
    /**
    * Set the cached css
    */
    function uplift_set_cached_css( $css ) {
        set_transient( uplift_get_custom_css_transient_key(), $css, 0 );
    }
    
    
    /**
    * Delete the cached css
    */
    function uplift_delete_cached_css() {
        global $wp_filesystem;

        if ( ! $wp_filesystem ) {
            require_once( ABSPATH . 'wp-admin/includes/file.php' );
        }

        $upload_dir = wp_upload_dir();
        $filename = uplift_get_custom_css_filename();
        $dir = trailingslashit( $upload_dir['basedir'] ) . 'swiftframework/';

        WP_Filesystem( false, $upload_dir['basedir'], true );
        $wp_filesystem->rmdir( $dir, true );

        delete_transient( uplift_get_custom_css_transient_key() );
        
        do_action( 'uplift_after_delete_cached_css' );

        return true;
    }
    
    
    /**
    * Generate the custom css
    */
    function uplift_generate_custom_css() {
		$css = uplift_custom_styles_output();
		
		if ( strlen( $css ) ) {
		
		    $css .= "/** " . date('l jS \of F Y h:i:s A') . " **/";
		
		    uplift_set_cached_css( $css );
		
		    if ( uplift_get_css_output_method() == 'fs' ) {
		        uplift_save_custom_css_to_fs( $css );
		    }
		
		}
		
		return $css;
    }
    
    
    /**
    * Save custom css to file system
    */
    function uplift_save_custom_css_to_fs( $css ) {
	    global $wp_filesystem;
	
	    if ( ! $wp_filesystem ) {
	        require_once( ABSPATH . 'wp-admin/includes/file.php' );
	    }
	
	    $upload_dir = wp_upload_dir();
	    $filename = uplift_get_custom_css_filename();
	    $dir = trailingslashit( $upload_dir['basedir'] ) . 'swiftframework/';
	
	    WP_Filesystem( false, $upload_dir['basedir'], true );
	    wp_mkdir_p( $dir );
	
	    if ( ! $wp_filesystem->put_contents( $dir . $filename, $css ) ) {
	
	        // If the file write fails, update the theme option to ajax to prevent repeat fails
	        $settings = get_option( 'sf_uplift_options' );
	        $settings['dynamic_styles_output'] = 'ajax';
	        update_option( 'sf_uplift_options', $settings );
	
	    }
    }
	