<?php
class Calendarista_ConnectTemplate extends Calendarista_ViewBase{
	public $setting;
	public $googleCalendarList;
	public $currentUrl;
	public $authorizationUrl;
	public $allowAuthorization;
	public $id;
	public $profile;
	public $redirectURI;
	public $googleCronJobUrl;
	public $wooCronJobUrl;
	public $javascriptOrigins;
	public $tabs;
	public $selectedTab;
	function __construct( ){
		parent::__construct(false, true, 'calendarista-settings');
		$this->selectedProjectId = -1;
		new Calendarista_GcalProfileController(
			array($this, 'createdProfile')
			, array($this, 'updatedProfile')
			, array($this, 'deletedProfile')
		);
		new Calendarista_GcalController(
			array($this, 'created')
			, array($this, 'deleted')
			, array($this, 'deletedMany')
			, array($this, 'deletedWithImportedData')
			, array($this, 'synced')
		);
		$generalSettingsRepository = new Calendarista_GeneralSettingsRepository();
		$this->setting = $generalSettingsRepository->read();
		$this->tabs = $this->getTabs();
		if(array_key_exists('calendarista_update_google_cronjob', $_POST)){
			$this->googleCronJob();
		}
		$this->wooController();
		$this->zapController();
		$this->twilioController();
		$this->googleCalendarList = new Calendarista_GoogleCalendarList();
		$this->googleCalendarList->bind();
		$userId = Calendarista_PermissionHelper::getUserId();
		$gcalRepoRepo = new Calendarista_GcalProfileRepository();
		$this->profile = $gcalRepoRepo->readByUserId($userId);
		if(!$this->profile){
			$this->profile = array('id'=>null, 'userId'=>null, 'clientId'=>null, 'clientSecret'=>null, 'accessToken'=>null);
		}
		$this->currentUrl = esc_url(add_query_arg(array(
			'page'=>'calendarista-settings',
			'calendarista-tab'=>9,
		), 'admin.php'));
		$this->redirectURI = get_site_url();
		$this->googleCronJobUrl = $this->redirectURI . '?calendarista_handler=gcal_cron';
		$this->wooCronJobUrl = $this->redirectURI . '?calendarista_handler=woo_cron';
		if($this->selectedTab === 0){
			$urlParts = parse_url($this->redirectURI);
			$port = isset($urlParts['port']) ? ':' . $urlParts['port'] : '';
			$this->javascriptOrigins = $urlParts['scheme'] . '://' . $urlParts['host'] . $port;
			$service = new Calendarista_GoogleCalendarHelper($this->profile['userId']);
			$this->authorizationUrl = null;
			if(!$this->profile['accessToken']){
				$this->authorizationUrl = $service->getAuthorizationUrl();
			}
			$this->calendarList = $service->getCalendarList();
			$this->allowAuthorization = $this->profile['id'] || $this->profile['accessToken'];
		}
		$this->render();
	}
	public function getTabs(){
		$url = admin_url() . 'admin.php?page=calendarista-settings';
		$this->selectedTab = isset($_GET['calendarista-sub-tab']) ? (int)$_GET['calendarista-sub-tab'] : 0;
		$result = array();
		$result[0] = array('url'=>$url . '&calendarista-tab=9', 'label'=>__('Google Calendar', 'calendarista'), 'active'=>false);
		$result[1] = array('url'=>$url . '&calendarista-tab=9&calendarista-sub-tab=1', 'label'=>__('Woo commerce', 'calendarista'), 'active'=>false);
		$result[2] = array('url'=>$url . '&calendarista-tab=9&calendarista-sub-tab=2', 'label'=>__('Zapier', 'calendarista'), 'active'=>false);
		$result[3] = array('url'=>$url . '&calendarista-tab=9&calendarista-sub-tab=3', 'label'=>__('Twilio', 'calendarista'), 'active'=>false);
		if($this->selectedTab !== null){
			$result[$this->selectedTab]['active'] = true;
			$this->requestUrl .= '&calendarista-sub-tab=' . $this->selectedTab;
		}else{
			$result[0]['active'] = true;
		}
		return $result;
	}
	public function wooController(){
		if (!(array_key_exists('controller', $_POST) 
			&& $_POST['controller'] == 'calendarista_woo')){
			return;
		}
		if(!Calendarista_NonceHelper::valid()){
			return;
		}
		$generalSettingsRepository = new Calendarista_GeneralSettingsRepository();
		$this->setting->autoCompleteWooCommerceOrder = $this->getPostValue('autoCompleteWooCommerceOrder');
		$this->setting->addBookingFormWooProduct = $this->getPostValue('addBookingFormWooProduct');
		$this->setting->cancelWooCommerceOrder = $this->getPostValue('cancelWooCommerceOrder');
		$this->setting->includeCustomFieldsWooCommerce = $this->getPostValue('includeCustomFieldsWooCommerce');
		$this->setting->includeGuestsWooCommerce = $this->getPostValue('includeGuestsWooCommerce');
		$this->setting->wooCommerceAltCronJob = $this->getPostValue('wooCommerceAltCronJob');
		$this->setting->wooCommerceCheckoutMode = (int)$this->getPostValue('wooCommerceCheckoutMode');
		$this->setting->wooCommerceProcessingStatusOnly = $this->getPostValue('wooCommerceProcessingStatusOnly');
		if($this->setting->id === -1){
			$result = $generalSettingsRepository->insert($this->setting);
		}else{
			$result = $generalSettingsRepository->update($this->setting);
		}
	}
	public function zapController(){
		if (!(array_key_exists('controller', $_POST) 
			&& $_POST['controller'] == 'calendarista_zap')){
			return;
		}
		if(!Calendarista_NonceHelper::valid()){
			return;
		}
		$generalSettingsRepository = new Calendarista_GeneralSettingsRepository();
		$this->setting->newAppointmentZap = $this->getPostValue('newAppointmentZap');
		$this->setting->updatedAppointmentZap = $this->getPostValue('updatedAppointmentZap');
		$this->setting->newCustomerZap = $this->getPostValue('newCustomerZap');
		if(array_key_exists('calendarista_zap_reset', $_POST)){
			$this->setting->newAppointmentZap = null;
			$this->setting->updatedAppointmentZap = null;
			$this->setting->newCustomerZap = null;
		}
		if($this->setting->id === -1){
			$result = $generalSettingsRepository->insert($this->setting);
		}else{
			$result = $generalSettingsRepository->update($this->setting);
		}
		?>
		<div class="wrap">
			<div class="calendarista-notice updated notice is-dismissible">
				<p><?php echo __('The Zapier setting has been updated successfully.', 'calendarista'); ?></p>
			</div>
			<hr>
		</div>
		<?php
	}
	public function twilioController(){
		if (!(array_key_exists('controller', $_POST) 
			&& $_POST['controller'] == 'calendarista_twilio')){
			return;
		}
		if(!Calendarista_NonceHelper::valid()){
			return;
		}
		$generalSettingsRepository = new Calendarista_GeneralSettingsRepository();
		$this->setting->twilioAccountSID = trim($this->getPostValue('twilioAccountSID'));
		$this->setting->twilioAuthToken = trim($this->getPostValue('twilioAuthToken'));
		$this->setting->twilioFromNumber = trim($this->getPostValue('twilioFromNumber'));
		$this->setting->twilioCountryCode = trim($this->getPostValue('twilioCountryCode'));
		$this->setting->smsContentTemplate = trim($this->getPostValue('smsContentTemplate'));
		if(array_key_exists('calendarista_twilio_reset', $_POST)){
			$this->setting->twilioAccountSID = null;
			$this->setting->twilioAuthToken = null;
			$this->setting->twilioFromNumber = null;
			$this->setting->twilioCountryCode = null;
			$this->setting->smsContentTemplate = null;
		}else{
			if($this->setting->smsContentTemplate){
				if(!class_exists('Mustache_Engine')){
					require_once CALENDARISTA_MUSTACHE . 'Autoloader.php';
					Mustache_Autoloader::register();
				}
				$mustacheEngine = new Mustache_Engine();
				try{
					$mustacheEngine->render($this->setting->smsContentTemplate);
				} catch (Exception $e) {
					$errorMessage = $e->getMessage();
					?>
						<div class="wrap">
							<div class="calendarista-notice updated notice is-dismissible">
								<p><?php echo sprintf(__('Update failed. There is an error within the sms content template, please check braces and syntax. Error message: %s', 'calendarista'), $errorMessage); ?></p>
							</div>
							<hr>
						</div>
					<?php
					return;
				}
			}
		}
		if($this->setting->id === -1){
			$result = $generalSettingsRepository->insert($this->setting);
		}else{
			$result = $generalSettingsRepository->update($this->setting);
		}
		?>
		<div class="wrap">
			<div class="calendarista-notice updated notice is-dismissible">
				<p><?php echo __('The Twilio account setting has been updated successfully.', 'calendarista'); ?></p>
			</div>
			<hr>
		</div>
		<?php
	}
	public function googleCronJob(){
		if (!(array_key_exists('controller', $_POST) 
			&& $_POST['controller'] == 'calendarista_cronjob')){
			return;
		}
		if(!Calendarista_NonceHelper::valid()){
			return;
		}
		$generalSettingsRepository = new Calendarista_GeneralSettingsRepository();
		$this->setting->googleCalendarAltCronJob = $this->getPostValue('googleCalendarAltCronJob') ? true : false;
		if($this->setting->id === -1){
			$result = $generalSettingsRepository->insert($this->setting);
		}else{
			$result = $generalSettingsRepository->update($this->setting);
		}
		?>
		<div class="wrap">
			<div class="calendarista-notice updated notice is-dismissible">
				<p><?php echo __('The CRON Job setting has been updated successfully.', 'calendarista'); ?></p>
			</div>
			<hr>
		</div>
		<?php
	}
	public function createdProfile($result) {
		if($result):
		$this->id = $result;
		?>
		<div class="wrap">
			<div class="calendarista-notice updated notice is-dismissible">
				<p><?php echo __('The google profile has been created.', 'calendarista') ?></p>
			</div>
			<hr>
		</div>
		<?php
		else:
		?>
		<div class="wrap">
			<div class="calendarista-notice error notice is-dismissible">
				<p><?php echo __('Failed. The google profile may already exists.', 'calendarista') ?></p>
			</div>
			<hr>
		</div>
		<?php 
		endif;
	}
	public function created($result) {
		if($result):
		$this->id = $result;
		?>
		<div class="wrap">
			<div class="calendarista-notice updated notice is-dismissible">
				<p><?php echo __('The service availability has been linked to the selected Google calendar.', 'calendarista') ?></p>
			</div>
			<hr>
		</div>
		<?php
		else:
		?>
		<div class="wrap">
			<div class="calendarista-notice error notice is-dismissible">
				<p><?php echo __('Failed. The service availability is already linked to the selected Google calendar.', 'calendarista') ?></p>
			</div>
			<hr>
		</div>
		<?php 
		endif;
	}
	public function updatedProfile($result, $id) {
		$this->id = $id;
		?>
		<div class="wrap">
			<div class="calendarista-notice updated notice is-dismissible">
				<p><?php echo  __('The google profile has been updated.', 'calendarista') ?></p>
			</div>
			<hr>
		</div>
		<?php
	}
	public function deletedProfile($result) {
		$this->id = null;
		?>
		<div class="wrap">
			<div class="calendarista-notice updated notice is-dismissible">
				<p><?php echo __('The google profile has been deleted.', 'calendarista') ?></p>
			</div>
			<hr>
		</div>
		<?php
	}
	public function deleted($result) {
		$this->id = null;
		?>
		<div class="wrap">
			<div class="calendarista-notice updated notice is-dismissible">
				<p><?php echo __('The selected service availability linked with google calendar has been deleted.', 'calendarista') ?></p>
			</div>
			<hr>
		</div>
		<?php
	}
	public function deletedMany($result) {
		?>
		<div class="wrap">
			<div class="calendarista-notice updated notice is-dismissible">
				<p><?php echo sprintf(__('%d selected service availabilities linked with google calendar have been deleted.', 'calendarista'), $result) ?></p>
			</div>
			<hr>
		</div>
		<?php
	}
	public function deletedWithImportedData($result) {
		?>
		<div class="wrap">
			<div class="calendarista-notice updated notice is-dismissible">
				<p><?php echo sprintf(__('The selected service availabilities linked with google calendar have been deleted along with %d imported and %d exported records.', 'calendarista'), $result['imported'], $result['exported']) ?></p>
			</div>
			<hr>
		</div>
		<?php
	}
	public function synced($result) {
		//$result['updated'] is excluded from the result below 
		//because we update on every run regardless there is a change hence not accurate.
		?>
		<div class="wrap">
			<div class="calendarista-notice updated notice is-dismissible">
				<p><?php echo sprintf(__('Appointments sync result: %d imported, %d deleted locally and %d exported.', 'calendarista'), $result['inserted'], $result['deleted'], $result['exported']) ?></p>
			</div>
			<hr>
		</div>
		<?php
	}
	public function render(){
	?>
		<p class="description">
			<?php echo __('Connect Calendarista with the following third party services.', 'calendarista') ?>
			<br>
			<br>
			<?php foreach($this->tabs as $tab):?>
				<?php if(!isset($tab)){continue;}?>
				<input type="radio" name="connectmode" value="<?php echo $tab['url']?>" <?php echo $tab['active'] ? 'checked': '' ?>>—<?php echo $tab['label']?>&nbsp;&nbsp;
			<?php endforeach;?>
		</p>
		<?php if($this->selectedTab === 0): ?>
		<h3 class="calendarista-connect-heading"><?php echo __('Connect to Google Calendar', 'calendarista') ?></h3>
		<div class="widget-liquid-left">
			<div id="widgets-left">
				<div class="wrap">
					<div class="column-pane">
						<form action="<?php echo $this->currentUrl ?>" method="post">
						<input type="hidden" name="controller" value="calendarista_gcal_profile">
						<input type="hidden" name="calendarista_nonce" value="<?php echo wp_create_nonce('calendarista-ajax-nonce') ?>"/>
						<table class="form-table">
							<tbody>
								<tr>
									<th scope="row">
										<label for="clientId"><?php echo __('Client Id', 'calendarista')?></label>
									</th>
									<td>
										<input type="text" 
											id="clientId"
											class="regular-text"
											name="clientId" 
											value="<?php echo $this->profile['clientId'] ?>"
											data-parsley-required="true" 
											data-parsley-trigger="change"/>
									</td>
								</tr>
								<tr>
									<th scope="row">
										<label for="clientSecret"><?php echo __('Client Secret', 'calendarista')?></label>
									</th>
									<td>
										<input type="text" 
											id="clientSecret"
											class="regular-text"
											name="clientSecret" 
											value="<?php echo $this->profile['clientSecret'] ?>"
											data-parsley-required="true" 
											data-parsley-trigger="change"/>
									</td>
								</tr>
							</table>
							<div>
								<button type="submit" name="calendarista_delete" value="<?php echo $this->profile['id'] ?>" class="button button-primary"  <?php echo !$this->profile['id'] ? 'disabled' : '' ?>>
									<?php echo __('Delete', 'calendarista') ?>
								</button>
								<button type="submit" name="calendarista_update" value="<?php echo $this->profile['id'] ?>" class="button button-primary"  <?php echo !$this->profile['id'] ? 'disabled' : '' ?>>
									<?php echo __('Update', 'calendarista') ?>
								</button>
								<button type="submit" name="calendarista_create" class="button button-primary" <?php echo $this->profile['id'] ? 'disabled' : '' ?>>
									<?php echo __('Create profile', 'calendarista') ?>
								</button>
								<?php if($this->allowAuthorization && $this->authorizationUrl): ?>
								<a href="<?php echo $this->authorizationUrl ?>" class="button button-primary" 
									title="<?php echo __('Grant permission so that Calendarista can access this calendar', 'calendarista') ?>" 
									target="_blank">
									<?php echo __('Authorize', 'calendarista') ?>
								</a>
								<?php endif; ?>
							</div>
						</form>
						<hr>
						<form action="<?php echo $this->currentUrl ?>" method="post">
						<input type="hidden" name="controller" value="calendarista_cronjob">
						<input type="hidden" name="calendarista_nonce" value="<?php echo wp_create_nonce('calendarista-ajax-nonce') ?>"/>
						<div>
							<?php echo __('For true CRON Job, add the following URL to your cron job scheduler tool, normally found in your hosting panel:', 'calendarista') ?> <strong><?php echo $this->googleCronJobUrl ?></strong>
						</div>
						<p>
							<input type="checkbox" name="googleCalendarAltCronJob" <?php echo $this->setting->googleCalendarAltCronJob ? 'checked' : '' ?> <?php echo !$this->profile['id'] ? 'disabled' : '' ?>>
							<?php echo __('Alternate CRON Job (If checked, do not use above URL)', 'calendarista')?>
							<br>
							<br>
							<button type="submit" name="calendarista_update_google_cronjob" class="button button-primary" <?php echo !$this->profile['id'] ? 'disabled' : '' ?>>
								<?php echo __('Update Cron setting', 'calendarista') ?>
							</button>
						</p>
						</form>
						<hr>
						<ul>
							<li><?php echo __('Add the following value for Javascript Origins, if required:', 'calendarista') ?> <strong><?php echo $this->javascriptOrigins ?></strong></li>
							<li><?php echo __('Add the following value for RedirectURI, if required:', 'calendarista') ?> <strong><?php echo $this->redirectURI?></strong></li>
							<li>
								<?php if(!$this->setting->brandName): ?>
								<p>
									<?php echo __('Need help? Checkout the Google Calendar section in the', 'calendarista') ?>&nbsp;<a href="<?php echo CALENDARISTA_ABSOLUTE_PATH_TO_DOCUMENTATION ?>" target="__blank">
										<?php echo __('documentation.', 'calendarista') ?>
									</a>
								</p>
								<?php endif; ?>
							</li>
						</ul>
					</div>
				</div>
			</div>
		</div>
		<div class="widget-liquid-right">
			<div id="widgets-right">
				<div class="wrap">
					<div class="column-pane">
						<form data-parsley-validate action="<?php echo $this->requestUrl ?>" method="post">
							<input type="hidden" name="controller" value="calendarista_gcal">
							<input type="hidden" name="gcalProfileId" value="<?php echo $this->profile['id'] ?>">
							<input type="hidden" name="calendarista_nonce" value="<?php echo wp_create_nonce('calendarista-ajax-nonce') ?>"/>
							<input type="hidden" name="calendarName">
							<input type="hidden" name="projectName">
							<input type="hidden" name="availabilityName">
							<table class="form-table">
							<tbody>
								<tr>
									<th scope="row">
										<label for="calendarId"><?php echo __('Google calendar', 'calendarista') ?></label> 
									</th>
									<td>
										<select id="calendarId" name="calendarId" data-parsley-required="true" data-parsley-errors-messages-disabled="true">
											<option value=""><?php echo __('Select a calendar', 'calendarista') ?></option>
											<?php foreach($this->calendarList as $calendar):?>
											<option value="<?php echo $calendar['id'] ?>"><?php echo $calendar['summary'] ?></option>
											<?php endforeach; ?>
										</select>
									</td>
								</tr>
								<tr>
									<th scope="row">
										<label for="projectId"><?php echo __('Service', 'calendarista') ?></label> 
									</th>
									<td>
										<?php $this->renderProjectSelectList(true, __('Select a service', 'calendarista'), true, false, array(7/*ROUND_TRIP*/)) ?>
									</td>
								</tr>
								<tr>
									<th scope="row">
										<label for="availabilityId"><?php echo __('Availability', 'calendarista') ?></label> 
									</th>
									<td>
										<select id="availabilityId" name="availabilityId" data-parsley-required="true" data-parsley-errors-messages-disabled="true">
											<option value=""><?php echo __('Select an availability', 'calendarista') ?></option>
										</select>
										<span id="spinner_feeds1" class="calendarista-spinner calendarista-invisible">
											<img src="<?php echo CALENDARISTA_PLUGINDIR ?>assets/img/transparent.gif">
										</span>
										<br class="clear">
									</td>
								</tr>
							</table>
							<p class="description"><?php echo __('New bookings made on the service availability will be synced to the selected Google calendar.', 'calendarista') ?></p>
							<p>
								<button type="submit" name="calendarista_create" class="button button-primary">
									<?php echo __('Add', 'calendarista') ?>
								</button>
							</p>
						</form>
					</div>
					<br class="clear">
					<form action="<?php echo $this->currentUrl ?>" method="post">
						<input type="hidden" name="controller" value="calendarista_gcal">
						<input type="hidden" name="availabilityId" value="<?php echo $this->googleCalendarList->availabilityId ?>">
						<input type="hidden" name="calendarista_nonce" value="<?php echo wp_create_nonce('calendarista-ajax-nonce') ?>"/>
						<?php $this->googleCalendarList->display(); ?>
						<?php if($this->googleCalendarList->count > 0):?>
						<p class="description"><?php echo __('** Deletes also imported data', 'calendarista') ?></p>
						<?php endif; ?>
						<div>
							<button type="submit" name="calendarista_delete_many" class="button button-primary" disabled>
								<?php echo __('Delete', 'calendarista') ?>
							</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		<?php elseif($this->selectedTab === 1): ?>
		<h3 class="calendarista-connect-heading"><?php echo __('WooCommerce Settings', 'calendarista') ?></h3>
		<p class="description"><?php echo __('Note that woocommerce needs to be the selected payment method. You will find this option in the Services page.', 'calendarista') ?></p>
		<div class="wrap">
			<div class="column-pane">
				<form action="<?php echo $this->currentUrl . '&calendarista-sub-tab=1' ?>" method="post">
					<input type="hidden" name="controller" value="calendarista_woo">
					<input type="hidden" name="calendarista_nonce" value="<?php echo wp_create_nonce('calendarista-ajax-nonce') ?>"/>
					<table class="form-table">
						<tbody>
							<tr>
								<th scope="row">
									<label for=""><?php echo __('Auto complete woocommerce order', 'calendarista')?></label>
								</th>
								<td>
								<input name="autoCompleteWooCommerceOrder" type="hidden" value="0">
								<input id="autoCompleteWooCommerceOrder" name="autoCompleteWooCommerceOrder" 
									type="checkbox" <?php echo $this->setting->autoCompleteWooCommerceOrder ? "checked" : ""?> /> 
										<?php echo __('When checked, a successful woocommerce order status will be automatically set to complete.', 'calendarista')?>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for=""><?php echo __('Add booking form to Woocommerce Product', 'calendarista')?></label>
								</th>
								<td>
								<input name="addBookingFormWooProduct" type="hidden" value="0">
								<input id="addBookingFormWooProduct" name="addBookingFormWooProduct" 
									type="checkbox" <?php echo $this->setting->addBookingFormWooProduct ? "checked" : ""?> /> 
										<?php echo __('When checked, the booking form is added automatically to the Woocommerce Product.', 'calendarista')?>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for=""><?php echo __('Create booking only if payment has been received', 'calendarista')?></label>
								</th>
								<td>
								<input name="wooCommerceProcessingStatusOnly" type="hidden" value="0">
								<input id="wooCommerceProcessingStatusOnly" name="wooCommerceProcessingStatusOnly" 
									type="checkbox" <?php echo $this->setting->wooCommerceProcessingStatusOnly ? "checked" : ""?> /> 
										<?php echo __('Create a booking only if the status is processing (payment received and stock has been reduced).', 'calendarista')?>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for=""><?php echo __('Cancel woocommerce order', 'calendarista')?></label>
								</th>
								<td>
								<input name="cancelWooCommerceOrder" type="hidden" value="0">
								<input id="cancelWooCommerceOrder" name="cancelWooCommerceOrder" 
									type="checkbox" <?php echo $this->setting->cancelWooCommerceOrder ? "checked" : ""?> /> 
										<?php echo __('When checked, a cancelled appointment will also cancel the associated woocommerce order.', 'calendarista')?>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for=""><?php echo __('Custom fields in woocommerce', 'calendarista')?></label>
								</th>
								<td>
								<input name="includeCustomFieldsWooCommerce" type="hidden" value="0">
								<input id="includeCustomFieldsWooCommerce" name="includeCustomFieldsWooCommerce" 
									type="checkbox" <?php echo $this->setting->includeCustomFieldsWooCommerce ? "checked" : ""?> /> 
										<?php echo __('When checked, custom form fields will be included in the woocommerce order summary.', 'calendarista')?>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for=""><?php echo __('Guests in woocommerce', 'calendarista')?></label>
								</th>
								<td>
								<input name="includeGuestsWooCommerce" type="hidden" value="0">
								<input id="includeGuestsWooCommerce" name="includeGuestsWooCommerce" 
									type="checkbox" <?php echo $this->setting->includeGuestsWooCommerce ? "checked" : ""?> /> 
										<?php echo __('When checked, guests will be included in the woocommerce order summary.', 'calendarista')?>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for=""><?php echo __('Use WordPress Cron job', 'calendarista')?></label>
								</th>
								<td>
								<input name="wooCommerceAltCronJob" type="hidden" value="0">
								<input id="wooCommerceAltCronJob" name="wooCommerceAltCronJob" 
									type="checkbox" <?php echo $this->setting->wooCommerceAltCronJob ? "checked" : ""?> /> 
										<?php echo __('When checked, a WordPress Cron job is used. Note, this is not a true CRON job.', 'calendarista')?>
										<br>
										<br>
										<?php echo __('For accurate results, uncheck the above option and instead use the following URL:', 'calendarista')?>
										<br>
										<strong><?php echo $this->wooCronJobUrl ?></strong>
								</td>
							</tr>
							<tr>
								<th></th>
								<td>
									<p>
									  <?php echo __('During checkout step, redirect to', 'calendarista') ?>
									  <input type="radio" name="wooCommerceCheckoutMode" value="0" <?php echo $this->setting->wooCommerceCheckoutMode === 0 ? 'checked' : '' ?>><?php echo __('Woocommerce checkout page', 'calendarista') ?>
									  <input type="radio" name="wooCommerceCheckoutMode" value="1" <?php echo $this->setting->wooCommerceCheckoutMode === 1 ? 'checked' : '' ?>><?php echo __('Woocommerce cart page', 'calendarista') ?>
									</p>
								</td>
							</tr>
							<tr>
								<th></th>
								<td>
									<button type="submit" name="calendarista_woo_update" class="button button-primary">
										<?php echo __('Update WooCommerce settings', 'calendarista') ?>
									</button>
								</td>
							</tr>
						</tbody>
					</table>
				</form>
			</div>
		</div>
		<?php elseif($this->selectedTab === 2): ?>
		<h3 class="calendarista-connect-heading"><?php echo __('Connect to Zapier', 'calendarista') ?></h3>
		<div class="wrap">
			<div class="column-pane">
				<form action="<?php echo $this->currentUrl . '&calendarista-sub-tab=2' ?>" method="post">
					<input type="hidden" name="controller" value="calendarista_zap">
					<input type="hidden" name="calendarista_nonce" value="<?php echo wp_create_nonce('calendarista-ajax-nonce') ?>"/>
					<table class="form-table">
						<tbody>
							<tr>
								<th scope="row">
									<label for="newAppointmentZap"><?php echo __('New Appointment', 'calendarista')?></label>
								</th>
								<td>
									<input type="text" 
										id="newAppointmentZap"
										class="regular-text"
										name="newAppointmentZap" 
										value="<?php echo $this->setting->newAppointmentZap ?>"/>
									<p class="description"><?php echo __('Webhook to send data when a new appointment is created', 'calendarista') ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="updatedAppointmentZap"><?php echo __('Updated Appointment', 'calendarista')?></label>
								</th>
								<td>
									<input type="text" 
										id="updatedAppointmentZap"
										class="regular-text"
										name="updatedAppointmentZap" 
										value="<?php echo $this->setting->updatedAppointmentZap ?>"/>
									<p class="description"><?php echo __('Webhook to send data when an appointment is modified', 'calendarista') ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="newCustomerZap"><?php echo __('New customer', 'calendarista')?></label>
								</th>
								<td>
									<input type="text" 
										id="newCustomerZap"
										class="regular-text"
										name="newCustomerZap" 
										value="<?php echo $this->setting->newCustomerZap ?>"/>
									<p class="description"><?php echo __('Webhook to send data when a new customer books an appointment', 'calendarista') ?></p>
								</td>
							</tr>
							<tr>
								<th></th>
								<td>
									<button type="submit" name="calendarista_zap_update" class="button button-primary">
										<?php echo __('Update Zapier settings', 'calendarista') ?>
									</button>
									<button type="submit" name="calendarista_zap_reset" class="button button-primary" <?php echo $this->setting->hasZap() ? '' : 'disabled' ?>>
										<?php echo __('Reset', 'calendarista') ?>
									</button>
								</td>
							</tr>
						</tbody>
					</table>
				</form>
			</div>
		</div>
		<?php elseif($this->selectedTab === 3): ?>
		<h3 class="calendarista-connect-heading"><?php echo __('Twilio (SMS)', 'calendarista') ?></h3>
		<div class="wrap">
			<div class="column-pane">
				<form action="<?php echo $this->currentUrl . '&calendarista-sub-tab=3' ?>" method="post" data-parsley-validate>
					<input type="hidden" name="controller" value="calendarista_twilio">
					<input type="hidden" name="calendarista_nonce" value="<?php echo wp_create_nonce('calendarista-ajax-nonce') ?>"/>
					<table class="form-table">
						<tbody>
							<tr>
								<th scope="row">
									<label for="twilioAccountSID"><?php echo __('Account SID', 'calendarista')?></label>
								</th>
								<td>
									<input type="text" 
										id="twilioAccountSID"
										class="regular-text"
										name="twilioAccountSID" 
										data-parsley-required="true"
										value="<?php echo $this->setting->twilioAccountSID ?>"/>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="twilioAuthToken"><?php echo __('Auth Token', 'calendarista')?></label>
								</th>
								<td>
									<input type="password" 
										id="twilioAuthToken"
										class="regular-text"
										name="twilioAuthToken" 
										data-parsley-required="true"
										value="<?php echo $this->setting->twilioAuthToken ?>"/>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="twilioFromNumber"><?php echo __('Twilio From Number', 'calendarista')?></label>
								</th>
								<td>
									<input type="text" 
										id="twilioFromNumber"
										class="regular-text"
										name="twilioFromNumber" 
										data-parsley-pattern="^\+[1-9]\d{1,14}$"
										data-parsley-required="true"
										value="<?php echo $this->setting->twilioFromNumber ?>"/>
									<p class="description"><?php echo __('This must be a Twilio phone number that you own, formatted with a + and country code, e.g. +16175551212', 'calendarista') ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="twilioCountryCode"><?php echo __('Country code', 'calendarista')?></label>
								</th>
								<td>
									<input type="text" 
										id="twilioCountryCode"
										class="small-text"
										name="twilioCountryCode" 
										data-parsley-pattern="/^(\+?\d{1,3}|\d{1,4})$/"
										data-parsley-required="true"
										value="<?php echo $this->setting->twilioCountryCode ?>"/>
									<p class="description"><?php echo __('Insert the country code here so that customers will only have to insert the local number. eg for the USA insert: 001 or +1', 'calendarista') ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="smsContentTemplate"><?php echo __('Message content', 'calendarista')?></label>
								</th>
								<td>
									<?php wp_editor($this->setting->smsContentTemplate, 'smsContentTemplate', $settings = array('media_buttons'=>false, 'tinymce'=>false)); ?> 
									<p class="description"><strong><?php echo __('Note!', 'calendarista') ?></strong>&nbsp;<?php echo __('When editing pay particular attention to how tokens are enclosed within 2 braces {{token}} or 3 braces {{{token}}}.', 'calendarista') ?></p>
									<div class="calendarista-borderless-accordion">
										<div id="sms_tokens">
											<h3><?php echo __('+ Tokens (Click to expand)', 'calendarista') ?></h3>
											<div>
												<p class="description">
													<?php echo __('Use any of the tokens below to include in your emails. Note that some tokens contains 3 curly braces instead of the usual 2', 'calendarista')?>
												</p>
												<ul>
													<li>{{customer_name}}</li>
													<li>{{service_name}}</li>
													<li>{{availability_name}}</li>
													<li>{{start_datetime}}</li>
													<li>{{start_date}}</li>
													<li>{{start_time}}</li>
													<li>{{end_datetime}}</li>
													<li>{{end_date}}</li>
													<li>{{end_time}}</li>
													<li>{{booked_seats_count}}</li>
													<li><strong>{{{</strong>dynamic_fields<strong>}}}</strong></li>
												</ul>
												<p class="description">
													<?php echo __('Along with tokens, you can use the following control statements', 'calendarista')?>
												</p>
												<ul>
													<li>
													{{#if_has_end_date}}
													<br>
													{{/if_has_end_date}}
													</li>
													<li>
													{{#if_has_return_trip}}
													<br>
													{{/if_has_return_trip}}
													</li>
													<li>
													{{#if_service_id_123}}
													<br><?php echo ('Note: replace 123 with the service id') ?><br>
													{{/if_service_id_123}}
													</li>
													<li>
													{{#if_availability_id_123}}
													<br><?php echo ('Note: replace 123 with the availability id') ?><br>
													{{/if_availability_id_123}}
													</li>
												</ul>
											</div>
										</div>
									</div>
								</td>
							</tr>
							<tr>
								<th></th>
								<td>
									<button type="submit" name="calendarista_twilio_update" class="button button-primary">
										<?php echo __('Update Twilio settings', 'calendarista') ?>
									</button>
									<button type="submit" name="calendarista_twilio_reset" class="button button-primary" <?php echo $this->setting->hasTwilio() ? '' : 'disabled' ?>>
										<?php echo __('Reset', 'calendarista') ?>
									</button>
								</td>
							</tr>
						</tbody>
					</table>
				</form>
			</div>
		</div>
		<?php endif; ?>
		<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(){
						var selectedTab = options['selectedTab']
						,  $connectMode = $('input[name="connectmode"]');
						$connectMode.on('click', function(){
							window.location = $(this).val();
						});
						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.actionGetAvailabilities = 'calendarista_get_availabilities';
					this.$projectList = $('select[name="projectId"]');
					this.$projectName = $('input[name="projectName"]');
					this.$availabilityList = $('select[name="availabilityId"]');
					this.$availabilityName = $('input[name="availabilityName"]');
					this.$selectAllCheckboxes = $('input[name="selectall"]');
					this.$googleCalendarListCheckboxes = $('.calendarista-google-calendar-list input[name="id[]"]');
					this.$deleteManyButton = $('button[name="calendarista_delete_many"]');
					this.$deleteDeleteSyncDataButton = $('button[name="calendarista_delete_many_sync_data"]');
					this.ajax1 = new Calendarista.ajax({'ajaxUrl': this.ajaxUrl, 'id': 'feeds1'});
					this.$calendarId = $('select[name="calendarId"]');
					this.$calendarName = $('input[name="calendarName"]');
					this.$calendarId.on('change', function(e){
						context.$calendarName.val($.trim($('option:selected', $(this)).text()));
					});
					this.$projectList.on('change', function(e){
						var $me = $(this)
							, val = parseInt($me.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));
						context.$projectName.val($.trim($('option:selected', $me).text()));
					});
					this.$availabilityList.on('change', function(e){
						context.$availabilityName.val($.trim($('option:selected', $(this)).text()));
					});
					this.$selectAllCheckboxes.on('change', function(){
						if(this.checked){
							context.$googleCalendarListCheckboxes.prop('checked', true);
						}else{
							context.$googleCalendarListCheckboxes.prop('checked', false);
							context.$selectAllCheckboxes.prop('checked', false);
						}
						context.checkedAll();
					});
					this.checkedAllDelegate = calendarista.createDelegate(this, this.checkedAll);
					this.$googleCalendarListCheckboxes.on('change', this.checkedAllDelegate);
					$('#sms_tokens').accordion({
						collapsible: true
						, active: false
						, heightStyle: 'content'
						, autoHeight: false
						, clearStyle: true
					});
				};
				calendarista.feeds.prototype.availabilitiesResponse = function(result){
					this.$availabilityList[0].length = 0;
					this.$availabilityList.append(result);
				};
				calendarista.feeds.prototype.checkedAll = function(){
					var hasChecked = this.$googleCalendarListCheckboxes.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 ?>'
			, 'selectedTab': <?php echo $this->selectedTab ?>
		});
		</script>
		<?php
	}
}