<?php if ( ! defined( 'ABSPATH' ) ) {exit;} // Cannot access pages directly.

/**
 * Premium functions and auto update.
 * 
 * @since 4.4.5
 */

class Codevz_Core_Premium {

	use Codevz_Core_Instance;

	public function __construct() {

		add_action( 'admin_init', [ $this, 'admin_init' ], 11 );
		add_action( 'after_setup_theme', [ $this, 'white_label_check' ] );
		add_action( 'customize_save_after', [ $this, 'white_label' ] );

	}

	/**
	 * Redirect to dashboard after theme activated.
	 * 
	 * @since 2.7.0
	 * @return -
	 */
	public function admin_init() {

		// Check automatic theme update on admin init.
		add_filter( 'site_transient_update_themes', [ $this, 'update' ] );
		add_filter( 'pre_set_site_transient_update_themes', [ $this, 'update' ] );

		// Plugin install notice.
		if ( ! Codevz_Core_Theme::$plugin ) {
			add_action( 'admin_notices', [ $this, 'admin_notice' ] );
		}

	}

	/**
	 * Add the admin notice for installing codevz plugin.
	 * 
	 * @since 4.7.2
	 * @return string
	 */
	public function admin_notice() {

		$color = Codevz_Core_Config::get( 'color_1' );

		$plugins = Codevz_Core_Config::get( 'plugins' );
		$plugin  = array_keys( $plugins );
		$plugin  = reset( $plugin );

		echo '<div class="codevz-admin-notice">';
		echo '<img src="' . esc_url( Codevz_Core_Theme::$url ) . 'assets/img/dashboard.png" />';

		$title = Codevz_Core_Theme::option( 'white_label_theme_name', apply_filters( 'codevz_config_name', false ) );

		echo '<h2>' . esc_html( Codevz_Core_Strings::get( 'thanks_install', $title ) );
		echo '<small>' . esc_html( Codevz_Core_Strings::get( 'thanks_install_plugin' ) ) . '</small>';
		echo '</h2>';

		echo '<a href="#" class="button button-primary">' . esc_html( Codevz_Core_Strings::get( 'thanks_install_plugin_b' ) ) . '</a>';
		echo '</div>';

		?>

			<script>

				jQuery( function( $ ) {

					$( 'body' ).on( 'click', '.codevz-admin-notice .button', function( e ) {

						var $this = $( this ),
							problem = function() {
								$this.removeClass( 'button disabled' ).find( '.xtra-loading' ).remove();
								$this.attr( 'href', '<?php echo esc_attr( $plugins[ $plugin ][ 'source' ] ); ?>' ).html( 'Click to download plugin and install it manually' );
							};

						$this.html( '<?php echo esc_html( Codevz_Core_Strings::get( 'thanks_installing_plugin' ) ); ?>' ).addClass( 'disabled' ).prepend( '<span class="xtra-loading"></span>' );

						$.ajax(
							{
								type: 'POST',
								url: ajaxurl,
								data: {
									action: 'codevz_wizard',
									type: 'plugin',
									name: '<?php echo esc_attr( $plugin ); ?>',
									nonce: '<?php echo esc_attr( wp_create_nonce( 'xtra-wizard' ) ); ?>'
								},
								success: function( obj ) {

									console.log( obj );

									if ( ( typeof obj === 'object' && obj.status === '200' ) || ( typeof obj === 'string' && obj.indexOf( '200' ) >= 0 ) ) {

										window.location = '<?php echo esc_url( admin_url( 'admin.php?page=theme-importer' ) ); ?>';

									} else {

										problem();

										return false;

									}

								},
								error: function( xhr, type, message ) {

									problem();

									console.log( xhr, type, message );

								}
							}
						);

						e.preventDefault();
						
					});

				});

			</script>

			<style>
				.codevz-admin-notice {
					position: relative;
					margin: 20px 0;
					padding: 20px 40px;
					display: flex;
					align-items: center;
					box-sizing: border-box;
					overflow: hidden;
					background: #fff;
					border-radius: 5px;
					max-width: 1140px;
					border: 1px solid <?php echo esc_html( $color ? $color : '#ffbb00' ); ?>;
					box-shadow: 0 0 40px rgba(17, 17, 17, 0.07)
				}
				.codevz-admin-notice img {
					width: 60px;
					height: 60px;
					margin-right: 40px
				}
				.rtl .codevz-admin-notice img {
					margin-left: 40px;
					margin-right: 0
				}
				.codevz-admin-notice h2 {
					font-size: 20px;
					font-weight: bold
				}
				.codevz-admin-notice small {
					display: block;
					opacity: .6;
					font-size: 14px;
					margin-top: 10px;
					font-weight: normal;
				}
				.codevz-admin-notice a {
					position: absolute;
					right: 40px;
					padding: 5px 20px !important;
					font-size: 14px !important
				}
				.rtl .codevz-admin-notice a {
					left: 40px;
					right: auto
				}
				.codevz-admin-notice .xtra-loading {
					position: relative;
					display: inline-block;
					width: 10px;
					height: 10px;
					vertical-align: middle;
					margin-right: 12px;
					border-radius: 100px;
					transform: translateZ(0);
					border: 2px solid rgba(40, 40, 40, 0.1);
					border-left: 2px solid #222222;
					animation: loader 1.1s infinite linear
				}
				.rtl .codevz-admin-notice .xtra-loading {
					margin-left: 12px;
					margin-right: 0
				}
				@keyframes loader {
					0% {transform: rotate(0deg)}
					100% {transform: rotate(360deg)}
				}
			</style>

		<?php

	}

	/**
	 * Theme automatic update
	 * 
	 * @since 2.7.0
	 */
	public static function update( $transient ) {

		// API.
		$api = apply_filters( 'codevz_config_api', false );

		// Get cached update data (JSON)
		$json = get_site_transient( 'codevz_versions_json' );

		// Fetch new data.
		if ( empty( $json['themes'] ) || isset( $_GET[ 'force-check' ] ) ) {

			$json = wp_remote_get( $api . 'versions.json' );
			$json = is_wp_error( $json ) ? [] : json_decode( wp_remote_retrieve_body( $json ), true );

	        // Store JSON for 6 hours.
	        set_site_transient( 'codevz_versions_json', $json, 21600 );

		}

        // Validate API response
        if ( empty( $json['themes'] ) ) {
            return $transient;
        }

        // Get installed themes list
        foreach( wp_get_themes() as $theme => $th ) {

            // Normalize theme slug
            $theme = sanitize_title_with_dashes( $theme );

            // Skip if theme is not in API data
            if ( empty( $json['themes'][ $theme ]['version'] ) ) {
                continue;
            }

            // Get current version & API version
            $new_version = $json['themes'][ $theme ]['version'];

            // Skip if already up to date
            if ( version_compare( $th->get( 'Version' ), $new_version, '>=' ) ) {
                continue;
            }

            // Build update.
            $transient->response[ $theme ] = [
                'theme'       => $theme,
                'new_version' => $new_version,
                'url'         => apply_filters( 'codevz_config_changelog_link', '#' ),
                'package'     => $api . ( ( $theme === 'xtra' ) ? $theme : 'themes/' . $theme ) . '.zip'
            ];

        }

        return $transient;

	}

	/**
	 * Check white labeled themes after update.
	 * 
	 * @return -
	 */
	public function white_label_check() {

		// White label after update.
		$white_label = Codevz_Core_Theme::option( 'white_label_theme_name' );

		if ( $white_label ) {

			$theme = wp_get_theme();

			if ( empty( $theme->parent() ) && $white_label !== $theme->get( 'Name' ) ) {

				self::white_label();

			}

		}

	}

	/**
	 * Theme white label
	 * 
	 * @since 3.2.0
	 */
	public static function white_label() {

		if ( ! Codevz_Core_Theme::$plugin ) {
			return;
		}

		$dir 			= trailingslashit( get_template_directory() );
		$basename 		= basename( $dir );

		$name 			= esc_html( Codevz_Core_Theme::option( 'white_label_theme_name' ) );
		$desc 			= esc_html( Codevz_Core_Theme::option( 'white_label_theme_description' ) );
		$link 			= esc_url( Codevz_Core_Theme::option( 'white_label_link', 'https://codevz.com/' ) );
		$author 		= esc_html( Codevz_Core_Theme::option( 'white_label_author', 'Codevz' ) );
		$author_link 	= $link;
		$slug 			= sanitize_title_with_dashes( $name );
		$screenshot 	= esc_url( Codevz_Core_Theme::option( 'white_label_theme_screenshot', Codevz_Core_Theme::$url . 'assets/img/screenshot.png' ) );

		$is_child_theme = is_child_theme();

		if ( empty( $name ) ) {
			return;
		}

		// WP_Filesystem.
		$wpfs = Codevz_Plus::wpfs();

		// Get theme version.
		$theme = wp_get_theme();
		$ver = empty( $theme->parent() ) ? $theme->get( 'Version' ) : $theme->parent()->Version;

		$information = '/*
	Theme Name:   ' . $name . '
	Theme URI:    ' . $link . '
	Description:  ' . $desc . '
	Version:      ' . $ver . '
	Author:       ' . $author . '
	Author URI:   ' . $author_link . '
	License:      GPLv2
	License URI:  http://gnu.org/licenses/gpl-2.0.html
	Tags:         one-column, two-columns, right-sidebar, custom-menu, rtl-language-support, sticky-post, translation-ready
*/

/*
	PLEASE DO NOT edit this file, if you want add custom CSS go to Theme Options > Additional CSS
*/';

		// Save style.css
		$result = $wpfs->put_contents( $dir . 'style.css', $information, FS_CHMOD_FILE );

		// Replace image.
		$new_image = $wpfs->get_contents( $screenshot );
		$result = $wpfs->put_contents( $dir . 'screenshot.png', $new_image, FS_CHMOD_FILE );
		$result = $wpfs->put_contents( str_replace( '/' . $basename . '/', '/' . $slug . '-child/screenshot.png', $dir ), $new_image, FS_CHMOD_FILE );

		// Rename folder name.
		$new_name = str_replace( '/' . $basename . '/', '/' . $slug . '/', $dir );
		rename( $dir, $new_name );

		// Check child theme.
		if ( $is_child_theme ) {

			// Child theme.
			$child = '/*
		Theme Name:	' . $name . ' Child
		Theme URI:	' . $link . '
		Description:' . $desc . '
		Author:		' . $author . '
		Author URI:	' . $author_link . '
		Template:	' . strtolower( $name ) . '
		Version:	1.0
	*/

	/*
		PLEASE DO NOT edit this file, if you want add custom CSS go to Theme Options > Additional CSS
	*/';

			$new_name = str_replace( '/' . $basename . '/', '/' . $slug . '-child/', $dir );
			$child_dir = str_replace( '/' . $basename . '/', '/' . $basename . '-child/', $dir );
			rename( $child_dir, $new_name );

			$result = $wpfs->put_contents( str_replace( '/' . $basename . '/', '/' . $slug . '-child/style.css', $dir ), $child, FS_CHMOD_FILE );

			// Activate child theme.
			switch_theme( $slug . '-child' );

		} else {

			// Theme activate.
			switch_theme( $slug );
		}

	}

}

Codevz_Core_Premium::instance();