	<link rel="stylesheet" type="text/css" href="<?= asset_url('assets/css/manage_app.css') ?>">
             <?php if (isset($exceptions)): ?>
                <div style="margin: 10px">
                    <h4><?= lang('unexpected_issues') ?></h4>
                    <?php foreach ($exceptions as $exception): ?>
                        <?= exceptionToHtml($exception) ?>
                    <?php endforeach ?>
                </div>
            <?php endif ?>


            <!-- SELECT SERVICE AND PROVIDER -->
<div class="container-fluid backend-page reports" id="users-page">
<div class="container" style="text-align:center;">&nbsp;
<h3>Manage Appointments</h3>
	<div><b>Filter By</b></div>
	
	<div class="clo-5">
	<div class="reports_filter" style="text-align:center;">
		<div class="coldetail">
			<? if($dependantsCnt > 0) { ?>
			<label class="collab">Dependant :</label>
			<select id="did" name="did" class="colinp">
					<option value="">-Select Dependant-</option>
					<option value="<?php echo $this->session->userdata('user_id'); ?>" <?php if($this->input->get('did') == $this->session->userdata('user_id')) { echo "selected"; }?>>Self</option>
				<?php foreach($dependants as $dependant) { ?>
					<option value="<?php echo $dependant['id']; ?>" <?php if($this->input->get('did') == $dependant['id']) { echo "selected"; }?>><?php echo ucfirst($dependant['first_name'])." ".ucfirst($dependant['last_name'])." - ".$dependant['relationship']; ?></option>
				<?php } ?>
			</select>
			<? } ?>
		</div>
		
		<div class="coldetail">
			<label class="collab">Location :</label>
			<select id="lid" name="lid" class="colinp">
					<option value="">-Select Location-</option>
				<?php foreach($locations as $location) { ?>
					<option value="<?php echo $location['location_id']; ?>" <?php if($this->input->get('lid') == $location['location_id']) { echo "selected"; }?>><?php echo $location['location_name']; ?></option>
				<?php } ?>
			</select>
		</div>		
		
		<div class="coldetail">
			<label class="collab">Service :</label>
			<select id="sid" name="sid" class="colinp">
					<option value="">-Select Service-</option>
				<?php foreach($services as $service) { ?>
					<option value="<?php echo $service['id']; ?>" <?php if($this->input->get('sid') == $service['id']) { echo "selected"; }?>><?php echo $service['name']; ?></option>
				<?php } ?>
			</select>
		</div>
		
		<div class="coldetail">
			<label class="collab">Doctor :</label>
			<select id="pid" name="pid" class="colinp">
					<option value="">-Select Doctor-</option>
				<?php foreach($providers as $provider) { ?>
					<option value="<?php echo $provider['id']; ?>" <?php if($this->input->get('pid') == $provider['id']) { echo "selected"; }?>><?php echo ucfirst($provider['first_name'])." ".ucfirst($provider['last_name']); ?></option>
				<?php } ?>
			</select>
		</div>
		
	</div>
	</div>
	<div class="clo-5">
	<div  class="coldetail marright"><label class="collab1">Start Date:</label> <input type="text" id="start_date" style="float:left; width:230px; height:25px;" value="<?php echo $this->input->get('start_date'); ?>" readonly></div> 
	<div class="coldetail"><label class="collab1">End Date:</label> <input type="text" id="end_date" style="float:left; width:230px; height:25px;" value="<?php echo $this->input->get('end_date'); ?>" readonly></div>
		
	</div>
	<div class="coldetail" style="width:100%; margin-top:5px;"><input type="button" value="Search" id="search">
		<input type="button" value="Clear All" id="reset"></div>
	</div>
	
	<div class="limiter appreports">
		<div class="container-table100">
			<div class="wrap-table100" style="width:100%;">
				<div class="table100">
					<table>
						<thead>
							<tr class="table100-head">
								<th class="column2"><div style="cursor:pointer;" onclick="javascipt:setsorting('start_datetime','<?php echo $rev_sort_order; ?>');">Start Date<?php echo $sortImg['sortimg_start_datetime']; ?></div></th>
								<th class="column3"><div style="cursor:pointer;" onclick="javascipt:setsorting('end_datetime','<?php echo $rev_sort_order; ?>');">End Date<?php echo $sortImg['sortimg_end_datetime']; ?></div></th>
								<th class="column4"><div style="cursor:pointer;" onclick="javascipt:setsorting('service_name','<?php echo $rev_sort_order; ?>');">Type<?php echo $sortImg['sortimg_service_name']; ?></div></th>
								<th class="column5"><div style="cursor:pointer;" onclick="javascipt:setsorting('doctor_name','<?php echo $rev_sort_order; ?>');">Doctor<?php echo $sortImg['sortimg_doctor_name']; ?></div></th>
								<th class="column6">Action</th>
							</tr>
						</thead>
						<tbody>
						<?php 
						if($total_rows > 0 ) {
						foreach( $appointments as $res) { 
							/// Convert provider timezone to customer timezone ///
							date_default_timezone_set( $res['customer_timezone'] );	
							$appointmentStartTime = $res['start_datetime'];
							$appointmentEndTime   = $res['end_datetime'];
							$from   = new DateTimeZone($res['provider_timezone']);
							$to     = new DateTimeZone($res['customer_timezone']);
							$result = new DateTime($appointmentStartTime, $from);
							$result->setTimezone($to);				
							$convertedappointmentStartTime =  $result->format('Y-m-d H:i');
							$result2 = new DateTime($appointmentEndTime, $from);
							$result2->setTimezone($to);				
							$convertedappointmentEndTime =  $result2->format('Y-m-d H:i');							
							/// Calculating times difference in mins ///
							$currentDateTime = new DateTime();
							$appointmentStartDateTime = new DateTime( $convertedappointmentStartTime );
							$curretDateTime_TimeStamp =  strtotime($currentDateTime->format('Y-m-d H:i'));
							$appointmentStartDateTime_TimeStamp =  strtotime($appointmentStartDateTime->format('Y-m-d H:i'));
							$interval = $appointmentStartDateTime_TimeStamp - $curretDateTime_TimeStamp;
							$totalMins = round($interval / 60,2);						
						?>
								<tr align="center">
									<td ><?php echo date_format( date_create( $convertedappointmentStartTime ), "M d, Y H:i A" ); ?></td>
									<td ><?php echo date_format( date_create( $convertedappointmentEndTime ), "M d, Y H:i A" ); ?></td>
									<td ><?php echo ucfirst($res['name']); ?></td>
									<td ><?php echo ucfirst($res['first_name'])." ".ucfirst($res['last_name'])."<br>Timezone: ".$res['timezone']; ?></td>
									<td>
										<?php 
										/// Cant reschedule past appointments or within 1 hour before appointment start time ///
										if($totalMins >= $rescheduleExpiryTime) { ?>
											<a href="<?php echo site_url('appointments/index/'.$res['hash']); ?>">Reschedule</a>&nbsp;|&nbsp;
										<? } else  { ?>
											<span onclick="javascript:alert('Reschedule options are only available up to <?php echo $rescheduleExpiryTime; ?> minutes prior to the start time of the appointment.');">Reschedule</span>&nbsp;|&nbsp;
										<?php } 	
										if($totalMins >= $cancelExpiryTime) { ?>
											<a href="<?php echo site_url('appointments/cancel/'.$res['hash']); ?>" onclick="javascript:return confirm('Do you want to delete this appointment?');">Cancel</a>
										<? } else { ?>
											<span onclick="javascript:alert('Cancel options are only available up to  <?php echo $cancelExpiryTime; ?> minutes  prior to the start time of the appointment.');">Cancel</span>
										<? } ?>
									</td>
								</tr>
						<?php } } else { ?>	
								<tr align="center">
									<td colspan="6">No Records Found.</td>
								</tr>
						<?php } ?>	
						</tbody>
						<input type="hidden" id="sort_type" value="<?php echo $sort_type; ?>" disabled>
						<input type="hidden" id="sort_order" value="<?php echo $sort_order; ?>" disabled>
						<input type="hidden" id="records_count" value="<?php echo $records_count; ?>" disabled>
					</table>
					<div>&nbsp;</div>
					<?php if( !empty( $total_pages ) && $total_pages > 1) { echo $links; } ?>
				</div>
			</div>
		</div>
	</div>

</div>

   <!-- FRAME FOOTER -->

            <div id="frame-footer">
                <small>
                    <span class="footer-powered-by">
                       <?php echo config('footer_content'); ?>
                    </span>
                </small>
            </div>
        </div>
    </div>
</div>

<?php if ($display_cookie_notice === '1'): ?>
    <?php require 'cookie_notice_modal.php' ?>
<?php endif ?>

<?php if ($display_terms_and_conditions === '1'): ?>
    <?php require 'terms_and_conditions_modal.php' ?>
<?php endif ?>

<?php if ($display_privacy_policy === '1'): ?>
    <?php require 'privacy_policy_modal.php' ?>
<?php endif ?>

<script>
    var GlobalVariables = {
        availableServices: <?= json_encode($available_services) ?>,
        availableProviders: <?= json_encode($available_providers) ?>,
        baseUrl: <?= json_encode(config('base_url')) ?>,
        manageMode: <?= $manage_mode ? 'true' : 'false' ?>,
        customerToken: <?= json_encode($customer_token) ?>,
        dateFormat: <?= json_encode($date_format) ?>,
        timeFormat: <?= json_encode($time_format) ?>,
        firstWeekday: <?= json_encode($first_weekday) ?>,
        displayCookieNotice: <?= json_encode($display_cookie_notice === '1') ?>,
        appointmentData: <?= json_encode($appointment_data) ?>,
        providerData: <?= json_encode($provider_data) ?>,
        customerData: <?= json_encode($customer_data) ?>,
        displayAnyProvider: <?= json_encode($display_any_provider) ?>,
        csrfToken: <?= json_encode($this->security->get_csrf_hash()) ?>
    };

    var EALang = <?= json_encode($this->lang->language) ?>;
    var availableLanguages = <?= json_encode(config('available_languages')) ?>;
</script>

<script src="<?= asset_url('assets/js/general_functions.js') ?>"></script>
<script src="<?= asset_url('assets/ext/jquery/jquery.min.js') ?>"></script>
<script src="<?= asset_url('assets/ext/jquery-ui/jquery-ui.min.js') ?>"></script>
<script src="<?= asset_url('assets/ext/cookieconsent/cookieconsent.min.js') ?>"></script>
<script src="<?= asset_url('assets/ext/bootstrap/js/bootstrap.bundle.min.js') ?>"></script>
<script src="<?= asset_url('assets/ext/popper/popper.min.js') ?>"></script>
<script src="<?= asset_url('assets/ext/tippy/tippy-bundle.umd.min.js') ?>"></script>
<script src="<?= asset_url('assets/ext/datejs/date.min.js') ?>"></script>
<script src="<?= asset_url('assets/ext/moment/moment.min.js') ?>"></script>
<script src="<?= asset_url('assets/ext/moment/moment-timezone-with-data.min.js') ?>"></script>
<script src="<?= asset_url('assets/js/frontend_book_api.js') ?>"></script>
<script src="<?= asset_url('assets/js/frontend_book.js') ?>"></script>

<script>
    $(function () {
        FrontendBook.initialize(true, GlobalVariables.manageMode);
        GeneralFunctions.enableLanguageSelection($('#select-language'));
    });
</script>

</body>
</html>

<script>
$("#sid").change(function () {
    var sid = $('#sid').val();
	redirectUrl();
});

$("#pid").change(function () {
    var pid = $('#pid').val();
	redirectUrl();
});

$("#did").change(function () {
    var did = $('#did').val();
	redirectUrl();
});

$("#lid").change(function () {
    var lid = $('#lid').val();
	redirectUrl2();
});

$( function() {
    $( "#start_date,#end_date" ).datepicker({ dateFormat: 'yy-mm-dd' });
});

$("#search").click(function() {
	var startDate = new Date($('#start_date').val());
	var endDate = new Date($('#end_date').val());

	if($("#start_date").val()=='') {
		alert('Please select start date.');
		$("#start_date").focus();
		return;
	} else if($("#end_date").val()=='') {
		alert('Please select end date.');
		$("#end_date").focus();
		return;
	} else if (endDate < startDate){
		alert('End date should be greater that start date.');
		return;
	}
	redirectUrl();
});

$("#reset").click(function() {
	window.location = '<?php echo $base_url; ?>/index.php/customer/myappointments';
});

function setsorting(sort_type, sort_order) {
	$('#sort_type').val(sort_type);
	$('#sort_order').val(sort_order);
	redirectUrl();
}	

function redirectUrl(controller_name = "myappointments") {
	var sid = $('#sid').val();
	var pid = $('#pid').val();
	var did = $('#did').val();
	var lid = $('#lid').val();
	var start_date = $('#start_date').val();
	var end_date = $('#end_date').val();
	var sort_type  = $('#sort_type').val();
	var sort_order = $('#sort_order').val();
	var url = '';
	var qs  = '';		
	
	if(sid != '') {
	    url += '&sid='+sid;
		qs = '?';
	}	
	if(pid != '') {
	    url += '&pid='+pid;
		qs = '?';
	}
	if(did != '' && typeof did != 'undefined') {
	    url += '&did='+did;
		qs = '?';
	}
	if(lid != '') {
	    url += '&lid='+lid;
		qs = '?';
	}	
	if(start_date != '' &&  end_date != '') {
	    url += '&start_date='+start_date+'&end_date='+end_date;
		qs = '?';		
	}
	if(sort_type != '' &&  sort_order != '') {
	    url += '&sort_type='+sort_type+'&sort_order='+sort_order;
		qs = '?';		
	}	
	
	window.location = '<?php echo $base_url; ?>'+'/index.php/customer/'+controller_name+'/'+qs+url.substr(1);
}	

function redirectUrl2(controller_name = "myappointments") {
	var lid = $('#lid').val();
	var url = '';
	var qs  = '';		
	
	if(lid != '') {
	    url += '&lid='+lid;
		qs = '?';
	}	
	
	window.location = '<?php echo $base_url; ?>'+'/index.php/customer/'+controller_name+'/'+qs+url.substr(1);
}	


</script>