<?php
class Calendarista_ExportTemplate extends Calendarista_ViewBase{
	public $exportUrl;
	function __construct( ){
		parent::__construct(false, true, 'calendarista-settings');
		$this->exportUrl = home_url('/') . '?calendarista_handler=export';
		$this->render();
	}
	
	public function render(){
	?>
	<div class="wrap">
		<div class="column-pane">
			<p class="description"><?php echo __('Export bookings', 'calendarista') ?></p>
			<div class="searchfilter">
				<form id="exportForm" action="<?php echo $this->requestUrl ?>" method="post" data-parsley-validate>
					<p>
					<?php $this->renderProjectSelectList(true, __('Select a service', 'calendarista'), true, true) ?>
					&nbsp;<?php echo __('and', 'calendarista') ?>&nbsp;
					<select name="availabilityId">
						<option value="-1"><?php echo __('All availabilities', 'calendarista') ?></option>
					</select>
					</p>
					<p>
					<label for="from"><?php echo __('On or after', 'calendarista') ?></label>
					<input 
						type="text" 
						id="from" 
						name="from" 
						class="medium-text enable-readonly-input" 
						readonly
						data-parsley-trigger="change"
						data-parsley-required="true"
						data-parsley-errors-messages-disabled="true">
					<label for="to"><?php echo __('or between', 'calendarista') ?></label>
					<input 
						type="text" 
						id="to" 
						name="to" 
						class="medium-text enable-readonly-input" 
						readonly>
					&nbsp;|&nbsp;
					<input type="text" 
						id="email" 
						name="email" 
						class="medium-text"
						placeholder="<?php echo __('customer email', 'calendarista') ?>"
						data-parsley-errors-messages-disabled="true"
						data-parsley-type="email" 
						data-parsley-trigger="change" />
					&nbsp;&nbsp;<span id="spinner_callback" class="calendarista-spinner calendarista-invisible">
						<img src="<?php echo CALENDARISTA_PLUGINDIR ?>assets/img/transparent.gif">
					</span>
					</p>
					<p>
					<?php do_action('calendarista_export_custom_field') ?>
					<input type="hidden" name="custom_field_name" value="<?php do_action('calendarista_export_custom_field_value') ?>">
					<input type="checkbox" name="includeSales"><?php echo __('Include sales data', 'calendarista') ?>
					&nbsp;
					<input type="checkbox" name="includeOptionals"><?php echo __('Include optional extras data', 'calendarista') ?>
					&nbsp;
					<input type="checkbox" name="includeFormFields"><?php echo __('Include custom form fields data', 'calendarista') ?>
					&nbsp;
					<input type="checkbox" name="includeMap"><?php echo __('Include departure, destination and waypoints', 'calendarista') ?>
					</p>
					<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>
					<p>
					<button class="button button-primary" name="export">
						<i class="fa fa-download"></i>
						<?php echo __('Get CSV', 'calendarista') ?>
					</button>
					</p>
					
				</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.export = function(options){
				var context = this;
				$(window).ready(function(){
					context.init(options);
				});
			};
			calendarista.export.prototype.init = function(options){
				var context = this;
				this.ajaxUrl = wp.url;
				this.nonce = wp.nonce;
				this.requestUrl = options['requestUrl'];
				this.exportUrl = options['exportUrl'];
				this.nonce = options['nonce'];
				this.dateFormat = 'yy-mm-dd';
				this.selectedTabIndex = options['selectedTabIndex'];
				this.actionGetAvailabilities = 'calendarista_get_availabilities';
				this.$projectList = $('select[name="projectId"]');
				this.$availabilityList = $('select[name="availabilityId"]');
				this.$exportForm = $('#exportForm');
				this.$exportButton = $('button[name="export"]');
				this.$email = $('input[name="email"]');
				this.$customFieldName = $('input[name="custom_field_name"]');
				this.$includeSales = $('input[name="includeSales"]');
				this.$includeOptionals = $('input[name="includeOptionals"]');
				this.$includeFormFields = $('input[name="includeFormFields"]');
				this.$includeMap = $('input[name="includeMap"]');
				this.$status = $('input[name="status"]');
				this.ajax1 = new Calendarista.ajax({'ajaxUrl': this.ajaxUrl, 'id': 'callback'});
				this.$projectList.on('change', function(e){
					var val = parseInt($(this).val(), 10)
						, model = [
							{ 'name': 'projectId', 'value': val}
							, { 'name': 'action', 'value': context.actionGetAvailabilities }
							, { 'name': 'calendarista_nonce', 'value': context.nonce }
						];
					context.ajax1.request(context, context.availabilitiesResponse, $.param(model));
				});
				this.$availabilityList.on('change', function(e){
					//nothing yet..
				});
				this.datepickerOptions = {
					'dateFormat': this.dateFormat
					, 'showButtonPanel': true
					, 'closeText': 'Clear'
					, 'onClose': function (dateText, inst){
						if ($(window.event.srcElement).hasClass('ui-datepicker-close')){
							if(this.id === 'from'){
								context.$toDate.datepicker('option' , {setDate: null, minDate: null, maxDate: null}).val('');
							}else if(this.id === 'to'){
								$(this).datepicker('option' , {setDate: null}).val('');
								return;
							}
							$(this).datepicker('option' , {setDate: null, minDate: null, maxDate: null}).val('');
						}
					}
				};
				this.$fromDate = $('input[name="from"]');
				this.$toDate = $('input[name="to"]');
				this.$fromDate.datepicker(this.datepickerOptions).on('change', function(){
					context.$toDate.datepicker('option', 'minDate', context.getDate(this));
				});
				this.$toDate.datepicker(this.datepickerOptions).on('change', function(){
					context.$fromDate.datepicker('option', 'maxDate', context.getDate(this));
				});
				this.$exportButton.on('click', function(e){
					var statusValue = context.$status.filter(':checked').val()
						, $customField
						, url = context.exportUrl 
							+ '&calendarista_projectid=' + context.$projectList.val()
							+ '&calendarista_availabilityid=' + context.$availabilityList.val()
							+ '&calendarista_from=' + context.$fromDate.val()
							+ '&calendarista_to=' + context.$toDate.val()
							+ '&calendarista_email=' + context.$email.val()
							+ '&calendarista_dynamicfields=true'
							+ '&calendarista_nonce=' + context.nonce;
					if(context.$customFieldName.val()){
						$customField = $('input[name="' + context.$customFieldName.val() + '"]');
						if($customField.length > 0 && $customField.is(':checked')){
							url += '&' + context.$customFieldName.val();
						}
					}
					if(context.$includeSales.is(':checked')){
						url += '&calendarista_sales=true';
					}
					if(context.$includeOptionals.is(':checked')){
						url += '&calendarista_optionals=true';
					}
					if(context.$includeFormFields.is(':checked')){
						url += '&calendarista_formfields=true';
					}
					if(context.$includeMap.is(':checked')){
						url += '&calendarista_map=true';
					}
					if(statusValue != '-1'){
						url += '&calendarista_status=' + statusValue;
					}
					e.preventDefault();
					if($.trim(context.$email.val())){
						context.$email.parsley().validate();
						context.$projectList.parsley().validate();
						if(!context.$email.parsley().isValid() || !context.$projectList.parsley().isValid()){
							return;
						}
					}else{
						context.$exportForm.parsley().validate();
						if(!context.$exportForm.parsley().isValid()){
							return;
						}
					}
					window.location.href = url;
				});
			};
			calendarista.export.prototype.getDate =  function getDate(element) {
			  var date;
			  try {
				date = $.datepicker.parseDate(this.dateFormat, element.value);
			  } catch( error ) {
				date = null;
			  }
		 
			  return date;
			};
			calendarista.export.prototype.availabilitiesResponse = function(result){
				this.$availabilityList[0].length = 0;
				this.$availabilityList.append(result);
			};
		window['calendarista'] = calendarista;
	})(window['jQuery'], window['calendarista_wp_ajax']);
	new calendarista.export({
		'requestUrl': '<?php echo $_SERVER['REQUEST_URI'] ?>'
		, 'selectedTabIndex': <?php echo $this->selectedTab ?>
		, 'exportUrl': '<?php echo $this->exportUrl ?>'
		, 'nonce': '<?php echo wp_create_nonce('calendarista-ajax-nonce') ?>'});
	</script>
		<?php
	}
}