<?php

namespace PureCharity\Sponsorships;

class AdminController extends SponsorshipsController {

    public $moduleConfig;
	public static $moduleConfigStatic;

    private $version;
    private $pluginName;
    
    public static $classPath = '\PureCharity\Sponsorships\AdminController';

    function __construct($moduleConfig) {
        
        $this->moduleConfig = $moduleConfig;
		self::$moduleConfigStatic = $moduleConfig;
    
        $this->pluginName = $this->moduleConfig['plugin']['name'];
        $this->version = $this->moduleConfig['plugin']['version'];
    }
	
	/**
	 * Add the Plugin Settings Menu.
	 *
	 * @since 1.0.0
	 */
	function addAdminMenu() { 

		add_options_page(
            'PureCharity&#8482; Sponsorships Settings', 
            'PureCharity&#8482; Sponsorships', 
            'manage_options', 
            'pure_plugin_sponsorships', 
            [$this, 'optionsPage']
        );
	}

	/**
	 * Checks for the existence of the pure base settings.
	 *
	 * @since 1.0.0
	 */
	public static function settingsExist() { 
		if (false == get_option('purecharity_plugin_sponsorship_settings')) { 
			add_option('purecharity_plugin_sponsorship_settings');
		}
	}

	/**
	 * Initializes the settings page options.
	 *
	 * @since 1.0.0
	 */
	public static function settingsInit() 
	{
		register_setting( 'psPluginPage', 'purecharity_plugin_sponsorship_settings' );

		add_settings_section(
			'purecharity_sponsorships_psPluginPage_section',
			__( 'General settings', 'wordpress' ),
			[self::$classPath, 'settingsSectionCallback'],
			'psPluginPage'
		);

		add_settings_field(
			'plugin_color',
			__( 'Main Theme Color', 'wordpress' ),
			[self::$classPath, 'mainColorRender'],
			'psPluginPage',
			'purecharity_sponsorships_psPluginPage_section'
		);

		add_settings_field(
			'plugin_style',
			__( 'Style to Use', 'wordpress' ),
			[self::$classPath, 'pluginStyleRender'],
			'psPluginPage',
			'purecharity_sponsorships_psPluginPage_section'
		);

		add_settings_field(
			'single_view_template', __( 'Single view template', 'wordpress' ),
			[self::$classPath, 'singleViewTemplateRender'],
			'psPluginPage',
			'purecharity_sponsorships_psPluginPage_section'
		);

		add_settings_section(
			'purecharity_sponsorships_display_psPluginPage_section',
			__( 'Display settings', 'wordpress' ),
			[self::$classPath, 'displaySettingsSectionCallback'],
			'psPluginPage'
		);

		add_settings_field(
			'hide_powered_by', __( 'Hide Powered By Image', 'wordpress' ),
			[self::$classPath, 'hidePoweredByRender'],
			'psPluginPage', 'purecharity_sponsorships_display_psPluginPage_section'
		);

		add_settings_field(
			'search_input', __( 'Display Global Search', 'wordpress' ),
			[self::$classPath, 'searchInputRender'],
			'psPluginPage', 'purecharity_sponsorships_display_psPluginPage_section'
		);

		add_settings_field(
			'age_filter', __( 'Display Age Filter', 'wordpress' ),
			[self::$classPath, 'ageFilterRender'],
			'psPluginPage', 'purecharity_sponsorships_display_psPluginPage_section'
		);

		add_settings_field(
			'gender_filter', __( 'Display Gender Filter', 'wordpress' ),
			[self::$classPath, 'genderFilterRender'],
			'psPluginPage', 'purecharity_sponsorships_display_psPluginPage_section'
		);

		add_settings_field(
			'location_filter', __( 'Display Location Filter', 'wordpress' ),
			[self::$classPath, 'locationFilterRender'],
			'psPluginPage', 'purecharity_sponsorships_display_psPluginPage_section'
		);

		add_settings_field(
			'allowed_custom_fields', __( 'Allowed Custom Fields', 'wordpress' ),
			[self::$classPath, 'allowedCustomFieldsRender'],
			'psPluginPage', 'purecharity_sponsorships_display_psPluginPage_section'
		);

		add_settings_section(
			'purecharity_sponsorships_3_psPluginPage_section',
			__( 'Display settings', 'wordpress' ),
			[self::$classPath, 'thirdOptionSettingsSectionCallback'],
			'psPluginPage'
		);

		add_settings_field(
			'show_back_link', __( 'Display Back Link', 'wordpress' ),
			[self::$classPath, 'showBackLinkRender'],
			'psPluginPage', 'purecharity_sponsorships_3_psPluginPage_section'
		);

		add_settings_field(
			'back_link', __( 'Back Link to (default: back)', 'wordpress' ),
			[self::$classPath, 'backLinkRender'],
			'psPluginPage', 'purecharity_sponsorships_3_psPluginPage_section'
		);

		add_settings_field(
			'show_more_link', __( 'Display More Info Link', 'wordpress' ),
			[self::$classPath, 'showMoreLinkRender'],
			'psPluginPage', 'purecharity_sponsorships_3_psPluginPage_section'
		);

		add_settings_field(
			'more_link', __( 'More Info Link to', 'wordpress' ),
			[self::$classPath, 'moreLinkRender'],
			'psPluginPage', 'purecharity_sponsorships_3_psPluginPage_section'
		);
	}

	public static function settingsSectionCallback() {
		echo __( 'General settings for the Sponsorships module.', 'wordpress' );
	}

	public static function mainColorRender() {
		$options = get_option('purecharity_plugin_sponsorship_settings');
		?>
		<input type="text" name="purecharity_plugin_sponsorship_settings[plugin_color]" id="main_color" value="<?php echo @$options['plugin_color']; ?>">
		<?php
	}
	
	public static function pluginStyleRender() {
		$options = get_option('purecharity_plugin_sponsorship_settings');
		$moduleConfig = self::$moduleConfigStatic;
		?>
		<input 	type="radio"
				style="float:left; margin: 57px 10px 0 0"
				name="purecharity_plugin_sponsorship_settings[plugin_style]"
				value="pure-sponsorships-option1"
				<?php echo $options['plugin_style'] == 'pure-sponsorships-option1' ? 'checked' : '' ?>
				/>
			<label><img src="<?php echo $moduleConfig['resources']['assets']['img'] .'sponsorships/opt1.png'; ?>" width="320"></label>
		<br />
		<input 	type="radio"
				style="float:left; margin: 57px 10px 0 0"
				name="purecharity_plugin_sponsorship_settings[plugin_style]"
				value="pure-sponsorships-option2"
				<?php echo $options['plugin_style'] == 'pure-sponsorships-option2' ? 'checked' : '' ?>
				/>
			<label><img src="<?php echo $moduleConfig['resources']['assets']['img'] .'sponsorships/opt2.png'; ?>" width="320"></label>
		<br />
		<input 	type="radio"
				style="float:left; margin: 57px 10px 0 0"
				name="purecharity_plugin_sponsorship_settings[plugin_style]"
				value="pure-sponsorships-option3"
				<?php echo $options['plugin_style'] === 'pure-sponsorships-option3' ? 'checked' : '' ?>
				/>
			<label><img src="<?php echo $moduleConfig['resources']['assets']['img'] .'sponsorships/opt3.png'; ?>" width="320"></label>
		<?php
	}

	public static function singleViewTemplateRender() {
		$options = get_option( 'purecharity_plugin_sponsorship_settings' );

		global $PcPlugin;
		$baseModule = $PcPlugin->getModule('base', 'BaseController');
		$templates = $baseModule->purecharityGetTemplates();
		
		?>
		<select name="purecharity_plugin_sponsorship_settings[single_view_template]">
			<option value="">Inherit from the listing page</option>
			<?php foreach($templates as $key => $template){ ?>
				<option <?php echo $template == @$options['single_view_template'] ? 'selected' : '' ?> value="<?php echo $template; ?>"><?php echo "$key ($template)" ?></option>
			<?php } ?>
		</select>
		<?php
	}

	public static function displaySettingsSectionCallback() {
		echo __( 'Display settings for the sponsorships plugin.', 'wordpress' );
	}

	public static function hidePoweredByRender() {
		$options = get_option( 'purecharity_plugin_sponsorship_settings' );
		?>
		<input
			type="checkbox"
			name="purecharity_plugin_sponsorship_settings[hide_powered_by]"
			<?php echo (isset($options['hide_powered_by'])) ? 'checked' : '' ?>
			value="true">
		<?php
	}

	public static function searchInputRender() {
		$options = get_option( 'purecharity_plugin_sponsorship_settings' );
		?>
		<input
			type="checkbox"
			name="purecharity_plugin_sponsorship_settings[search_input]"
			<?php echo (isset($options['search_input'])) ? 'checked' : '' ?>
			value="true">
		<?php
	}

	public static function ageFilterRender() {
		$options = get_option( 'purecharity_plugin_sponsorship_settings' );
		?>
		<input
			type="checkbox"
			name="purecharity_plugin_sponsorship_settings[age_filter]"
			<?php echo (isset($options['age_filter'])) ? 'checked' : '' ?>
			value="true">
		<?php
	}

	public static function genderFilterRender() {
		$options = get_option( 'purecharity_plugin_sponsorship_settings' );
		?>
		<input
			type="checkbox"
			name="purecharity_plugin_sponsorship_settings[gender_filter]"
			<?php echo (isset($options['gender_filter'])) ? 'checked' : '' ?>
			value="true">
		<?php
	}

	public static function locationFilterRender() {
		$options = get_option( 'purecharity_plugin_sponsorship_settings' );
		?>
		<input
			type="checkbox"
			name="purecharity_plugin_sponsorship_settings[location_filter]"
			<?php echo (isset($options['location_filter'])) ? 'checked' : '' ?>
			value="true">
		<?php
	}

	public static function allowedCustomFieldsRender() {
		$options = get_option( 'purecharity_plugin_sponsorship_settings' );
		?>
		<input type="hidden" name="purecharity_plugin_sponsorship_settings[allowed_custom_fields]" id="custom_fields_value" value="<?php echo @$options['allowed_custom_fields']; ?>">

		<a href="#" class="button button-primary pc-add-custom-field">Add Custom Field</a>

		<ul class="pcs_custom_field header">
			<li>
				<div class="left">
					<b>Display Name</b>
				</div>
				<div class="right">
					<b>Original Custom Field Name</b>
				</div>
				<br style="clear: both" />
			</li>
		</ul>

		<ul class="pcs_custom_field sortable">
			<?php foreach(explode(';', $options['allowed_custom_fields']) as $field){ ?>
				<?php $parsed_field = explode('|', $field); ?>
				<li class="custom_field pc-custom-field-item">

					<div class="left">
						<b><?php echo @$parsed_field[1]; ?></b>
						<input type="text" value="<?php echo @$parsed_field[1]; ?>" class="pc-custom-field-input pc-custom-field-input-value">
						<a href="#" class="edit pc-edit-custom-field">edit</a>
						<a href="#" class="save pc-save-custom-field">save</a>
					</div>

					<div class="right">
						<b><?php echo @$parsed_field[0]; ?></b>
						<input type="text" value="<?php echo @$parsed_field[0]; ?>" class="pc-custom-field-input pc-custom-field-input-key">
						<a href="#" class="edit pc-edit-custom-field">edit</a>
						<a href="#" class="save pc-save-custom-field">save</a>
					</div>

					<div class="options">
						<a href="#" class="remove pc-remove-custom-field">remove</a>
					</div>

					<br style="clear:both" />
				</li>
			<?php } ?>
		</ul>

		<p>
			Add the allowed custom fields for your sponsorship program, using the format they are inputted into the Pure Charity app.<br />
			<a href="#" id="custom-fields-example">Load Example</a>
			<a href="#" id="custom-fields-example-cancel" style="display:none">Cancel</a>
			<br />
			<div id="custom-fields-loader"
				class="custom-fields-example-loader-trigger"
				style="display:none"
			>
				<span>Sponsorship Program Slug:</span><br />
				<input type="text" id="example-program-slug" /><br />
				<button type="button" id="generate-example" name="button">Load Example</button>
			</div>
		</p>
		<?php
	}

	public static function thirdOptionSettingsSectionCallback() {
		echo __( 'Display settings for the sponsorships plugin. * Only available when using the third layout option.', 'wordpress' );
	}

	public static function showBackLinkRender() {
		$options = get_option( 'purecharity_plugin_sponsorship_settings' );
		?>
		<input
			type="checkbox"
			name="purecharity_plugin_sponsorship_settings[show_back_link]"
			<?php echo $options['plugin_style'] === 'pure-sponsorships-option3' ? '' : 'disabled' ?>
			<?php echo (isset($options['back_link'])) ? 'checked' : '' ?>
			value="true">
		<?php
	}

	public static function backLinkRender() {
		$options = get_option( 'purecharity_plugin_sponsorship_settings' );
		?>
		<input
			type="text"
			name="purecharity_plugin_sponsorship_settings[back_link]"
			placeholder="javascript:history.go(-1)"
			value="<?php echo @$options['back_link']; ?>" />
		<?php
	}

	public static function showMoreLinkRender() {
		$options = get_option( 'purecharity_plugin_sponsorship_settings' );
		?>
		<input
			type="checkbox"
			name="purecharity_plugin_sponsorship_settings[show_more_link]"
			<?php echo $options['plugin_style'] === 'pure-sponsorships-option3' ? '' : 'disabled' ?>
			<?php echo (isset($options['more_link'])) ? 'checked' : '' ?>
			value="true">
		<?php
	}

	public static function moreLinkRender() {
		$options = get_option( 'purecharity_plugin_sponsorship_settings' );
		?>
		<input
			type="text"
			name="purecharity_plugin_sponsorship_settings[more_link]"
			value="<?php echo @$options['more_link']; ?>" />
		<?php
	}

	/**
	 * Creates the options page.
	 *
	 * @since 1.0.0
	 */
	public static function optionsPage() {
    ?>
	<div class="wrap">
      <form action="options.php" method="post" class="pure-settings-form">
				<?php
					echo '<img align="left" src="' . plugins_url( 'purecharity-plugin/resources/assets/img/purecharity.png' ) . '" > ';
				?>
				<h2 style="padding-left:100px;padding-top: 20px;padding-bottom: 50px;border-bottom: 1px solid #ccc;">
					PureCharity&#8482; Sponsorships Settings
				</h2>

				<?php
				settings_fields( 'psPluginPage' );
				do_settings_sections( 'psPluginPage' );
				submit_button();
				?>

			</form>
    </div>
    <?php
	}

	public function generateSponsorshipsCustomFieldsExample() {
		
		$sponsorshipId = (
			!empty($_POST['sponsorshipId']) ?
			$_POST['sponsorshipId'] :
			null
		);

		if (empty($sponsorshipId)) { $this->returnAjaxResponse(false, 'Provide Sponsorship ID.'); }

		$baseModule = $this->getModule('base', 'BaseController');
        $apiController = $baseModule->getController('ApiController');

		$sponsorhipsRequest = $apiController->apiCall(
			'sponsorships',
			[],
			[
				'limit' => 1,
				'sponsorship_program_id' => $sponsorshipId,
			],
		);
		
		if (empty($sponsorhipsRequest)) { $this->returnAjaxResponse(false, 'Results not found.'); }

		$customFieldsFromRequest = $sponsorhipsRequest->sponsorships[0]->custom_fields;

		$results = [];

		if (empty($customFieldsFromRequest)) { $this->returnAjaxResponse(true, $results); }

		$customFieldsFromRequest = (array)$customFieldsFromRequest;

		foreach ($customFieldsFromRequest as $optionKey => $optionValue) {

			$results[$optionKey] = $optionValue;
		}

		$this->returnAjaxResponse(true, $results);
	}

	/**
	 * Register the stylesheets for the Dashboard.
	 *
	 * @since 1.0.0
	 */
	public function enqueueStyles() {
		wp_enqueue_style('thickbox');
	}

	/**
	 * Register the JavaScript for the dashboard.
	 *
	 * @since 1.0.0
	 */
	public function enqueueScripts($hook) {
		wp_enqueue_script('jquery-ui-sortable');
		wp_enqueue_script('media-upload');
		wp_enqueue_script('thickbox');
	}

	/** 
	 * Sponsorships Cache Purge - Admin only
	 * Triggered via ?pcCacheReset=true
	 * 
	 * @since 1.0.0
	*/
	public function sponsorshipsCacheReset() {

		if (
			isset($_GET['pcCacheReset']) &&
			!wp_doing_ajax()
		) {
			$resetCacheResult = $this->resetSponsorshipsCache();
			$resetLocationsCacheResult = $this->resetSponsorshipsLocationsCache();
		}
	}

	/** 
	 * Reset Sponsorships Cache
	 *
	 * @return bool
	 * @since 1.0.0
	*/
	public function resetSponsorshipsCache() {

		if (!isset($_GET['pcCacheReset'])) { return false; }
	
		$sponsorshipsCacheDir = (wp_get_upload_dir())['basedir'] .'/pc-sponsorships-cache/';
	
		return (
			file_exists($sponsorshipsCacheDir) ?
			$this->deleteDir($sponsorshipsCacheDir) :
			false
		);
	}

	/** 
	 * Reset Sponsorships Locations Cache
	 *
	 * @return bool
	 * @since 1.0.0
	*/
	public function resetSponsorshipsLocationsCache() {

		if (!isset($_GET['pcCacheReset'])) { return false; }
	
		$sponsorshipsLocationsCacheDir = (wp_get_upload_dir())['basedir'] .'/pc-sponsorships-locations-cache/';
	
		return (
			file_exists($sponsorshipsLocationsCacheDir) ?
			$this->deleteDir($sponsorshipsLocationsCacheDir) :
			false
		);
	}

	/** 
	 * Delete Dir
	 *
	 * @param string
	 * @return bool
	 * @since 1.0.0
	*/
	public function deleteDir($dirPath) {

		if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
			$dirPath .= '/';
		}

		$files = scandir($dirPath);

		$restrictedFiles = [
			'.',
			'..',
		];

		foreach ($files as $file) {
			if (in_array($file, $restrictedFiles)) { continue; }

			$filePath = $dirPath . $file;

			if (is_dir($filePath)) {
				$this->deleteDir($filePath);
			} else {
				unlink($filePath);
			}
		}

		return rmdir($dirPath);
	}

}