<?php
class Calendarista_ManageStaff extends Calendarista_ViewBase{
	public $staffList;
	public $availabilityId;
	public $name;
	public $email;
	public $availabilities;
	function __construct( ){
		parent::__construct(false, true, 'calendarista-staff');
		if(array_key_exists('calendarista_delete', $_POST)){
			$this->deleteStaff();
		}
		$this->staffList = new Calendarista_StaffList();
		$this->staffList->bind();
		$this->availabilityId = isset($_GET['availabilityId']) ? (int)$_GET['availabilityId'] : null;
		$this->name = isset($_GET['name']) ? $_GET['name'] : null;
		$this->email = isset($_GET['email']) ? $_GET['email'] : null;
		if($this->selectedProjectId !== -1){
			$repo = new Calendarista_AvailabilityRepository();
			$this->availabilities = $repo->readAll($this->selectedProjectId);
		}
		$this->render();
	}
	public function deleteStaff(){
		if (!(array_key_exists('controller', $_POST) 
			&& $_POST['controller'] == 'calendarista_staff')){
			return;
		}
		$val = isset($_POST['members']) ? (array)$_POST['members'] : array();
		$staffMembers = array_map('intval', $val);
		$staffRepository = new Calendarista_StaffRepository();
		foreach($staffMembers as $staff){
			$staffRepository->delete($staff);
		}
		?>
		<div class="wrap">
			<div class="calendarista-notice update notice is-dismissible">
				<p><?php echo __('Staff member(s) have been deleted successfully.', 'calendarista'); ?></p>
			</div>
			<hr>
		</div>
		<?php
	}
	public function render(){
	?>
		<div class="wrap" id="manage_staff_filter">
			<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) ?>
					<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> 
					&nbsp;<?php echo __('optionally filter by name', 'calendarista') ?>
					&nbsp;<input type="text" id="name" name="name" value="<?php echo $this->name ?>" />
					&nbsp;<?php echo __('or email', 'calendarista') ?>
					&nbsp;<input type="text" id="email" name="email" value="<?php echo $this->email ?>" data-parsley-type="email" data-parsley-errors-messages-disabled/>
					<button type="button" id="filterButton" class="button button-primary">
						<?php echo __('Filter results', 'calendarista') ?>
					</button>
					&nbsp;
					<button type="button" id="filterResetButton" class="button button-primary">
						<?php echo __('Reset', 'calendarista') ?>
					</button>
				</form>
				<div id="spinner_staff_filter" class="calendarista-spinner calendarista-invisible">
					<br>
					<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">
				<div class="add-staff-modal calendarista" 
						title="<?php echo __('Staff', 'calendarista') ?>">
						<div class="add_staff_placeholder"></div>
				</div>
				<form action="<?php echo $_SERVER['REQUEST_URI'] ?>" method="post">
					<input type="hidden" name="controller" value="calendarista_staff">
					<p>
						<button type="submit" name="calendarista_delete" class="button button-primary" disabled>
							<?php echo __('Delete', 'calendarista') ?>
						</button>&nbsp;&nbsp;
						<button type="button" name="addStaff" class="button button-primary">
							<?php echo __('Add New Staff', 'calendarista') ?>
						</button>
					</p>
					<div>
						<span id="spinner_update_staff_list" class="calendarista-spinner calendarista-invisible">
							<img src="<?php echo CALENDARISTA_PLUGINDIR ?>assets/img/transparent.gif">
						</span>
					</div>
					<div id="calendarista_staff_list" class="table-responsive">
					<?php $this->staffList->printVariables() ?>
					<?php $this->staffList->display(); ?>
					</div>
					<p>
						<button type="submit" name="calendarista_delete" class="button button-primary" disabled>
							<?php echo __('Delete', 'calendarista') ?>
						</button>
					</p>
				</form>
				
			</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.staff = function(options){
					var context = this;
					$(window).ready(function(){
						context.init(options);
						window.Parsley.addValidator('exclusive', {
						  validateString: function (value, requirement) {
							if($.trim($(requirement).val()).length !== 0 && $.trim(value).length !== 0){
								return false;
							}
							return true;
						  },
						  priority: 32
						});
					});
				};
				calendarista.staff.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.actionAddStaff = 'calendarista_create_staff';
					this.actionGetStaffList = 'calendarista_get_staff_list';
					this.$filter= $('#manage_staff_filter');
					this.$filterButton = this.$filter.find('#filterButton');
					this.$filterResetButton = this.$filter.find('#filterResetButton');
					this.$searchFilterProjectList = this.$filter.find('select[name="projectId"]');
					this.$availabilityList = this.$filter.find('select[name="availabilityId"]');
					this.$addStaffPlaceHolder = $('.add_staff_placeholder');
					this.$staffListCheckboxes = $('.calendarista-staff-list input[name="members[]"]');
					this.$deleteButton = $('button[name="calendarista_delete"]');
					this.$staffMembers = $('input[name="staffMembers"]');
					this.$staffAllCheck = $('input[name="selectall"]');
					this.ajax1 = new Calendarista.ajax({'ajaxUrl': this.ajaxUrl, 'id': 'staff_filter'});
					this.ajax2 = new Calendarista.ajax({'ajaxUrl': this.ajaxUrl, 'id': 'staff'});
					this.ajax3 = new Calendarista.ajax({'ajaxUrl': this.ajaxUrl, 'id': 'update_staff_list'});
					this.$addStaffButton = $('button[name="addStaff"]');
					this.$editStaff = $('button[name="editStaff"]');
					this.$staffList = $('#calendarista_staff_list');
					this.$filterButton.on('click', function(e){
						context.staffListRequest(true);
					});
					this.$filterResetButton.on('click', function(e){
						context.$searchFilterProjectList[0].selectedIndex = 0;
						context.$availabilityList.find('option').remove().end().append('<option value=""><?php echo $this->decodeString(__("Select an availability", "calendarista")) ?></option>');
						context.$availabilityList[0].selectedIndex = 0;
						$('input[name="name"]').val('');
					    $('input[name="email"]').val('');
						context.staffListRequest(true);
					});
					this.staffCheckAllDelegate = calendarista.createDelegate(this, this.staffCheckall);
					this.$staffAllCheck.on('change', this.staffCheckAllDelegate);
					this.checkedAllDelegate = calendarista.createDelegate(this, this.checkedAll);
					this.$staffListCheckboxes.on('change', this.checkedAllDelegate);
					this.$addStaffButton.on('click', function(e){
						var model = [{ 'name': 'action', 'value': context.actionAddStaff }
									, { 'name': 'calendarista_nonce', 'value': context.nonce }];
						context.$addStaffModalDialog.dialog('open');
						context.createEditStaffButtonText(0);
						$('#spinner_staff').removeClass('calendarista-invisible');
						context.ajax2.request(context, context.staffResponse, $.param(model));
					});
					this.editStaffDelegate = calendarista.createDelegate(this, this.editStaff);
					this.$editStaff.on('click', this.editStaffDelegate);
					this.$addStaffModalDialog = $('.add-staff-modal').dialog({
						autoOpen: false
						, height: '480'
						, width: '640'
						, modal: true
						, resizable: false
						, dialogClass: 'calendarista-dialog'
						, closeOnEscape: false
						, open: function(event, ui) {
							$('.ui-dialog-titlebar-close', ui.dialog | ui).hide();
						}
						, create: function() {
							var spinner = '<div id="spinner_staff" class="calendarista-spinner ui-widget ui-button calendarista-invisible">';
								spinner += '<img src="<?php echo CALENDARISTA_PLUGINDIR ?>assets/img/transparent.gif">&nbsp;';
								spinner += '</div>';
							$(this).dialog('widget').find('.ui-dialog-buttonset').prepend(spinner);
						}
						, buttons: [
							{
								'text': 'Create'
								, 'name': 'create'
								, 'click':  function(e){
									var $target = $(e.currentTarget)
										, $form = context.$addStaffModalDialog.dialog('widget').find('#form1')
										, editMode = parseInt($target.val(), 10) === 1
										, model = $form.serializeArray();
									e.preventDefault();
									if(!Calendarista.wizard.isValid($form)){
										return false;
									}
									model.push({ 'name': 'controller', 'value': 'calendarista_staff'});
									model.push({ 'name': editMode ? 'calendarista_update' : 'calendarista_create', 'value': 'true'});
									model.push({ 'name': 'action', 'value': context.actionAddStaff });
									model.push({ 'name': 'calendarista_nonce', 'value': context.nonce });
									context.ajax2.request(context, context.staffResponse, $.param(model));
								}
							}
							, {
								'text': 'Delete'
								, 'name': 'delete'
								, 'click':  function(){
									var $id = context.$addStaffModalDialog.dialog('widget').find('input[name="id"]')
										, model = [
											{ 'name': 'id', 'value': parseInt($id.val(), 10)}
											, { 'name': 'controller', 'value': 'calendarista_staff'}
											, { 'name': 'calendarista_delete', 'value': 'true'}
											, { 'name': 'action', 'value': context.actionAddStaff }
											, { 'name': 'calendarista_nonce', 'value': context.nonce }
										];
									context.createEditStaffButtonText(2);
									context.ajax2.request(context, context.staffResponse, $.param(model));
								}
							}
							, {
								'text': 'Close'
								, 'click':  function(){
									$('#spinner_staff').removeClass('calendarista-invisible');
									context.$addStaffModalDialog.dialog('close');
									context.staffListRequest();
								}
							}
						]
					});
					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.pagerButtonDelegates();
				};
				calendarista.staff.prototype.editStaff = function(e){
					var id = parseInt($(e.currentTarget).val(), 10)
						, model = [
							{ 'name': 'id', 'value':  id }
							, { 'name': 'action', 'value': this.actionAddStaff }
							, { 'name': 'calendarista_nonce', 'value': this.nonce }
						];
					this.$addStaffModalDialog.dialog('open');
					this.createEditStaffButtonText(1);
					this.ajax2.request(this, this.staffResponse, $.param(model));
				};
				calendarista.staff.prototype.checkedAll = function(){
					var hasChecked = this.$staffListCheckboxes.is(':checked');
					if(hasChecked){
						this.$deleteButton.prop('disabled', false);
					}else{
						this.$deleteButton.prop('disabled', true);
					}
				};
				calendarista.staff.prototype.availabilitiesResponse = function(result){
					this.$availabilityList[0].length = 0;
					this.$availabilityList.append(result);
				};
				calendarista.staff.prototype.staffResponse = function(result){
					var $createButton = this.$addStaffModalDialog.dialog('widget').find('.ui-dialog-buttonset').find('button[name="create"]')
						, mode = parseInt($createButton.val(), 10)
						, deactivateCreate = false;
					this.$addStaffPlaceHolder.replaceWith('<div class="add_staff_placeholder">' + result + '</div>');
					this.$addStaffPlaceHolder = $('.add_staff_placeholder');
					if(mode === 0/*create*/ && this.$addStaffPlaceHolder.find('input[name="email"]').length === 0){
						deactivateCreate = true;
					}
					this.createEditStaffButtonText(mode, deactivateCreate);
				};
				calendarista.staff.prototype.createEditStaffButtonText = function(status, deactivateCreate){
					var $createButton = this.$addStaffModalDialog.dialog('widget').find('.ui-dialog-buttonset').find('button[name="create"]')
						, $deleteButton = this.$addStaffModalDialog.dialog('widget').find('.ui-dialog-buttonset').find('button[name="delete"]');
					$createButton.button('option', 'label', '<?php echo $this->decodeString(__("Create", "calendarista")) ?>');
					$createButton.prop('disabled', false).removeClass('ui-state-disabled');
					$deleteButton.prop('disabled', true).addClass('ui-state-disabled');
					$createButton.val(status);
					if(status === 1){
						$createButton.button('option', 'label', '<?php echo $this->decodeString(__("Update", "calendarista")) ?>');
						$deleteButton.prop('disabled', false).removeClass('ui-state-disabled');
					}
					if(status === 2 || deactivateCreate){
						$createButton.prop('disabled', true).addClass('ui-state-disabled');
					}
				};
				calendarista.staff.prototype.staffListRequest = function(cleanUrl, values){
				var paged = $('input[name="paged"]').val()
					, orderby = $('input[name="orderby"]').val()
					, order = $('input[name="order"]').val()
					, projectId = this.$searchFilterProjectList.val()
					, availabilityId = this.$availabilityList.val()
					, name = $('input[name="name"]').val()
					, email = $('input[name="email"]').val()
					, url = window.location.pathname + window.location.search
					, model = [
						{ 'name': 'projectId', 'value': projectId }
						, { 'name': 'availabilityId', 'value': availabilityId }
						, { 'name': 'current_url', 'value': url }
						, { 'name': 'name', 'value': name }
						, { 'name': 'email', 'value': email }
						, { 'name': 'action', 'value': this.actionGetStaffList }
						, { 'name': 'calendarista_nonce', 'value': this.nonce }
					];
				if(!cleanUrl){
					model.push({ 'name': 'orderby', 'value': orderby } , { 'name': 'order', 'value': order });
					if(!values){
						model.push({ 'name': 'paged', 'value': paged });
					}
				}
				if(values){
					model = model.concat(values);
				}
				window.history.replaceState({}, document.title, window.location.href);
				this.ajax3.request(this, this.staffListResponse, $.param(model));
			};
			calendarista.staff.prototype.staffCheckall = function(e){
				var target = e.currentTarget;
				if(target.checked){
					this.$staffListCheckboxes.prop('checked', true);
				}else{
					this.$staffListCheckboxes.prop('checked', false);
				}
				this.checkedAll();
			};
			calendarista.staff.prototype.staffListResponse = function(result){
				var context = this;
				this.$editStaff.off();
				this.$staffAllCheck.off();
				this.$staffList.replaceWith('<div id="calendarista_staff_list">' + result + '</div>');
				this.$staffList = $('#calendarista_staff_list');
				this.$editStaff = $('button[name="editStaff"]');
				this.$editStaff.on('click', this.editStaffDelegate);
				this.$staffAllCheck = $('input[name="selectall"]');
				this.$staffAllCheck.on('change', this.staffCheckAllDelegate);
				this.$staffListCheckboxes = $('.calendarista-staff-list input[name="members[]"]');
				this.pagerButtonDelegates();
			};
			calendarista.staff.prototype.pagerButtonDelegates = function(){
				var context = this;
				this.$nextPage = $('a[class="next-page"]');
				this.$lastPage = $('a[class="last-page"]');
				this.$prevPage = $('a[class="prev-page"]');
				this.$firstPage = $('a[class="first-page"]');
				this.$nextPage.on('click', function(e){
					context.gotoPage(e);
				});
				this.$lastPage.on('click', function(e){
					context.gotoPage(e);
				});
				this.$prevPage.on('click', function(e){
					context.gotoPage(e);
				});
				this.$firstPage.on('click', function(e){
					context.gotoPage(e);
				});
			};
			calendarista.staff.prototype.gotoPage = function(e){
				var pagedValue = this.getUrlParameter('paged', $(e.currentTarget).prop('href'))
					, model = pagedValue ? [{ 'name': 'paged', 'value': pagedValue }] : [];
				this.$nextPage.off();
				this.$lastPage.off();
				this.$prevPage.off();
				this.$firstPage.off();
				this.staffListRequest(false, model);
				e.preventDefault();
				return false;
			};
			calendarista.staff.prototype.removeURLParameter = function(parameter) {
				 var url = window.location.href;
				//prefer to use l.search if you have a location/link object
				var urlparts= url.split('?');   
				if (urlparts.length>=2) {

					var prefix= encodeURIComponent(parameter)+'=';
					var pars= urlparts[1].split(/[&;]/g);

					//reverse iteration as may be destructive
					for (var i= pars.length; i-- > 0;) {    
						//idiom for string.startsWith
						if (pars[i].lastIndexOf(prefix, 0) !== -1) {  
							pars.splice(i, 1);
						}
					}

					url= urlparts[0]+'?'+pars.join('&');
				}
				window.history.replaceState({}, document.title, url);
			};
			calendarista.staff.prototype.getUrlParameter = function(param, url) {
				var regex, results;
				param = param.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
				regex = new RegExp('[\\?&]' + param + '=([^&#]*)');
				results = regex.exec(url);
				return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
			};
			window['calendarista'] = calendarista;
		})(window['jQuery'], window['calendarista_wp_ajax']);
		new calendarista.staff({
			'requestUrl': '<?php echo $_SERVER['REQUEST_URI'] ?>'
		});
		</script>
	<?php
	}
}