<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://elicus.com/
 * @since      1.0.0
 *
 * @package    Divi_Layouts_Extended
 * @subpackage Divi_Layouts_Extended/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Divi_Layouts_Extended
 * @subpackage Divi_Layouts_Extended/admin
 * @author     Elicus <hello@elicus.com>
 */
class Divi_Layouts_Extended_Admin {

	/**
	 * The name of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The name of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * Setting page title.
	 * 
	 * @since 	 1.0.0
	 * @access 	 private
	 * @var 	 string
	 */
	private $page_title;

	/**
	 * Admin menu title.
	 *
	 * @since 	 1.0.0
	 * @access   private
	 * @var 	 string
	 */
	private $menu_title;

	/**
	 * Settings page slug.
	 *
	 * @since 	 1.0.0
	 * @access   private
	 * @var 	 string
	 */
	private $menu_slug;

	/**
	 * Plugin option page hook.
	 *
	 * @since 	 1.0.0
	 * @access   private
	 * @var 	 string
	 */
	private $hook_suffix;

	/**
	 * Panel Class Object.
	 *
	 * @since 	 1.0.0
	 * @access   private
	 * @var 	 Object
	 */
	private $panel;

	/**
     * Plugin Basename.
     *
     * @since 	 1.0.0
     * @access   private
     * @var 	 string
     */
	private $plugin_basename;

	/**
     * Metadata Url.
     *
     * @since 	 1.0.0
     * @access   private
     * @var 	 string
     */
	private $metadata_url;

	/**
     * Plugin Upgrade Transient.
     *
     * @since 	 1.0.0
     * @access   private
     * @var 	 string
     */
	private $upgrade_transient;	

	/**
     * Last checked update.
     *
     * @since 	 1.0.0
     * @access   private
     * @var 	 string
     */
	private $last_checked;

	/**
     * Last checked update option.
     *
     * @since 	 1.0.0
     * @access   private
     * @var 	 string
     */
	private $last_checked_option;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {

		$this->plugin_name 			= $plugin_name;
		$this->version 				= $version;
		$this->plugin_basename		= DIVI_LAYOUTS_EXTENDED_BASENAME;
        $this->metadata_url 		= 'http://cdn.elicus.com';
        $this->upgrade_transient    = 'upgrade_divi_layouts_extended';
        $this->last_checked_option  = 'divi_layouts_extended_last_checked';
        $this->last_checked 		= get_option( $this->last_checked_option, 0 );
		$this->menu_slug    		= $this->plugin_name;
		$this->page_title 			= esc_html__( 'Divi Layouts Extended', 'divi-layouts-extended' );
		$this->menu_title 			= esc_html__( 'Divi Layouts Extended', 'divi-layouts-extended' );
		$this->panel  				= new Divi_Layouts_Extended_Panel( $this->page_title );
	}

	/**
	 * Register the admin menu for the plugin.
	 *
	 * @since    1.0.0
	 */
	public function admin_menu() {
		$this->hook_suffix = add_menu_page( 
			$this->page_title,
			$this->menu_title,
			'manage_options', $this->menu_slug,
			array( $this->panel, 'panel_page' ),
			DIVI_LAYOUTS_EXTENDED_PATH . 'admin/panel/assets/de-admin-menu-icon.svg',
			85
		);
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles( $hook_suffix ) {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Divi_Layouts_Extended_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Divi_Layouts_Extended_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */
		if ( $hook_suffix == $this->hook_suffix ) {
			wp_enqueue_style( 'divi-layouts-extended-panel-style', plugin_dir_url( __FILE__ ) . 'panel/styles/panel.min.css', array(), $this->version, 'all' );
		}

	}

	/**
	 * Print admin styles
	 * 
	 * @since    2.8.0
	 */
	public function print_admin_styles() {
		echo '<style>
			#adminmenu li.toplevel_page_divi-layouts-extended:hover a:not(.current) img,
			#adminmenu li>a.toplevel_page_divi-layouts-extended:focus a:not(.current) img{
				opacity: 1;
				filter: invert(73%) sepia(26%) saturate(1028%) hue-rotate(92deg) brightness(170%) contrast(90%);
			}
			#adminmenu li.toplevel_page_divi-layouts-extended a.current div.wp-menu-image img{
				opacity: 1;
			}
		</style>';
	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts( $hook_suffix ) {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Divi_Layouts_Extended_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Divi_Layouts_Extended_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		if ( $hook_suffix == $this->hook_suffix ) {
			wp_enqueue_script( 'elicus-images-loaded-script', plugin_dir_url( __FILE__ ) . "panel/scripts/imagesloaded.pkgd.min.js", array('jquery'), '4.1.4', true );
			wp_enqueue_script( 'elicus-isotope-script', plugin_dir_url( __FILE__ ) . 'panel/scripts/isotope.pkgd.min.js', array( 'jquery' ), '3.0.6', true );
			wp_enqueue_script( 'twbs-pagination-script', plugin_dir_url( __FILE__ ) . 'panel/scripts/twbspagination.min.js', array( 'jquery' ), '1.4.2', true );
			wp_register_script( 'popper', plugin_dir_url( __FILE__ ) . 'panel/scripts/popper.min.js', array(), '2.11.8', false );
			wp_register_script( 'tippy', plugin_dir_url( __FILE__ ) . 'panel/scripts/tippy.min.js', array(), '6.3.7', false );
			wp_enqueue_script( 'divi-layouts-extended-panel-script', plugin_dir_url( __FILE__ ) . 'panel/scripts/panel.min.js', array( 'jquery', 'popper', 'tippy' ), $this->version, false );
			wp_localize_script(
                'divi-layouts-extended-panel-script',
                'divi_layouts_extended_panel_ajax_object',
                array(
                    'ajaxurl'   => admin_url( 'admin-ajax.php' ),
                    'ajaxnonce' => wp_create_nonce( 'divi-layouts-extended-panel-nonce' ),
                )
            );
		}

	}

	/**
	 * Import the layout in Divi Library.
	 *
	 * @since    1.0.0
	 */
	public function import_layout() {
        
        // verify nonce.
        if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'divi-layouts-extended-panel-nonce' ) ) {
            echo '';
            exit;
        }

        $defaults = array(
			'type'  	=> '',
			'subtype'   => '',
			'name'      => '',
		);

        // phpcs:ignore ET.Sniffs.ValidatedSanitizedInput.InputNotSanitized
		$params = isset( $_POST['params'] ) ? wp_unslash( $_POST['params'] ) : array();

		if ( empty( $params ) ) {
			echo '';
			exit;
		}

		$params = wp_parse_args( $params, $defaults );

		foreach ( $defaults as $key => $default ) {
			// phpcs:ignore ET.Sniffs.ValidatedSanitizedInput.InputNotSanitized
			${$key} = sanitize_text_field( et_()->array_get( $params, $key, $default ) );
		}

		if ( empty( $type ) || empty( $name ) ) {
			echo '';
			exit;
		}

		global $wp_version;
		$params = array(
			'user-agent' => 'WordPress/' . $wp_version . ';' . get_bloginfo('url'),
			'body'       => array(
				'action'    => sanitize_text_field( 'download' ),
				'slug'      => sanitize_text_field( 'divi-layouts-extended' ),
				'type'		=> sanitize_text_field( $type ),
				'subtype'	=> sanitize_text_field( $subtype ),
				'name'		=> sanitize_text_field( $name ),
				'url'       => rawurlencode( get_bloginfo('url') ),
			)
		);

		$request = wp_safe_remote_post( 'https://cdn.diviextended.com/', $params );
		if ( ! is_wp_error( $request ) && ! empty( $request['body'] ) ) {
			$response = json_decode( wp_remote_retrieve_body( $request ), true );
			if ( ! empty( $response ) ) {
				require_once 'panel/portability.php';
				$import = new Divi_Layouts_Extended_Import();

				// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
				echo $import->import_post( $response );
				exit;
			}
		}

		echo false;
		exit;
	}

	/**
	 * Get the layouts for pagination and sorting.
	 *
	 * @since    1.0.0
	 */
	public function get_layouts() {
		
		// verify nonce.
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'divi-layouts-extended-panel-nonce' ) ) {
			echo '';
			exit;
		}

		$defaults = array(
			'type'  			=> '',
			'subtype'   		=> '',
			'search'			=> '',
			'sortby'			=> 'popular',
			'page'      		=> '1',
			'total_pages'		=> '1',
		);

		// phpcs:ignore ET.Sniffs.ValidatedSanitizedInput.InputNotSanitized
		$params = isset( $_POST['params'] ) ? wp_unslash( $_POST['params'] ) : array();

		if ( empty( $params ) ) {
			echo '';
			exit;
		}

		$params = wp_parse_args( $params, $defaults );
		foreach ( $defaults as $key => $default ) {
			// phpcs:ignore ET.Sniffs.ValidatedSanitizedInput.InputNotSanitized
			${$key} = sanitize_text_field( et_()->array_get( $params, $key, $default ) );
		}

		if ( empty( $type ) || empty( $subtype ) ) {
			echo '';
			exit;
		}

		$layouts = $this->panel->get_layouts( $type, $subtype, $search, $sortby, $page, $total_pages );

		// Default heading.
		$layouts['heading'] = sprintf( esc_html__( '%s', 'divi-layouts-extended' ), ucwords( str_replace( '-', ' ', $subtype ) ) );

		// Add title or heading of section.
		if ( ! empty( $search ) ) {
			$layouts['heading'] = sprintf( esc_html__( 'Search Result for: %s', 'divi-layouts-extended' ), $search );
		}

		if ( ! empty( $layouts ) ) {
			wp_send_json( $layouts );
			exit;
		}
		echo '';
		exit;
	}

	/**
	 * Check for updates.
	 *
	 * @since    1.0.0
	 */
	public function check_update( $transient ) {

		// trying to get from cache first, to disable cache comment 10,20,21,22,24
		$response = get_transient( $this->upgrade_transient );
		
		if ( ! $response && isset( $transient->response[$this->plugin_basename] ) ) {
			unset( $transient->response[$this->plugin_basename] );
			return $transient;
		}

		if ( ! $response && empty( $transient->checked ) ) {
            return $transient;
        }

		if ( is_admin() &&
			current_user_can( 'update_plugins' ) && 
			( 
				( false === $response && ( ( time() - $this->last_checked ) > 43200 ) ) || 
			  	( false === $response && isset( $_REQUEST['force-check'] ) && $_REQUEST['force-check'] == '1' )
			)
		) {
			global $wp_version;
     		$params	= array(
                		'user-agent' => 'WordPress/' . $wp_version . ';' . get_bloginfo('url'),
                       	'body'       => array(
                            'action'	=> esc_attr( 'update' ),
                            'slug'		=> esc_attr( $this->plugin_name ),
                        	'blog'		=> get_bloginfo( 'url' ),
                        )
        			);
            $request    = wp_safe_remote_post( $this->metadata_url, $params );
          	
	 		if ( ! is_wp_error( $request ) && ! empty( $request['body'] ) ) {
	 			$response = json_decode( wp_remote_retrieve_body( $request ) );
				if ( version_compare( $this->version, $response->current_version, '<' ) ) {	
					set_transient( $this->upgrade_transient, $response, 43200 ); // 12 hours cache
				}
			}

			update_option( $this->last_checked_option, time() );
			$this->last_checked = time();
		}
	 
	 	
		if ( $response && current_user_can( 'update_plugins' ) ) {
			if ( version_compare( $this->version, $response->current_version, '<' ) ) {
				$metadata 			= unserialize( $response->update_metadata );
				$obj 				= new stdClass();
				$obj->name 			= $metadata->name;
				$obj->slug 			= $this->plugin_name;
				$obj->plugin 		= $this->plugin_basename;
				$obj->new_version 	= $metadata->version;
				$obj->tested 		= $metadata->tested;
				$obj->icons         = array(
                   '1x' => 'https://diviextended.com/wp-content/uploads/2024/02/divi-extended-logo-green-1x.png',
                   '2x' => 'https://diviextended.com/wp-content/uploads/2024/02/divi-extended-logo-green-2x.png',
                );
				$obj->package 		= $metadata->download_url . '?slug=' . esc_attr( $this->plugin_name ) . '&blog_url=' . get_bloginfo( 'url' );
	           	
	           	$transient->response[$obj->plugin] = $obj;
			}
		}

        return $transient;
	}

	/**
	 * Display metadata in popup.
	 *
	 * @since    1.0.0
	 */
	public function check_info( $res, $action, $args ) {
		
		// do nothing if this is not about getting plugin information
		if ( 'plugin_information' !== $action ) {
			return $res;
		}
	 
		// do nothing if it is not our plugin	
		if ( $this->plugin_name !== $args->slug ) {
			return $res;
		}
	 
		$response = get_transient( $this->upgrade_transient );
	 	
		if ( $response && current_user_can( 'update_plugins' ) ) {
			if ( version_compare( $this->version, $response->current_version, '<' ) ) {
				$metadata 					= unserialize( $response->update_metadata );
				$metadata->download_link 	= $metadata->download_url . '?slug=' . esc_attr( $this->plugin_name ) . '&blog_url=' . get_bloginfo( 'url' );
	        	return $metadata;
	        }
		}
	 
		return $res;
	}

	/**
	 * Delete transient of update completed
	 *
	 * @since    1.0.0
	 */
	public function update_complete( $upgrader_object, $options ) {

		if ( 'update' === $options['action'] && 'plugin' === $options['type'] ) {
			// just clean the cache when new plugin version is installed
			foreach( $options['plugins'] as $plugin ) {
          		if ( $plugin === $this->plugin_basename ) {
					delete_transient( $this->upgrade_transient );
					update_option( $this->last_checked_option, time() );
					$this->last_checked = time();
				}
			}
		}
	
	}
}
