<?php
class Calendarista_ManageHolidays extends Calendarista_ViewBase{
	public $id;
	public $availabilityId;
	public $availabilityDate;
	public $returnDate;
	public $holidayList;
	public $startDate;
	public $showExpired;
	public $availabilities;
	function __construct( ){
		parent::__construct(false, true, 'calendarista-specialdays', Calendarista_PermissionHelper::staffMemberProjects());
		$this->availabilityId = isset($_GET['availabilityId']) ? (int)$_GET['availabilityId'] : null;
		new Calendarista_HolidayController(array($this, 'updated'));
		$this->holidayList = new Calendarista_HolidayList();
		$this->holidayList->bind();
		if($this->selectedProjectId !== -1){
			$repo = new Calendarista_AvailabilityRepository();
			$this->availabilities = $repo->readAll($this->selectedProjectId);
		}
		$this->render();
	}
	function updated($result){
		?>
		<div class="calendarista calendarista-no-margin-notice updated notice is-dismissible">
			<p><?php echo __('The date(s) have been updated', 'calendarista'); ?></p>
		</div>
		<?php
	}
	public function render(){
	?>
	<div class="wrap">
		<div class="column-pane">
			<form data-parsley-validate="">
				<?php foreach($_GET as $key=>$value):?>
				<input type="hidden" name="<?php echo $key ?>" value="<?php echo $value ?>">
				<?php endforeach; ?>
				<?php $this->renderProjectSelectList(true, __('Select a services', 'calendarista'), true, true, array(Calendarista_CalendarMode::PACKAGE)) ?>
				&nbsp;<select name="availabilityId" data-parsley-required="true" data-parsley-errors-messages-disabled="true">
					<option value=""><?php echo __('Select an availability', 'calendarista') ?></option>
					<?php if($this->availabilities):?>
						<?php foreach($this->availabilities as $availability):?>
							<option value="<?php echo $availability->id ?>" <?php echo $availability->id === $this->availabilityId ? 'selected' : ''?>><?php echo $availability->name ?></option>
						<?php endforeach;?>
					<?php endif;?>
				</select>
				<label><?php echo __('Month', 'calendarista') ?>: </label>
				<input type="text" id="month" name="month" class="monthPicker" autocomplete="off"
					data-parsley-required="true" data-parsley-errors-messages-disabled="true"/>
				<button type="submit" class="button button-primary">
					<?php echo __('Submit', 'calendarista') ?>
				</button>
			</form>
			<div id="spinner_holiday" class="calendarista-spinner calendarista-invisible">
				<img src="<?php echo CALENDARISTA_PLUGINDIR ?>assets/img/transparent.gif"><?php echo __('Loading availabilities...', 'calendarista') ?>
			</div>
		</div>
	</div>
	<div class="wrap">
		<div class="column-pane">
			<form action="<?php echo $_SERVER['REQUEST_URI'] ?>" method="post">
				<input type="hidden" name="controller" value="calendarista_holiday">
				<input type="hidden" name="availabilityId" value="<?php echo $this->availabilityId ?>">
				<input type="hidden" name="projectId" value="<?php echo $this->selectedProjectId ?>">
				<p class="description">
					<input type="checkbox" name="apply_all"> <?php echo __('Apply the changes below to the entire service', 'calendarista') ?>
				</p>
				<p>
					<button type="submit" name="calendarista_update" class="button button-primary" disabled><?php echo __('Update', 'calendarista') ?></button>
				</p>
				<p class="description">
					<strong><?php echo __('Check a row(s) to take a day off. To reinstate a date, uncheck it.', 'calendarista')?></strong>
				</p>
				<?php $this->holidayList->display(); ?>
				<?php if($this->holidayList->fullDay): ?>
					<p>
						<button type="submit" name="calendarista_update" class="button button-primary" disabled><?php echo __('Update', 'calendarista') ?></button>
					</p>
				<?php endif; ?>
			</form>
		</div>
	</div>
	<div class="timeoff-modal calendarista" 
			title="<?php echo __('Take time off', 'calendarista') ?>">
		<div class="container-fluid">
			<span id="spinner_timeoff" class="calendarista-spinner calendarista-invisible">
				<img src="<?php echo CALENDARISTA_PLUGINDIR ?>assets/img/transparent.gif">
			</span>
			<div class="timeoff_placeholder"></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.holidays = function(options){
				var context = this;
				$(window).ready(function(){
					context.init(options);
				});
			};
			calendarista.holidays.prototype.init = function(options){
				var context = this;
				this.ajaxUrl = wp.url;
				this.nonce = wp.nonce;
				this.requestUrl = options['requestUrl'];
				this.actionGetAvailabilities = 'calendarista_get_availabilities';
				this.actionTimeoff = 'calendarista_timeoff';
				this.$timeoffPlaceHolder = $('.timeoff_placeholder');
				this.$holidayListCheckboxes = $('.calendarista-holiday-list input[type="checkbox"]');
				this.$updateButton = $('button[name="calendarista_update"]');
				this.$updateAllCheckbox = $('input[name="updateall"]');
				this.$searchFilterProjectList = $('select[name="projectId"]');
				this.$availabilityList = $('select[name="availabilityId"]');
				this.$timeoffButton = $('button.timeoff');
				this.ajax1 = new Calendarista.ajax({'ajaxUrl': this.ajaxUrl, 'id': 'holiday'});
				this.ajax2 = new Calendarista.ajax({'ajaxUrl': this.ajaxUrl, 'id': 'timeoff'});
				this.checkedAllDelegate = calendarista.createDelegate(this, this.checkedAll);
				this.$holidayListCheckboxes.on('change', this.checkedAllDelegate);
				$('.monthPicker').datepicker({
					dateFormat: 'yy-mm-01',
					changeMonth: true,
					changeYear: true,
					showButtonPanel: true,
					closeText: '<?php echo $this->decodeString(__('Select', 'calendarista')) ?>',
					onClose: function(dateText, inst) {
						var month = $('#ui-datepicker-div .ui-datepicker-month :selected').val()
							, year = $('#ui-datepicker-div .ui-datepicker-year :selected').val();
						$(this).val($.datepicker.formatDate('yy-mm-01', new Date(year, month, 1)));
					}
				});
				$('.monthPicker').focus(function () {
					$('.ui-datepicker-calendar').hide();
					$('#ui-datepicker-div').position({
						my: 'center top',
						at: 'center bottom',
						of: $(this)
					});
				});
				this.$updateAllCheckbox.on('change', function(){
					if(this.checked){
						context.$holidayListCheckboxes.prop('checked', true);
					}else{
						context.$holidayListCheckboxes.prop('checked', false);
					}
					context.checkedAll();
				});
				this.$searchFilterProjectList.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': ''}
							, { 'name': 'action', 'value': context.actionGetAvailabilities }
							, { 'name': 'calendarista_nonce', 'value': context.nonce }
						];
					context.ajax1.request(context, context.availabilitiesResponse, $.param(model));
				});
				this.$timeoffButton.on('click', function(e){
					var result
						, $this = $(this)
						, projectId = parseInt(context.$searchFilterProjectList.val(), 10)
						, availabilityId = parseInt(context.$availabilityList.val(), 10)
						, date = $this.attr('data-selected-date')
						, model = [
							{ 'name': 'projectId', 'value': projectId }
							, { 'name': 'availabilityId', 'value': availabilityId }
							, { 'name': 'selectedDate', 'value': date }
							, { 'name': 'action', 'value': context.actionTimeoff }
							, { 'name': 'calendarista_nonce', 'value': context.nonce }
						];
						context.$timeoffModalDialog.dialog('open');
						context.ajax2.request(context, context.timeoffResponse, $.param(model));
						return false;
				});
				this.$timeoffModalDialog = $('.timeoff-modal').dialog({
					autoOpen: false
					, height: '480'
					, width: '640'
					, modal: true
					, resizable: false
					, dialogClass: 'calendarista-dialog'
					, create: function() {
						var spinner = '<div id="spinner_timeoff" class="calendarista-spinner ui-widget ui-button calendarista-invisible">';
							spinner += '<img src="<?php echo CALENDARISTA_PLUGINDIR ?>assets/img/transparent.gif">';
							spinner += '</div>';
						$(this).dialog('widget').find('.ui-dialog-buttonset').prepend(spinner);
						$(this).closest('div.ui-dialog').find('.ui-dialog-titlebar-close').on('click', function(e) {
						   e.preventDefault();
						   context.$timeoffPlaceHolder.empty();
						});
					}
					, buttons: [
						{
							'text': 'Update'
							, 'name': 'updateTimeoff'
							, 'click':  function(){
								var model = context.$timeoffModalDialog.find('form').serialize();
								model += '&calendarista_nonce=' + context.nonce + '&calendarista_update=0&action=' + context.actionTimeoff;
								context.ajax1.request(context, context.timeoffResponse, model);
							}
						}
						, {
							'text': 'Close'
							, 'click':  function(){
								context.$timeoffModalDialog.dialog('close');
								context.$timeoffPlaceHolder.empty();
							}
						}
					]
				});
			};
			calendarista.holidays.prototype.timeoffResponse = function(result){
				this.$timeoffPlaceHolder.replaceWith('<div class="timeoff_placeholder">' + result + '</div>');
				this.$timeoffPlaceHolder = $('.timeoff_placeholder');
			};
			calendarista.holidays.prototype.availabilitiesResponse = function(result){
				this.$availabilityList[0].length = 0;
				this.$availabilityList.append(result);
			};
			calendarista.holidays.prototype.checkedAll = function(){
				var hasChecked = this.$holidayListCheckboxes.is(':checked');
				if(hasChecked){
					this.$updateButton.prop('disabled', false);
				}else{
					this.$updateButton.prop('disabled', true);
				}
			};
		window['calendarista'] = calendarista;
	})(window['jQuery'], window['calendarista_wp_ajax']);
	new calendarista.holidays({
		'requestUrl': '<?php echo $_SERVER['REQUEST_URI'] ?>'
		, 'selectedTabIndex': <?php echo $this->selectedTab ?>
	});
	</script>
		<?php
	}
}