<?php
class Calendarista_FeedsTemplate extends Calendarista_ViewBase{
	public $setting;
	public $feedList;
	function __construct( ){
		parent::__construct(false, true, 'calendarista-settings');
		new Calendarista_FeedController(
			array($this, 'created')
			, array($this, 'updated')
			, array($this, 'deleted')
			, array($this, 'deletedAllImported')
			, array($this, 'deletedMany')
		);
		$generalSettingsRepository = new Calendarista_GeneralSettingsRepository();
		$this->setting = $generalSettingsRepository->read();
		$this->feedList = new Calendarista_FeedList();
		$this->feedList->bind();
		$this->render();
	}
	public function isLocalhost() {
		$whitelist = array( '127.0.0.1', '::1' );
		if( in_array( $_SERVER['REMOTE_ADDR'], $whitelist) )
			return true;
	}
	public function created($result) {
		if($result):
		$this->selectedProjectId = -1;
		$this->readAllProjects();
		?>
		<div class="wrap">
			<div class="calendarista-notice updated notice is-dismissible">
				<p><?php echo __('The feed has been created and will be synched to the selected service and/or availability.', 'calendarista') ?></p>
			</div>
			<hr>
		</div>
		<?php
		else:
		?>
		<div class="wrap">
			<div class="calendarista-notice error notice is-dismissible">
				<p><?php echo __('The feed you are tryign to create already exists.', 'calendarista') ?></p>
			</div>
			<hr>
		</div>
		<?php 
		endif;
	}
	public function updated($cronJobFeedTimeout) {
		?>
		<div class="wrap">
			<div class="calendarista-notice updated notice is-dismissible">
				<p><?php echo  __('Feed synchronization interval has been updated.', 'calendarista') ?></p>
			</div>
			<hr>
		</div>
		<?php
	}
	public function deleted() {
		?>
		<div class="wrap">
			<div class="calendarista-notice updated notice is-dismissible">
				<p><?php echo __('The feed has been deleted.', 'calendarista') ?></p>
			</div>
			<hr>
		</div>
		<?php
	}
	public function deletedAllImported($result) {
		?>
		<div class="wrap">
			<div class="calendarista-notice updated notice is-dismissible">
				<p><?php echo sprintf(__('Deleted %d imported appointments.', 'calendarista'), $result) ?></p>
			</div>
			<hr>
		</div>
		<?php
	}
	public function deletedMany() {
		?>
		<div class="wrap">
			<div class="calendarista-notice updated notice is-dismissible">
				<p><?php echo __('The feed(s) have been deleted.', 'calendarista') ?></p>
			</div>
			<hr>
		</div>
		<?php
	}
	public function render(){
	?>
		<div class="widget-liquid-left">
			<div id="widgets-left">
				<div class="wrap">
					<div class="column-pane">
						<div class="calendarista-borderless-accordion">
							<div id="export">
								<h3><?php echo __('Export', 'calendarista') ?></h3>
								<div>
									<form data-parsley-validate action="<?php echo $this->requestUrl ?>" method="post">
										<input type="hidden" name="controller" value="calendarista_feeds">
										<input type="hidden" name="calendarista_nonce" value="<?php echo wp_create_nonce('calendarista-ajax-nonce') ?>"/>
										<p>
											<input type="checkbox" name="enableFeeds" <?php echo $this->setting->enableFeeds ? 'checked=checked' : '' ?>><?php echo __('Enable', 'calendarista') ?>
											<span id="spinner_feeds1" class="calendarista-spinner calendarista-invisible">
												<img src="<?php echo CALENDARISTA_PLUGINDIR ?>assets/img/transparent.gif">
											</span>
										</p>
										<p class="description"><?php echo __('Feed generator', 'calendarista') ?></p>
										<div class="export-feed">
											<p>
												<?php $this->renderProjectSelectList(true, __('Select a service', 'calendarista'), true) ?>
											</p>
											<p>
												<select name="availabilityId" data-parsley-required="true" data-parsley-errors-messages-disabled="true">
													<option value=""><?php echo __('All availabilities', 'calendarista') ?></option>
												</select>
												<span id="spinner_feeds2" class="calendarista-spinner calendarista-invisible">
													<img src="<?php echo CALENDARISTA_PLUGINDIR ?>assets/img/transparent.gif">
												</span>
												<br class="clear">
											</p>
										</div>
										<p>
										  <strong><?php echo __('Appointment status', 'calendarista') ?></strong><br>
										  <input type="radio" name="status" value="-1" checked><?php echo __('Any', 'calendarista') ?>
										  <input type="radio" name="status" value="0"><?php echo __('Pending', 'calendarista') ?>
										  <input type="radio" name="status" value="1"><?php echo __('Approved', 'calendarista') ?>
										  <input type="radio" name="status" value="2"><?php echo __('Cancelled', 'calendarista') ?>
										</p>
									</form>
									<p class="description"><?php echo __('Select a service and availability. The resulting iCAL feed will be printed below.', 'calendarista') ?></p>
									<div>
										<textarea name="feedUrl" rows="5" style="width: 100%"></textarea>
									</div>
									<p class="description"><?php echo __('Copy the generated iCAL feed and use it in google calendar, outlook, icalendar etc', 'calendarista') ?></p>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<div class="widget-liquid-right">
			<div id="widgets-right">
				<div class="wrap">
					<div class="column-pane">
						<div class="calendarista-borderless-accordion">
							<div id="import">
								<h3><?php echo __('Import', 'calendarista') ?></h3>
								<div>
									<form data-parsley-validate action="<?php echo $this->requestUrl ?>" method="post">
										<input type="hidden" name="controller" value="calendarista_feeds">
										<input type="hidden" name="calendarista_nonce" value="<?php echo wp_create_nonce('calendarista-ajax-nonce') ?>"/>
										<div class="import-feed">
											<p>
												<?php $this->renderProjectSelectList(true, __('Select a service', 'calendarista'), true) ?>
											</p>
											<p>
												<select name="availabilityId" data-parsley-required="true" data-parsley-errors-messages-disabled="true">
													<option value=""><?php echo __('All availabilities', 'calendarista') ?></option>
												</select>
												<span id="spinner_feeds3" class="calendarista-spinner calendarista-invisible">
													<img src="<?php echo CALENDARISTA_PLUGINDIR ?>assets/img/transparent.gif">
												</span>
												<br class="clear">
											</p>
										</div>
										<p>
											<input id="feedUrl" name="feedUrl" type="text" 
											class="regular-text" 
											data-parsley-required="true" 
											<?php if(!$this->isLocalhost()):?>
											data-parsley-type="url"
											<?php endif; ?>
											placeholder="Feed URL" />
										</p>
										<p class="description"><?php echo __('The feed found at the above URL will be synched with the selected service and/or availability.', 'calendarista') ?></p>
										<p class="description"><strong><?php echo __('Note!', 'calendarista') ?></strong>&nbsp;<?php echo __('To avoid undesired results, please do not import a local service.', 'calendarista') ?></p>
										<p>
											<button type="submit" name="calendarista_create" class="button button-primary">
												<?php echo __('Add New Feed', 'calendarista') ?>
											</button>
										</p>
									</form>
								</div>
							</div>
						</div>
					</div>
					<div class="column-pane calendarista-borderless-accordion">
						<div id="cron_job_timeout">
							<h3><?php echo __('Advanced import optimization', 'calendarista') ?></h3>
							<div>
								<form data-parsley-validate action="<?php echo $_SERVER['REQUEST_URI'] ?>" method="post">
									<input type="hidden" name="controller" value="calendarista_feeds">
									<input type="hidden" name="calendarista_nonce" value="<?php echo wp_create_nonce('calendarista-ajax-nonce') ?>"/>
									<?php if($this->feedList->count > 0):?>
									<p>
										<label for="cronJobFeedTimeout"><?php echo __('Feed synchronization interval', 'calendarista') ?></label>&nbsp;
										<input type="text" class="small-text" data-parsley-required="true" data-parsley-type="digits" id="cronJobFeedTimeout" name="cronJobFeedTimeout" value="<?php echo $this->setting->cronJobFeedTimeout ?>">
									</p>
									<p>
										<?php echo __('Value needs to be in seconds. A value of 0 means feeds are synced when the service is loaded in the front-end, which can impact performance so choose wisely.', 'calendarista') ?>
									</p>
									<p>
										<button type="submit" name="calendarista_update" class="button button-primary">
											<?php echo __('Update', 'calendarista') ?>
										</button>
									</p>
									<hr>
									<p>
										<button type="submit" name="calendarista_delete_all_imported" class="button button-primary">
											<?php echo __('Delete all imported', 'calendarista') ?>
										</button>
										<p class="description"><?php echo __('Careful, this will delete all imported appointments in all services.', 'calendarista') ?></p>
									</p>
									<?php else: ?>
									<p class="description"><?php echo __('You must import atleast one feed to configure the synchronization interval.', 'calendarista') ?></p>
									<?php endif; ?>
								</form>
							</div>
						</div>
					</div>
					<br class="clear">
					<form action="<?php echo $_SERVER['REQUEST_URI'] ?>" method="post">
						<input type="hidden" name="controller" value="calendarista_feeds">
						<input type="hidden" name="calendarista_nonce" value="<?php echo wp_create_nonce('calendarista-ajax-nonce') ?>"/>
						<?php $this->feedList->display(); ?>
						<p class="description"><?php echo __('The delete all button will delete the feed and also all previously synced data on that particular availability', 'calendarista') ?></p>
						<div>
							<button type="submit" name="calendarista_delete_many" class="button button-primary" disabled>
								<?php echo __('Delete', 'calendarista') ?>
							</button>
							<button type="submit" name="calendarista_delete_many_sync_data" title="<?php __('Delete Feed + Sync data', 'calendarista') ?>" class="button button-primary" disabled>
								<?php echo __('Delete All', 'calendarista') ?>
							</button>
						</div>
						</form>
				</div>
			</div>
		</div>
		<script type="text/javascript">
			(function($, wp){
				var calendarista = window['calendarista'] ? window['calendarista'] : function(){};
				calendarista.createDelegate = function (instance, method) {
					return function () {
						return method.apply(instance, arguments);
					};
				};
				calendarista.feeds = function(options){
					var context = this;
					$(window).ready(function(){
						context.init(options);
					});
				};
				calendarista.feeds.prototype.init = function(options){
					var context = this;
					this.ajaxUrl = wp.url;
					this.nonce = wp.nonce;
					this.requestUrl = options['requestUrl'];
					this.homeUrl = options['homeUrl'];
					this.appKey = options['appKey'];
					this.actionGetAvailabilities = 'calendarista_get_availabilities';
					this.actionUpdateFeedStatus = 'calendarista_update_feed_status';
					this.$exportFeedProjectList = $('.export-feed select[name="projectId"]');
					this.$exportFeedAvailabilityList = $('.export-feed select[name="availabilityId"]');
					this.$importFeedProjectList = $('.import-feed select[name="projectId"]');
					this.$importFeedAvailabilityList = $('.import-feed select[name="availabilityId"]');
					this.$feedListCheckboxes = $('.calendarista-feed-list input[name="feeds[]"]');
					this.$deleteManyButton = $('button[name="calendarista_delete_many"]');
					this.$deleteDeleteSyncDataButton = $('button[name="calendarista_delete_many_sync_data"]');
					this.$enableFeeds = $('input[name="enableFeeds"]');
					this.$feedUrl = $('textarea[name="feedUrl"]');
					this.$status = $('input[name="status"]');
					this.ajax1 = new Calendarista.ajax({'ajaxUrl': this.ajaxUrl, 'id': 'feeds1'});
					this.ajax2 = new Calendarista.ajax({'ajaxUrl': this.ajaxUrl, 'id': 'feeds2'});
					this.ajax3 = new Calendarista.ajax({'ajaxUrl': this.ajaxUrl, 'id': 'feeds3'});
					this.$enableFeeds.on('change', function(e){
						var model = [
							{ 'name': 'enableFeeds', 'value': this.checked ? 1 : 0 }
							, { 'name': 'action', 'value': context.actionUpdateFeedStatus }
							, { 'name': 'calendarista_nonce', 'value': context.nonce }
						];
						context.feedStatus(this.checked);
						context.ajax1.request(context, context.feedStatusResponse, $.param(model));
					});
					this.$exportFeedProjectList.on('change', function(e){
						var val = parseInt($(this).val(), 10)
							, model = [
								{ 'name': 'projectId', 'value': val}
								, { 'name': 'defaultLabel', 'value': '<?php echo $this->decodeString(__('Select an availability', 'calendarista')) ?>'}
								, { 'name': 'defaultValue', 'value': '-1'}
								, { 'name': 'action', 'value': context.actionGetAvailabilities }
								, { 'name': 'calendarista_nonce', 'value': context.nonce }
							];
						context.buildExportUrl();
						context.ajax2.request(context, context.exportAvailabilitiesResponse, $.param(model));
					});
					this.$exportFeedAvailabilityList.on('change', function(e){
						context.buildExportUrl();
					});
					this.$status.on('change', function(e){
						context.buildExportUrl();
					});
					this.feedStatus(this.$enableFeeds.is(':checked'));
					this.$importFeedProjectList.on('change', function(e){
						var val = parseInt($(this).val(), 10)
							, model = [
							{ 'name': 'projectId', 'value': val}
							, { 'name': 'defaultLabel', 'value': '<?php echo $this->decodeString(__('All Availabilities', 'calendarista')) ?>'}
							, { 'name': 'defaultValue', 'value': '-1'}
							, { 'name': 'action', 'value': context.actionGetAvailabilities }
							, { 'name': 'calendarista_nonce', 'value': context.nonce }
						];
						context.ajax3.request(context, context.importAvailabilitiesResponse, $.param(model));
					});
					$('#cron_job_timeout').accordion({
						collapsible: true
						, active: false
						, heightStyle: 'content'
						, autoHeight: false
						, clearStyle: true
					});
					$('input[name="selectall"]').on('change', function(){
						if(this.checked){
							context.$feedListCheckboxes.prop('checked', true);
						}else{
							context.$feedListCheckboxes.prop('checked', false);
						}
						context.checkedAll();
					});
					this.checkedAllDelegate = calendarista.createDelegate(this, this.checkedAll);
					this.$feedListCheckboxes.on('change', this.checkedAllDelegate);
				};
				calendarista.feeds.prototype.buildExportUrl = function(){
					var serviceValue = this.$exportFeedProjectList.val()
						, availabilityValue = this.$exportFeedAvailabilityList.val()
						, statusValue = this.$status.filter(':checked').val()
						, result;
					this.$feedUrl.text('');
					if(!serviceValue){
						return;
					}
					if(this.appKey){
						result = this.homeUrl + '?calendarista_handler=feeds&calendarista_appkey=' + this.appKey + '&calendarista_service=' + serviceValue;
					}
					if(availabilityValue){
						result += '&calendarista_availability=' + availabilityValue;
					}
					if(statusValue){
						result  += '&calendarista_status=' + statusValue;
					}
					this.$feedUrl.text(result);
				};
				calendarista.feeds.prototype.exportAvailabilitiesResponse = function(result){
					this.$exportFeedAvailabilityList[0].length = 0;
					this.$exportFeedAvailabilityList.append(result);
				};
				calendarista.feeds.prototype.importAvailabilitiesResponse = function(result){
					this.$importFeedAvailabilityList[0].length = 0;
					this.$importFeedAvailabilityList.append(result);
				};
				calendarista.feeds.prototype.feedStatusResponse = function(result){
					this.appKey = result;
				};
				calendarista.feeds.prototype.feedStatus = function(enabled){
					this.$exportFeedProjectList.prop('disabled', false);
					this.$exportFeedAvailabilityList.prop('disabled', false);
					this.$feedUrl.prop('disabled', false);
					if(!enabled){
						this.$exportFeedProjectList.prop('disabled', true);
						this.$exportFeedProjectList.val(-1);
						this.$exportFeedAvailabilityList.prop('disabled', true);
						this.$exportFeedAvailabilityList.val('');
						this.$feedUrl.prop('disabled', true);
						this.$feedUrl.text('');
					}
				};
				calendarista.feeds.prototype.checkedAll = function(){
					var hasChecked = this.$feedListCheckboxes.is(':checked');
					if(hasChecked){
						this.$deleteManyButton.prop('disabled', false);
						this.$deleteDeleteSyncDataButton.prop('disabled', false);
					}else{
						this.$deleteManyButton.prop('disabled', true);
						this.$deleteDeleteSyncDataButton.prop('disabled', true);
					}
				};
			window['calendarista'] = calendarista;
		})(window['jQuery'], window['calendarista_wp_ajax']);
		new calendarista.feeds({
			'requestUrl': '<?php echo $this->requestUrl ?>'
			, 'homeUrl': '<?php echo home_url('/') ?>'
			, 'appKey': '<?php echo $this->setting->appKey ?>'
		});
		</script>
		<?php
	}
}