<?php
class Calendarista_DynamicFieldTemplate extends Calendarista_ViewBase{
	public $dynamicField;
	public $dynamicFieldPricing;
	public $dynamicFieldList;
	public $selectedDynamicFieldId;
	public $availabilityId;
	public $availabilities;
	public $availability;
	public $groupBooking;
	public $project;
	public $newUrl;
	public $id;
	function __construct(){
		$this->availabilityId = isset($_GET['availabilityId']) ? (int)$_GET['availabilityId'] : null;
		$this->selectedDynamicFieldId = isset($_GET['id']) ? (int)$_GET['id'] : -1;
		if($this->availabilityId){
			$repo = new Calendarista_AvailabilityRepository();
			$this->availability = $repo->read($this->availabilityId);
		}
		parent::__construct();
		new Calendarista_DynamicFieldController(
			array($this, 'createdDynamicField')
			, array($this, 'updatedDynamicField')
			, array($this, 'deletedDynamicField')
		);
		new Calendarista_DynamicFieldPricingController(
			array($this, 'createdPricingField')
			, array($this, 'updatedPricingField')
			, array($this, 'deletedPricingField')
		);
		$this->dynamicFieldList = new Calendarista_DynamicFieldList();
		$this->dynamicFieldList->bind();
		$this->dynamicField = new Calendarista_DynamicField(array('id'=>0, 'label'=>'', 'byOptional'=>false, 'limitBySeat'=>false, 'cost'=>null, 'required'=>false, 'fixedCost'=>false, 'data'=>array(array('seat'=>0, 'min'=>0, 'max'=>0, 'cost'=>0, 'new'=>true))));
		if($this->selectedDynamicFieldId !== -1){
			$dynamicFieldRepo = new Calendarista_DynamicFieldRepository();
			$this->dynamicField = $dynamicFieldRepo->read($this->selectedDynamicFieldId);
			if($this->dynamicField && count($this->dynamicField->data) === 0){
				array_push($this->dynamicField->data, array('seat'=>0, 'min'=>0, 'max'=>0, 'cost'=>0, 'new'=>true));
			}
			$dynamicFieldPricingRepo = new Calendarista_DynamicFieldPricingRepository();
			$this->dynamicFieldPricing = $dynamicFieldPricingRepo->readByDynamicFieldId($this->selectedDynamicFieldId);
			if(!is_array($this->dynamicFieldPricing)){
				$this->dynamicFieldPricing = array();
			}
			array_push($this->dynamicFieldPricing, array('id'=>null, 'cost'=>null, 'fieldValue'=>null, 'new'=>true));
		}
		$this->project = $this->getProject();
		if(!$this->project){
			return;
		}
		$availabilityRepo = new Calendarista_AvailabilityRepository();
		$this->availabilities = $availabilityRepo->readAll($this->selectedProjectId);
		$this->requestUrl = admin_url() . 'admin.php?page=calendarista-index';
        if($this->selectedTab !== null){
			$this->requestUrl .= '&calendarista-tab=' . $this->selectedTab;
		}
		$this->requestUrl .= '&projectId=' . $this->selectedProjectId;
		if($this->availabilityId){
			$this->requestUrl .= '&availabilityId=' . $this->availabilityId;
		}
		$this->newUrl = $this->requestUrl;
		if($this->selectedDynamicFieldId != -1){
			$this->requestUrl .= '&id=' . $this->selectedDynamicFieldId;
		}
		$this->render();
	}
	public function duplicateDynamicFieldNotice(){
		?>
		<div class="index error notice is-dismissible">
			<p><?php echo __('A guest field with the same number of seats already exists, aborted.', 'calendarista'); ?></p>
		</div>
		<?php
	}
	public function createdDynamicField($id){
		?>
		<div class="index updated notice is-dismissible calendarista-notice">
			<p><?php echo __('The guest field has been created. Now add individual item value', 'calendarista'); ?></p>
		</div>
		<?php
	}
	public function updatedDynamicField($id){
		$this->selectedDynamicFieldId = $id;
		?>
		<div class="index updated notice is-dismissible calendarista-notice">
			<p><?php echo __('The guest field has been updated.', 'calendarista'); ?></p>
		</div>
		<?php
	}
	public function deletedDynamicField(){
		$this->selectedDynamicFieldId = -1;
		?>
		<div class="index updated notice is-dismissible calendarista-notice">
			<p><?php echo __('The guest field item has been deleted.', 'calendarista'); ?></p>
		</div>
		<?php
	}
	public function createdPricingField($id, $duplicate){
		if($duplicate): ?>
		<div class="index error notice is-dismissible">
			<p><?php echo __('Price for the selected number of guests already exists, aborted.', 'calendarista'); ?></p>
		</div>
		<?php else: ?>
		<div class="index updated notice is-dismissible calendarista-notice">
			<p><?php echo __('A price has been set for the selected number of guest(s).', 'calendarista'); ?></p>
		</div>
		<?php endif; 
	}
	public function updatedPricingField($id, $duplicate){
		if($duplicate): ?>
		<div class="index error notice is-dismissible">
			<p><?php echo __('Price for the selected number of guests already exists, aborted.', 'calendarista'); ?></p>
		</div>
		<?php else: ?>
		<div class="index updated notice is-dismissible calendarista-notice">
			<p><?php echo __('The price has been updated for the selected number of guest(s).', 'calendarista'); ?></p>
		</div>
		<?php endif; 
	}
	public function deletedPricingField(){
		?>
		<div class="index updated notice is-dismissible calendarista-notice">
			<p><?php echo __('The price for the selected number of guest(s) has been deleted.', 'calendarista'); ?></p>
		</div>
		<?php
	}
	public function render(){
	?>
		<?php if($this->selectedDynamicFieldId !== -1): ?>
		<div class="column-pane">
			<br class="clear">
			<p class="description"><?php echo sprintf(__('Cost by number of %s', 'calendarista'), Calendarista_StringResourceHelper::decodeString($this->dynamicField->label)) ?></p>
			<form data-parsley-validate action="<?php echo $this->requestUrl ?>" method="post">
				<input type="hidden" name="controller" value="dynamic_field_pricing" />
				<input type="hidden" name="dynamicFieldId" value="<?php echo $this->selectedDynamicFieldId ?>"/>
				<input type="hidden" name="calendarista_nonce" value="<?php echo wp_create_nonce('calendarista-ajax-nonce') ?>"/>
				<table class="wp-list-table calendarista widefat fixed striped">
					<thead>
						<th><input type="checkbox" name="del_all_price_fields" value="dynamicfield-container3">
						<th><?php echo __('Cost', 'calendarista') ?></th>
						<th><?php echo sprintf(__('No. of %s', 'calendarista'), Calendarista_StringResourceHelper::decodeString($this->dynamicField->label)) ?></th>
						<th></th>
					</thead>
					<tbody class="dynamicfield-container3">
						<?php for($i = 0; $i < count($this->dynamicFieldPricing); $i++):?>
						<tr>
							<td>
								<?php if($this->dynamicFieldPricing[$i]['id']):?>
								<input type="checkbox" name="priceFields[]" value="<?php echo $this->dynamicFieldPricing[$i]['id'] ?>" 
									 <?php echo !$this->dynamicFieldPricing[$i]['id'] ? 'disabled' : '' ?>>
								<?php endif; ?>
							</td>
							<td>
								<input id="cost_<?php echo $this->dynamicFieldPricing[$i]['id'] ?>" 
										name="cost_<?php echo $this->dynamicFieldPricing[$i]['id'] ?>" 
										type="text" 
										class="small-text" 
										data-parsley-trigger="change focusout"
										data-parsley-min="0"
										data-parsley-pattern="^\d+(\.\d{1,2})?$"
										data-parsley-errors-container="#dynamic_field_error_container3"
										placeholder="0.00"
										value="<?php echo $this->emptyStringIfZero($this->dynamicFieldPricing[$i]['cost']) ?>" />
								</td>
							<td>
								<input id="fieldValue_<?php echo $this->dynamicFieldPricing[$i]['id'] ?>" 
									name="fieldValue_<?php echo $this->dynamicFieldPricing[$i]['id'] ?>" 
									type="text" 
									class="small-text" 
									data-parsley-trigger="change focusout"
									placeholder="0"
									data-parsley-type="digits"
									data-parsley-errors-container="#dynamic_field_error_container3"
									value="<?php echo $this->emptyStringIfZero($this->dynamicFieldPricing[$i]['fieldValue']) ?>" />
							</td>
							<td>
								<button type="submit" name="calendarista_<?php echo !$this->dynamicFieldPricing[$i]['id'] ? 'create' : 'update' ?>" class="button button-primary" 
								value="<?php echo $this->dynamicFieldPricing[$i]['id'] ?>">
								<?php echo !$this->dynamicFieldPricing[$i]['id'] ? __('Add', 'calendarista') : __('Update', 'calendarista') ?>
								</button>
								<?php if($this->dynamicFieldPricing[$i]['id']):?>
								&nbsp;|&nbsp;
								<button type="submit" name="calendarista_delete" class="button button-primary" value="<?php echo $this->dynamicFieldPricing[$i]['id'] ?>">
								<?php echo  __('Delete', 'calendarista') ?>
								</button>
								<?php endif; ?>
							</td>
						</tr>
					<?php endfor; ?>
					</tbody>
				</table>
				<div id="dynamic_field_error_container3"></div>
				<p>
				<button type="submit" name="calendarista_delete" class="button button-primary calendarista-delete-dynamic-pricing-field" disabled>
				<?php echo __('Delete', 'calendarista') ?>
				</button>
				</p>
			</form>
		</div>
		<?php endif; ?>
		<div class="column-pane">
			<form data-parsley-validate action="<?php echo $this->requestUrl ?>" method="post">
				<input type="hidden" name="calendarista_nonce" value="<?php echo wp_create_nonce('calendarista-ajax-nonce') ?>"/>
				<select name="availabilityId" id="availabilityId" data-parsley-required="true" class="calendarista_parsley_validated">
				<option value=""><?php echo __('Select an availability', 'calendarista'); ?></option>
				<?php foreach($this->availabilities as $availability):?>
					<option value="<?php echo $availability->id; ?>" <?php echo $availability->id === $this->availabilityId ? 'selected=selected' : '';?>><?php echo $availability->name; ?></option>
				<?php endforeach;?>
				</select>
			</form>
			<br class="clear">
			<form data-parsley-validate action="<?php echo $this->requestUrl ?>" method="post">
				<input type="hidden" name="controller" value="dynamic_field" />
				<input type="hidden" name="projectId" value="<?php echo $this->selectedProjectId ?>"/>
				<input type="hidden" name="availabilityId" value="<?php echo $this->availabilityId ?>"/>
				<input type="hidden" name="calendarista_nonce" value="<?php echo wp_create_nonce('calendarista-ajax-nonce') ?>"/>
				<table class="widefat">
					<thead>
						<th><?php echo __('Guest Label', 'calendarista') ?></th>
						<th title="<?php echo __('Limit by seat', 'calendarista') ?>"><?php echo __('Limit by seat', 'calendarista') ?></th>
						<th><?php echo __('Required', 'calendarista') ?></th>
						<th><?php echo __('Fixed Cost', 'calendarista') ?></th>
						<th title="<?php echo __('Calculate optional cost by each guest', 'calendarista') ?>"><?php echo __('Guest x Optional', 'calendarista') ?></th>
						<th><?php echo __('Cost', 'calendarista') ?></th>
						<th><?php echo __('Min', 'calendarista') ?></th>
						<th><?php echo __('Max', 'calendarista') ?></th>
					</thead>
					<tbody>
						<td>
								<input id="label" 
									name="label" 
									type="text" 
									class="medium-text" 
									data-parsley-trigger="change focusout"
									data-parsley-required="true"
									data-parsley-errors-container="#dynamic_field_error_container1"
									value="<?php echo Calendarista_StringResourceHelper::decodeString($this->dynamicField->label) ?>" />
							</td>
							<td>
								<input id="limitBySeat" 
									name="limitBySeat" 
									type="checkbox" 
									title="<?php echo __('Limit by seat', 'calendarista') ?>"
									<?php echo $this->dynamicField->limitBySeat ? 'checked' : '' ?> />
							</td>
							<td>
								<input id="required" 
									name="required" 
									type="checkbox" 
									title="<?php echo __('Required', 'calendarista') ?>"
									<?php echo $this->dynamicField->required ? 'checked' : '' ?> />
							</td>
							<td>
								<input id="fixedCost" 
									name="fixedCost" 
									type="checkbox" 
									title="<?php echo __('Fixed Cost', 'calendarista') ?>"
									<?php echo $this->dynamicField->fixedCost ? 'checked' : '' ?> />
							</td>
							<td>
								<input id="byOptional" 
									name="byOptional" 
									type="checkbox" 
									title="<?php echo __('Calculate optional cost by each guest', 'calendarista') ?>"
									<?php echo $this->dynamicField->byOptional ? 'checked' : '' ?> />
							</td>
							<td>
								<input id="cost" 
									name="cost" 
									type="text" 
									class="small-text" 
									data-parsley-trigger="change focusout"
									data-parsley-min="0"
									data-parsley-pattern="^\d+(\.\d{1,2})?$"
									placeholder="0.00"
									data-parsley-errors-container="#dynamic_field_error_container1"
									value="<?php echo $this->emptyStringIfZero($this->dynamicField->cost) ?>" />
							</td>
							<td>
								<input id="min_0" 
									name="min_0" 
									type="text" 
									class="small-text" 
									data-parsley-trigger="change focusout"
									placeholder="0"
									data-parsley-type="digits"
									data-parsley-errors-container="#dynamic_field_error_container1"
									value="<?php echo $this->emptyStringIfZero($this->dynamicField->data[0]['min']) ?>" />
							</td>
							<td>
								<input id="max_0" 
									name="max_0" 
									type="text" 
									class="small-text" 
									data-parsley-trigger="change focusout"
									placeholder="0"
									data-parsley-type="digits"
									data-parsley-errors-container="#dynamic_field_error_container1"
									value="<?php echo $this->emptyStringIfZero($this->dynamicField->data[0]['max']) ?>" />
							</td>
					</tbody>
				</table>
				<div id="dynamic_field_error_container1"></div>
				<p class="description">
					<?php echo __('Note 1: Max value must not exceed the value of seats, if limit by seat is checked.', 'calendarista') ?>
					<br>
					<?php echo __('Note 2: Cost will apply as base cost if pricing is not set.', 'calendarista') ?>
				</p>
				<p class="submit">
					<button type="submit" name="calendarista_<?php echo !$this->dynamicField->id ? 'create' : 'update' ?>" class="button button-primary" 
						value="<?php echo $this->dynamicField->id ?>"
						<?php echo !$this->availabilityId ? 'disabled' : '' ?>>
						<?php echo !$this->dynamicField->id ? __('Add', 'calendarista') : __('Update', 'calendarista') ?>
					</button>
					<button type="submit" name="calendarista_delete" class="button button-primary" value="<?php echo $this->dynamicField->id ?>" <?php echo !$this->dynamicField->id ? 'disabled': ''?>>
						<?php echo  __('Delete', 'calendarista') ?>
					</button>
					<?php if($this->selectedDynamicFieldId !== -1 && $this->availabilityId): ?>
					<a href="<?php echo $this->newUrl ?>" id="calendarista_<?php echo 'new' ?>" class="button button-primary">
						<?php echo __('New', 'calendarista') ?>
					</a>
					<?php endif; ?>
				<p>
			</form>
			<hr>
			<form data-parsley-validate action="<?php echo $this->requestUrl ?>" method="post">
				<input type="hidden" name="controller" value="dynamic_field" />
				<input type="hidden" name="calendarista_nonce" value="<?php echo wp_create_nonce('calendarista-ajax-nonce') ?>"/>
				<div>
					<?php $this->dynamicFieldList->display(); ?>
				</div>
			</form>
		</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.dynamicField = function(options){
					var context = this;
					$(window).ready(function(){
						context.init(options);
					});
				};
				calendarista.dynamicField.prototype.init = function(options){
					var context = this;
					this.ajaxUrl = wp.url;
					this.nonce = wp.nonce;
					this.requestUrl = options['requestUrl'];
					this.$availabilityId = $('select[name="availabilityId"]');
					this.$deleteAllPriceFields = $('input[name="del_all_price_fields"]');
					this.$dynamicPricingFieldCheckboxes = $('.dynamicfield-container3 input[type="checkbox"]:not(:disabled)');
					this.$dynamicPricingFieldDeleteButton = $('.calendarista-delete-dynamic-pricing-field');
					this.$availabilityId.on('change', function(e){
						var selectedIndex = parseInt($(this).val(), 10)
							, requestUrl = context.requestUrl.replace(/&?availabilityId=([^&]$|[^&]*)/i, "");
						if(selectedIndex){
							requestUrl += '&availabilityId=' + selectedIndex;
						}
						window.location.href = requestUrl;
					});
					this.$dynamicPricingFieldCheckboxes.on('change', function(e){
						context.deleteDynamicFieldButtonState();
					});
					this.$deleteAllPriceFields.on('change', function(e){
						context.checkboxState(this);
					});
				};
				calendarista.dynamicField.prototype.checkboxState = function(target){
					var $target = $(target)
							, checked = $target.is(':checked')
							, $container = $('.' + $target.val())
							, $checkboxes = $container.find('input[type="checkbox"]:not(:disabled)');
						if(checked){
							$checkboxes.prop('checked', true);
						}else{
							$checkboxes.prop('checked', false);
						}
						this.deleteDynamicFieldButtonState();
				};
				calendarista.dynamicField.prototype.deleteDynamicFieldButtonState = function(){
					var hasChecked = this.$dynamicPricingFieldCheckboxes.is(':checked');
					if(hasChecked){
						this.$dynamicPricingFieldDeleteButton.prop('disabled', false);
					}else{
						this.$dynamicPricingFieldDeleteButton.prop('disabled', true);
					}
			};
			window['calendarista'] = calendarista;
		})(window['jQuery'], window['calendarista_wp_ajax']);
		new calendarista.dynamicField({'requestUrl': '<?php echo $this->newUrl ?>'});
		</script>
		<?php
	}
}