<?php
class Youzify_Admin {

	function __construct() {

        if ( ! defined( 'YOUZIFY_STORE_URL' ) ) {
            define( 'YOUZIFY_STORE_URL', 'https://youzify.com' );
        }

        if ( ! defined( 'YOUZIFY_PANEL_URL' ) ) {
            define( 'YOUZIFY_PANEL_URL', plugin_dir_url( __FILE__ ) );
        }

        if ( ! defined( 'YOUZIFY_PANEL_PATH' ) ) {
            define( 'YOUZIFY_PANEL_PATH', plugin_dir_path( __FILE__ ) );
        }

		// Init Admin Area
		add_action( 'admin_menu', array( $this, 'admin_menu' ) );

	    if ( isset( $_GET['page'] ) && $_GET['page'] == 'youzify-extensions-settings' ) {
			add_action( 'admin_print_styles', array( $this, 'admin_styles' ) );
			add_action( 'admin_enqueue_scripts', array( $this, 'admin_scripts' ) );
		}

		// Save Settings
		add_action( 'wp_ajax_youzify_admin_data_save',  array( $this, 'save_settings' ) );

		// Reset Settings
		add_action( 'wp_ajax_youzify_reset_settings',  array( $this, 'reset_settings' ) );

		// Add youzify Plugin Admin Pages.
		add_action( 'wp_ajax_youzify_save_addon_key_license', array( $this, 'save_addon_key_license' ) );

	}

	/**
	 * Add Youzify Admin Pages.
	 */
	function admin_menu() {

		// Show youzify Panel to Admin's Only.
		if ( ! current_user_can( 'manage_options' ) && ! apply_filters( 'youzify_show_youzify_panel', false ) ) {
			return false;
		}

	    // Add youzify Plugin Admin Page.
	    add_submenu_page(
	    	'options-general.php',
	    	__( 'BuddyPress Extensions', 'youzify-social-share' ),
	    	__( 'BuddyPress Extensions', 'youzify-social-share' ),
	    	'administrator',
	    	'youzify-extensions-settings',
	    	array( $this, 'settings' )
	    );

	}

	/**
	 * Admin Scripts.
	 */
	function admin_scripts() {

		// Set Up Variables
		$jquery = array( 'jquery' );

    	// Admin Panel Script
    	wp_enqueue_script( 'klabs-settings', YOUZIFY_PANEL_URL . 'assets/js/youzify-settings.min.js', $jquery, false, true );
        wp_enqueue_script( 'klabs-panel', YOUZIFY_PANEL_URL . 'assets/js/klabs-panel.min.js', $jquery, false, true );
        wp_register_script( 'youzify-functions', YOUZIFY_PANEL_URL . 'assets/js/youzify-functions.min.js', $jquery, false, true );
        wp_localize_script( 'klabs-panel', 'YOUZIFY', array(
            'reset_error' => __( 'An error occurred while resetting the options!', 'youzify-social-share' ),
            'banner_url'  => __( 'Banner URL not working!', 'youzify-social-share' ),
			'name_exist' => __( 'This name already exists!', 'youzify-social-share' ),
			'required_fields' => __( 'All fields are required!', 'youzify-social-share' ),
			'save_changes' => __( 'Save Changes', 'youzify-social-share' ),
            'default_img' => YOUZIFY_PANEL_URL . 'assets/images/default-img.png',
            'ajax_url'    => admin_url( 'admin-ajax.php' ),
			'done' => __( 'Save', 'youzify-social-share' )
        ) );

        // Load Color Picker
        wp_enqueue_script( 'wp-color-picker' );
		wp_enqueue_style( 'wp-color-picker' );

        // Load Tags Script
        wp_enqueue_script( 'klabs-tags', YOUZIFY_PANEL_URL . 'assets/js/klabs-tags.min.js', array( 'jquery' ), false, true );

        // Media
        wp_enqueue_media();

	}

	/**
	 * Panel Styles.
	 */
	function admin_styles() {

    	// Load Settings Style
	    wp_enqueue_style( 'klabs-panel', YOUZIFY_PANEL_URL . 'assets/css/klabs-panel.min.css', array(), false );

        // Load Admin Panel Style
	    wp_enqueue_style( 'klabs-admin', YOUZIFY_PANEL_URL . 'assets/css/klabs-admin.min.css', array(), false );

        // Load Google Fonts
        wp_enqueue_style( 'klabs-fonts', 'https://fonts.googleapis.com/css?family=Open+Sans:100,400,600', array(), false );

		// Loading Font Awesome.
    	wp_enqueue_style( 'klabs-icons', YOUZIFY_PANEL_URL . 'assets/css/all.min.css', array(), false );

	    // Icon Picker.
	    wp_enqueue_style( 'klabs-iconpicker', YOUZIFY_PANEL_URL . 'assets/css/klabs-icon-picker.min.css', array(), false );

	    // IconPicker Script
	    wp_enqueue_script( 'klabs-iconpicker', YOUZIFY_PANEL_URL . 'assets/js/klabs-icon-picker.min.js', array( 'jquery' ), false, true );

		if ( $_GET['page']  == 'youzify-extensions-settings' ) {
		    wp_enqueue_script( 'youzify-automatic-updates', YOUZIFY_PANEL_URL . 'assets/js/youzify-automatic-updates.js', array(), false );
		    wp_localize_script( 'youzify-automatic-updates', 'Youzify_Automatic_Updates', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
		}

	}

	/**
	 * # General Settings.
	 */
	function settings() {

		// Filter.
		$tabs = apply_filters( 'youzify_extensions_settings_menu', array() );

		// Get Settings.
		$this->get_settings( $tabs, 'extensions-settings' );

	}

	/**
	 * Get Page Settings
	 */
	function get_settings( $tabs, $page = false ) {

		// Include Widget Class.
        include YOUZIFY_PANEL_PATH . 'youzify-fields.php';

		global $Youzify_Settings;

		// Get Tabs Keys
		$settings_tabs = array_keys( $tabs );

		// Get Current Tab.
		$current_tab = isset( $_GET['tab'] ) && in_array( $_GET['tab'], $settings_tabs ) ? (string) $_GET['tab'] : (string) key( $tabs );

		// Append Class to the active tab.
		$tabs[ $current_tab ]['class'] = 'youzify-active-tab';

		// Get Tab Data.
		$tab = $tabs[ $current_tab ];

		// Get Tab Function Name.
		$settings_function = isset( $tab['function'] ) ?  $tab['function']: null;

		ob_start();

        $Youzify_Settings->get_field(
        	array(
	            'type'  => 'start',
	            'id'    => $tab['id'],
	            'icon'  => $tab['icon'],
	            'title' => $tab['title'],
       		)
        );


        $file = YOUZIFY_PANEL_URL . 'a/' . $page . '/youzify-settings-' . $current_tab . '.php';

        if ( file_exists( $file ) ) {
			include $file;
        }

		$settings_function();

        $Youzify_Settings->get_field( array( 'type' => 'end' ) );

		$content = ob_get_contents();

		ob_end_clean();

		// Print Panel
		$this->admin_panel( $tabs, $content );

	}

	/**
	 * # youzify Panel Form.
	 */
	function admin_panel( $menu = null, $settings = null ) {

	?>

	<?php do_action( 'youzify_admin_before_form' ); ?>

	<div id="ukai-panel" class="<?php echo get_option( 'youzify_panel_scheme', 'youzify-yellow-scheme' ); ?>">

	    <div class="uk-sidebar">
	        <div class="ukai-logo">
	        	<img src="<?php echo YOUZIFY_PANEL_URL . 'assets/images/logo.png'; ?>" alt="">
	        </div>
	        <a class="youzify-tab-extensions" href="<?php echo apply_filters( 'youzify_panel_extensions_page_link', 'https://youzify.com' ); ?>" target="_blank"><i class="fas fa-plug"></i><?php _e( 'Extensions <span class="new">New</span>') ?></a>
			<div class="kl-responsive-menu">
				<?php _e( 'Menu', 'youzify-social-share' ); ?>
				<input class="kl-toggle-btn" type="checkbox" id="kl-toggle-btn">
	  			<label class="kl-toggle-icon" for="kl-toggle-btn"></i><span class="kl-icon-bars"></span></label>
			</div>

			<!-- Panel Menu. -->
	        <?php $this->get_menu( $menu ); ?>
	    </div>

	    <div id="ukai-panel-content" class="ukai-panel">
	        <div class="youzify-main-content"><?php echo $settings; ?></div>
	    </div>

	</div>

	<div class="youzify-md-overlay"></div>

	<!-- Reset Dialog -->
	<?php $this->popup_dialog( 'reset_tab' ); ?>

	<!-- Errors Dialog -->
	<?php $this->popup_dialog( 'error' ); ?>

	<?php do_action( 'youzify_admin_after_form' ); ?>

    <div class="youzify-form-msg">
        <div id="youzify-action-message"></div>
        <div id="youzify-wait-message">
            <div class="youzify_msg wait_msg">
                <div class="youzify-msg-icon">
                    <i class="fas fa-spinner fa-spin"></i>
                </div>
                <span><?php _e( 'Please wait...', 'youzify-social-share' ); ?></span>
            </div>
        </div>
    </div>
	<?php if ( 'on' == get_option( 'youzify_enable_panel_fixed_save_btn', 'on' ) ) : ?>
		<div class="youzify-fixed-save-btn"><i class="fas fa-save"></i></div>
	<?php endif; ?>

	<?php

	}

	/**
	 * Popup Dialog Message
	 */
	function popup_dialog( $type = null ) {

		// Get Dialog Class.
		$form_class = ( ! empty( $type ) && $type == 'reset_tab' ) ? 'alert' : 'error';

		// Get Dialog Name.
		$form_type  = ( ! empty( $type ) && $type == 'reset_tab' ) ? $type : 'error';

    ?>

    <div id="uk_popup_<?php echo $form_type; ?>" class="uk-popup uk-<?php echo $form_class; ?>-popup" style="display: none">
        <div class="uk-popup-container">
            <div class="uk-popup-msg"><?php

				if ( 'reset_tab' == $form_type ) : ?>

                <span class="dashicons dashicons-warning"></span>
                <h3><?php _e( 'Are you sure you want to do this ?', 'youzify-social-share' ); ?></h3>
                <p><?php _e( 'Be careful! This will reset all the current tab settings.', 'youzify-social-share' ); ?></p>

                <?php elseif ( 'error' == $form_type ) : ?>

                <i class="fas fa-exclamation-triangle"></i>
                <h3><?php _e( 'Oops!', 'youzify-social-share' ); ?></h3>
                <div class="uk-msg-content"></div>

            <?php endif; ?>
            </div>

            <ul class="uk-buttons"><?php

				if ( 'reset_tab' == $form_type ) : ?>
                    <li>
                        <a class="uk-confirm-popup youzify-confirm-reset" data-reset="tab"><?php _e( 'confirm', 'youzify-social-share' ); ?></a>
                    </li>
                <?php endif; ?>

                <li><a class="uk-close-popup"><?php echo ( 'error' == $form_type ) ? __( 'Got it!', 'youzify-social-share' ) : __( 'cancel', 'youzify-social-share' ); ?></a></li>

                <?php

             ?></ul>
            <i class="fas fa-times uk-popup-close"></i>
        </div>
    </div>

    <?php
	}

	/**
	 * Get Menu Content.
	 */
	function get_menu( $tabs_list ) {

	    // Build the redirect URL.
	    $current_url = is_ssl() ? 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']: 'http://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

		echo '<ul class="youzify-panel-menu youzify-form-menu">';

		foreach ( $tabs_list as $key => $tab ) {

			if ( isset( $tab['hide_menu'] ) && $tab['hide_menu'] === true ) {
				continue;
			}

 			// Add Tab ID to url.
			$tab_url = add_query_arg( 'tab', $key, $current_url );

			// Get Tab Class Name.
			$class = isset( $tab['class'] ) ? 'class="youzify-active-tab"' : null; ?>

			<li>
				<a href="<?php echo $tab_url; ?>" <?php echo $class; ?>><i class="<?php echo $tab['icon']; ?>"></i><?php echo $tab['title']; ?></a>
			</li>

			<?php

		}

	    echo '</ul>';

	}

	/**
	 * # Save Settings With Ajax.
	 */
	function save_settings() {

		check_ajax_referer( 'youzify-settings-data', 'security' );

		do_action( 'youzify_before_panel_save_settings' );

		$data = $_POST;

		unset( $data['security'], $data['action'] );

	    // youzify Panel options
	    $options = isset( $data['youzify_options'] ) ? $data['youzify_options'] : null;

	    // Save Options
	    if ( $options ) {

	    	// Get Default Options.
	    	$default_options = apply_filters( 'youzify_default_options', array() );

		    foreach ( $options as $option => $value ) {

		    	// Get Option Value
		        if ( ! is_array( $value ) ) {
		        		$the_value = stripslashes( $value );
		        } else {

		        	$the_value = $value;

		        	if ( isset( $value['color'] ) && empty( $value['color'] ) ) {
		        		$the_value = '';
		        	}

		        }

		        // Save Option or Delete Option if Empty
		        if ( ! empty( $the_value ) ) {

		        	if ( isset( $default_options[ $option ] ) && $the_value == $default_options[ $option ] ) {
		        		$this->delete_option( $option );
		        	} else {
		        		$this->update_option( $option, $the_value, false );
		        	}

		        } else {
		        	$this->delete_option( $option );
		        }


		    }


	    }

	    // Actions
	    do_action( 'youzify_panel_save_settings' );

		wp_send_json_success( array( 'result' => 1, 'message' => __( 'Success!', 'youzify-social-share' ) ) );
		exit();

	}

	/**
	 * Delete Option
	 */
	function delete_option( $option ) {

	     if ( ! is_multisite() ) {
	        $option_value = delete_option( $option );
	    } else {
	        $option_value = delete_blog_option( null, $option );
	    }

	    return $option_value;
	}

	/**
	 * Reset Settings
	 */
	function reset_settings() {

		check_ajax_referer( 'youzify-settings-data', 'security' );

		do_action( 'youzify_before_reset_tab_settings' );

		// Reset Tab Options
		if ( isset( $_POST['youzify_options'] ) && ! empty( $_POST['youzify_options'] ) ) {
			foreach ( $_POST['youzify_options'] as $option => $value ) {
				if ( get_option( $option ) ) {
					delete_option( $option );
				}
			}
		}

		wp_send_json_success( array( 'result' => 1, 'message' => __( 'Success !', 'youzify-social-share' ) ) );
		exit();

	}

	/**
	 * License Settings.
	 */
	function get_license_settings( $args = array() ) {

		// Get License.
		$license = isset( $args['license'] ) ? $args['license'] : get_option( $args['option_id'] );

        global $Youzify_Settings;

		// Get License Dates.
		$support_date = get_option( $args['option_id'] . '_expires' );

        $Youzify_Settings->get_field(
            array(
                'title' => __( 'License Settings', 'youzify-social-share' ),
                'type'  => 'openBox',
                'class' => 'youzify-addon-license-settings'
            )
        );

        $Youzify_Settings->get_field(
            array(
                'title'  => __( 'License Key', 'youzify-social-share' ),
                'desc'  => sprintf( __( '<a href="%s">How to find your product license key?</a>', 'youzify-social-share' ), 'https://kainelabs.ticksy.com/article/15685/' ),
                'id'    => 'license',
                'type'  => 'text',
                'class' => 'youzify-addon-license-key',
                'std'   => $license,
                'hide_name' => true,
            )
        );

        if ( ! $license || empty( get_option( $args['option_id'] . '_expires' ) ) || ( $support_date != 'lifetime' && strtotime( $support_date ) < time() )  ) {

            $Youzify_Settings->get_field(
                array(
                    'button_title' => __( 'Verify License', 'youzify-social-share' ),
                    'id'    => 'youzify-verify-license',
                    'type'  => 'button',
                    'button_class' => 'youzify-activate-addon-key',
                    'button_data' => array(
                        'product-name' => $args['product_id'],
                        'option-name' => $args['option_id'],
                    )
                )
            );

        }

        // Get License Status.
        $this->get_license_status( $args );

        $Youzify_Settings->get_field( array( 'type' => 'closeBox' ) );

	}

	/**
	 * License Status.
	 */
	function get_license_status( $args ) {

		// Get License.
		$license = get_option( $args['option_id'] );

		if ( $license ) {

			// Get Dates.
			$support_date = get_option( $args['option_id'] . '_expires' );

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

			// Compare Support Date.
			if ( $support_date == 'lifetime' ) {
				$status = 'lifetime';
			} else {
				$status = strtotime( $support_date ) > time() ? 'active' : 'expired';
			}

			if ( ( $status == 'active' || $status == 'lifetime' ) && ( isset( $args['position'] ) && $args['position'] == 'top' ) ) {
				return;
			}

			// Get License Expiration Date.
			$expiration_date = date_i18n( get_option( 'date_format' ), strtotime( $support_date, current_time( 'timestamp' ) ) );

		    echo '<div class="youzify-addon-expire-notice youzify-addon-license-' . $status . '">';

		    if ( $status == 'expired' ) {
		    	echo sprintf( __( 'Your license key expired on %s.', 'youzify-social-share' ), $expiration_date );
		    } elseif ( $status == 'lifetime' ) {
		    	echo sprintf( __( 'Your license key is valid forever.', 'youzify-social-share' ), $expiration_date );
			} else {
		    	echo sprintf( __( 'Your license key will expire on %s.', 'youzify-social-share' ), $expiration_date );
			}

			if ( $status == 'expired' ) {
		    	echo '<a href="https://www.youzify.com/checkout/?edd_license_key=' . $license . '&download_id=' . $args['product_id'] . '">' . __( 'Please renew your license to keep receiving updates and support.', 'youzify-social-share' ) . '</a>';
			}

			echo '</div>';

	    }

	}

	/**
	 * Save Add On Key License
	 */
	function save_addon_key_license() {

		// retrieve the license from the database
		$license = trim( $_POST['license'] );

		// data to send in our API request
		$api_params = array(
			'edd_action' => 'activate_license',
			'license'    => $license,
			'item_id'  	 => urlencode( $_POST['product_name'] ),
			'url'        => home_url()
		);

		// Call the custom API.
		$response = wp_remote_post( YOUZIFY_STORE_URL, array( 'timeout' => 15, 'sslverify' => false, 'body' => $api_params ) );

		// make sure the response came back okay
		if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {

			if ( is_wp_error( $response ) ) {
				$message = $response->get_error_message();
			} else {
				$message = __( 'An error occurred, please try again.' );
			}

		} else {

			$license_data = json_decode( wp_remote_retrieve_body( $response ) );

			if ( false === $license_data->success && $license_data->error != 'expired' ) {

				switch( $license_data->error ) {

					// case 'expired' :
					// 	$message = sprintf(
					// 		__( 'Your license key expired on %s.', 'youzify-social-share' ),
					// 		date_i18n( get_option( 'date_format' ), strtotime( $license_data->expires, current_time( 'timestamp' ) ) )
					// 	);
					// 	break;

					case 'disabled' :
					case 'revoked' :
						$message = __( 'Your license key has been disabled.', 'youzify-social-share' );
						break;

					case 'missing' :
						$message = __( 'Invalid license.', 'youzify-social-share' );
						break;

					case 'invalid' :
					case 'site_inactive' :
						$message = __( 'Your license is not active for this URL.', 'youzify-social-share' );
						break;

					case 'item_name_mismatch' :
						$message = sprintf( __( 'This appears to be an invalid license key for %s.', 'youzify-social-share' ), $_POST['product_name'] );
						break;

					case 'no_activations_left':
						$message = __( 'Your license key has reached its activation limit.', 'youzify-social-share' );
						break;

					default :
						$message = __( 'An error occurred, please try again.', 'youzify-social-share' );
						break;
				}

			}

		}
		// Check if anything passed on a message constituting a failure
		if ( ! empty( $message ) ) {
			wp_send_json_error( array( 'message' => $message ) );
		} else {

			$this->update_option( $_POST['name'] . '_expires', $license_data->expires );
			$this->update_option( $_POST['name'], $license );

			wp_send_json_success( array( 'message' => __( 'Success !', 'youzify-social-share' ) ) );
		}

		exit();

	}

	/**
	 * Update Options
	 */
	function update_option( $option, $value = null, $autoload = false ) {

	    if ( ! is_multisite() ) {
	        $option_value = update_option( $option, $value, $autoload );
	    } else {
	        if ( apply_filters( 'youzify_activate_blog_mode', true, $option ) ) {
	            $option_value = update_blog_option( null, $option, $value );
	        } else {
	            $option_value = update_site_option( $option, $value );
	        }
	    }

	    return $option_value;
	}

}

global $Youzify_Admin;

$Youzify_Admin = new Youzify_Admin();