<?php
namespace Blazemedia\Affiliation\AdminUserInterface\Settings;

use Blazemedia\Affiliation\AdminUserInterface\Settings\Capability;
use Blazemedia\Affiliation\Utils\HttpRequest;

/**
 * Generated by the WordPress Option Page generator
 * at http://jeremyhixon.com/wp-tools/option-page/
 */

class SettingPage {

    private $affiliation_settings_options;

	public function __construct() {

		if(!empty( $_POST ) ){

			if( isset($_POST['flush_transient_command']) && $_POST['flush_transient_command'] == 'purge'){
				$this->delete_transients_with_prefix('gt_');
				$this->delete_transients_with_prefix('https://format-provider');
				header("location: ./admin.php?page=affiliation-settings&transients_flushed=true");
			}

			
			if( isset($_POST['flush_cache_command']) && $_POST['flush_cache_command'] == 'purge'){
				if (isset($_POST['pwd']) && $_POST['pwd'] == '3llo3ll0') {
					$this->flush_format_provider_subcache($this->getDomain());
					header("location: ./admin.php?page=affiliation-settings&cache_flushed=true");
				} else {
					header("location: ./admin.php?page=affiliation-settings&cache_not_flushed");
				}
			}
		}

		add_action( 'admin_menu', [ $this, 'affiliation_settings_add_plugin_page' ]);
		add_action( 'admin_init', [ $this, 'affiliation_settings_page_init'       ] );
		add_action( 'admin_head', [ $this, 'transientFlushedNotice'               ]);
		add_action( 'admin_head', [ $this, 'cacheFlushedNotice'                   ]);

	}

	protected function getDomain() {

        return preg_replace('/^.*?\.(.*?\..*?)$/', '$1', home_url() );

    }


	public static function transientFlushedNotice() {

		if(strpos($_SERVER['REQUEST_URI'], "transients_flushed") == true) {
			echo '<div class="notice notice-success"><p>✅ <strong>Transient Formati</strong> vuotati correttamente</p></div>';
		}
    }

	public static function cacheFlushedNotice() {
		if(strpos($_SERVER['REQUEST_URI'], "cache_flushed") == true) {
			echo '<div class="notice notice-success"><p>✅ <strong>Cache del Randering Manager</strong> vuotata per questo dominio</p></div>';
		} 
		if(strpos($_SERVER['REQUEST_URI'], "cache_not_flushed") == true) {
			echo '<div class="notice notice-error"><p>⛔ <strong>Password errata</strong></p></div>';
		} 
    }

	public function affiliation_settings_add_plugin_page() {

		add_menu_page(
			'Affiliation Management', // page_title
			'Affiliation Management', // menu_title
			'manage_options', // capability
			'affiliation-management', // menu_slug
			'', // callback
			'dashicons-chart-area', // icon_url
			65 // position
		);

		add_submenu_page(
			'affiliation-management', //parent_slug
			'Affiliation Settings', // page_title
			'Affiliation Settings', // menu_title
			'manage_options', // capability
			'affiliation-settings', // menu_slug
			[ $this, 'affiliation_settings_create_admin_page' ], // callback	,
			5,
		);
	} 

	public function affiliation_settings_create_admin_page() {

        if( !current_user_can( Capability::AFFILIATION_CAP ) ) {
            wp_die('Non hai i permessi per visualizzare questa pagina');
        } 

		$this->affiliation_settings_options = get_option( 'affiliation_settings_option_name' ); ?>

		<div class="wrap">
			<h2>Affiliation Settings</h2>
			<p></p>
			<?php settings_errors(); ?>
			<form method="post" action="options.php">
				<?php
					settings_fields( 'affiliation_settings_option_group' );
					do_settings_sections( 'affiliation-settings-admin' );
					submit_button();
				?>
			</form>

			<div style="display: flex">
				<form method="post" name="flush-transient-button" action="options.php">
					<span id="flush-transient-button">
						<input type="hidden" value="purge" name="flush_transient_command"/>
						<input id="flush-transient" type="submit" value="⚠ Svuota transient formati" class="button" >
					</span>
				</form>
				<form method="post" name="flush-cache-button" action="options.php" style="margin-left: 6px">
					<span id="flush-cache-button">
						
						<input type="hidden" value="purge" name="flush_cache_command"/>
						<input id="flush-cache" type="submit" value="⚠ Svuota cache Rendering Manager" class="button" >
						<input type="password" name="pwd" placeholder="Password" required />
					</span>
				</form>
			</div>

		</div>
	<?php }

	public function flush_format_provider_subcache( $domain ) {

		$format_provider = str_replace('/api', '' , BLZ_API_RENDERING_MANAGER);


 		$apicall = $format_provider . 'purge_subcache/' . $domain;

        $response =  HttpRequest::getContent( $apicall , true, 60);

		return $response;

		
	}

	public function delete_transients_with_prefix( $prefix ) {
		foreach ( $this->get_transient_keys_with_prefix( $prefix ) as $key ) {
			delete_transient( $key );
		}
	}

	function get_transient_keys_with_prefix( $prefix ) {
		global $wpdb;

		$prefix = $wpdb->esc_like( '_transient_' . $prefix );
		$sql    = "SELECT `option_name` FROM $wpdb->options WHERE `option_name` LIKE '%s'";
		$keys   = $wpdb->get_results( $wpdb->prepare( $sql, $prefix . '%' ), ARRAY_A );

		if ( is_wp_error( $keys ) ) {
			return [];
		}

		return array_map( function( $key ) {
			// Remove '_transient_' from the option name.
			return ltrim( $key['option_name'], '_transient_' );
		}, $keys );
	}


	public function affiliation_settings_page_init() {

		register_setting(
			'affiliation_settings_option_group', // option_group
			'affiliation_settings_option_name', // option_name
			array( $this, 'affiliation_settings_sanitize' ) // sanitize_callback
		);

		add_settings_section(
			'affiliation_settings_setting_section', // id
			'Settings', // title
			array( $this, 'affiliation_settings_section_info' ), // callback
			'affiliation-settings-admin' // page
		);

		add_settings_field(
			'post_types_0', // id
			'Post Types', // title
			array( $this, 'post_types_0_callback' ), // callback
			'affiliation-settings-admin', // page
			'affiliation_settings_setting_section' // section
		);

		add_settings_field(
			'restrizioni_1', // id
			'Restrizioni', // title
			array( $this, 'restrizioni_1_callback' ), // callback
			'affiliation-settings-admin', // page
			'affiliation_settings_setting_section' // section
		);

		add_settings_field(
			'domain_2', // id
			'Dominio', // title
			array( $this, 'domain_2_callback' ), // callback
			'affiliation-settings-admin', // page
			'affiliation_settings_setting_section' // section
		);

		add_settings_field(
			'disclaimer', // id
			'Disclaimer', // title
			array( $this, 'disclaimer_callback' ), // callback
			'affiliation-settings-admin', // page
			'affiliation_settings_setting_section' // section
		);

		add_settings_field(
			'ambiente', // id
			'Ambiente', // title
			array( $this, 'ambiente_callback' ), // callback
			'affiliation-settings-admin', // page
			'affiliation_settings_setting_section' // section
		);

		add_settings_field( 'cache', 'Cache', [ $this, 'cache_callback' ], 'affiliation-settings-admin', 'affiliation_settings_setting_section' );
	}

	public function affiliation_settings_sanitize($input) {
		$sanitary_values = array();
		if ( isset( $input['post_types_0'] ) ) {
			$sanitary_values['post_types_0'] = sanitize_text_field( $input['post_types_0'] );
		}

		if ( isset( $input['restrizioni_1'] ) ) {
			$sanitary_values['restrizioni_1'] = sanitize_text_field( $input['restrizioni_1'] );
		}

		if ( isset( $input['domain_2'] ) ) {
			$sanitary_values['domain_2'] = sanitize_text_field( $input['domain_2'] );
		}

		if ( isset( $input['disclaimer'] ) ) {
			$sanitary_values['disclaimer'] = esc_textarea( $input['disclaimer'] );
		}

		if ( isset( $input['ambiente'] ) ) {
			$sanitary_values['ambiente'] = $input['ambiente'];
		}

		if ( isset( $input['cache'] ) ) {
			$sanitary_values['cache'] = $input['cache'];
		}

		return $sanitary_values;
	}

	public function affiliation_settings_section_info() {
		
	}


	public function post_types_0_callback() {
		printf(
			'<input class="regular-text" type="text" name="affiliation_settings_option_name[post_types_0]" id="post_types_0" value="%s">',
			isset( $this->affiliation_settings_options['post_types_0'] ) ? esc_attr( $this->affiliation_settings_options['post_types_0']) : ''
		);
	}

	public function restrizioni_1_callback() {
		printf(
			'<input class="regular-text" type="text" name="affiliation_settings_option_name[restrizioni_1]" id="restrizioni_1" value="%s">',
			isset( $this->affiliation_settings_options['restrizioni_1'] ) ? esc_attr( $this->affiliation_settings_options['restrizioni_1']) : ''
		);
	}

	public function domain_2_callback() {
		printf(
			'<input class="regular-text" type="text" name="affiliation_settings_option_name[domain_2]" id="domain_2" value="%s">',
			isset( $this->affiliation_settings_options['domain_2'] ) ? esc_attr( $this->affiliation_settings_options['domain_2']) : ''
		);
	}

	public function disclaimer_callback() {
		printf(
			'<textarea class="large-text" rows="5" name="affiliation_settings_option_name[disclaimer]" id="disclaimer">%s</textarea>',
			isset( $this->affiliation_settings_options['disclaimer'] ) ? esc_attr( $this->affiliation_settings_options['disclaimer']) : ''
		);
	}

	public function ambiente_callback() {
		?> <select name="affiliation_settings_option_name[ambiente]" id="ambiente">
			<?php $selected = (isset( $this->affiliation_settings_options['ambiente'] ) && $this->affiliation_settings_options['ambiente'] === 'staging') ? 'selected' : '' ; ?>
			<option value="staging" <?php echo $selected; ?>>Staging</option>
			<?php $selected = (isset( $this->affiliation_settings_options['ambiente'] ) && $this->affiliation_settings_options['ambiente'] === 'prod') ? 'selected' : '' ; ?>
			<option value="prod" <?php echo $selected; ?>>Produzione</option>
			<?php $selected = (isset( $this->affiliation_settings_options['ambiente'] ) && $this->affiliation_settings_options['ambiente'] === 'local') ? 'selected' : '' ; ?>
			<option value="local" <?php echo $selected; ?>>Local</option>
		</select> <?php
	}

	public function cache_callback() {
		?> <select name="affiliation_settings_option_name[cache]" id="cache">
			<?php $selected = (isset( $this->affiliation_settings_options['cache'] ) && $this->affiliation_settings_options['cache'] === '0') ? 'selected' : '' ; ?>
			<option value="0" <?php echo $selected; ?>>Off</option>
			<?php $selected = (isset( $this->affiliation_settings_options['cache'] ) && $this->affiliation_settings_options['cache'] === '1') ? 'selected' : '' ; ?>
			<option value="1" <?php echo $selected; ?>>On</option>
		</select> <?php
	}

}