<?php
class Calendarista_UserHistoryResultList extends Calendarista_UList {
	public $perPage;
	public $orderBy;
	public $projects;
	protected $pages;
	protected $generalSetting;
	protected $availabilityRepo;
	protected $bookedAvailabilityRepo;
	protected $availability;
	protected $timezone;
	protected $clientTime;
  function __construct($projects = null){
	  $this->projects = $projects;
	  $this->pages = $this->prepareGetPageLink();
		parent::__construct( array(
            'singular'  => 'order', 
            'plural'    => 'orders', 
            'ajax'      => false    
        ) );
		$repo = new Calendarista_GeneralSettingsRepository();
		$this->generalSetting = $repo->read();
		$this->availabilityRepo = new Calendarista_AvailabilityRepository();
		$this->bookedAvailabilityRepo = new Calendarista_BookedAvailabilityRepository();
		$this->timezone = isset($_REQUEST['timezone']) ? sanitize_text_field($_REQUEST['timezone']) : null;
		$this->clientTime = isset($_REQUEST['clientTime']) ? sanitize_text_field($_REQUEST['clientTime']) : null;
    }
    
	function single_row( $item ) {
		echo $this->single_row_columns( $item );
	}
	
    function column_default($item, $column_name){
        switch($column_name){
            default:
                return print_r($item,true); 
        }
    }
    
	function column_item($item){
		$status = (int)$item['status'];
		$title = sprintf('%s - %s', $item['projectName'], $item['availabilityName']);
		$appointmentStatus = sprintf('<span class="badge text-bg-success" title="%s">&nbsp;</span>', __('CONFIRMED', 'calendarista'));
		if($status === Calendarista_AvailabilityStatus::PENDING){
			$appointmentStatus = sprintf('<span class="badge text-bg-warning" title="%s">&nbsp;</span>', __('PENDING', 'calendarista'));
		}else if($status === Calendarista_AvailabilityStatus::CANCELLED){
			$appointmentStatus = sprintf('<span class="badge text-bg-danger" title="%s">&nbsp;</span>', __('CANCELLED', 'calendarista'));
		}
		$availableDate = Calendarista_TimeHelper::formatDate($item['fromDate']);
		$endDate = null;
		if(date(CALENDARISTA_DATEFORMAT, strtotime($item['fromDate'])) !== date(CALENDARISTA_DATEFORMAT, strtotime($item['toDate']))){
			$endDate = Calendarista_TimeHelper::formatDate($item['toDate']);
		}
		$startTime = null;
		$endTime = null;
		if($item['startTimeId'] && (int)$item['startTimeId'] !== -1){
			$timeslot = date("H:i", strtotime($item['fromDate']));
			$startTime = Calendarista_TimeHelper::formatTime(array(
				'timezone'=>null
				, 'serverTimezone'=>null
				, 'time'=>$timeslot
			));
		}
		if($item['endTimeId'] && (int)$item['endTimeId'] !== -1){
			$timeslot = date("H:i", strtotime($item['toDate']));
			$endTime = Calendarista_TimeHelper::formatTime(array(
				'timezone'=>null
				, 'serverTimezone'=>null
				, 'time'=>$timeslot
			));
		}
		$appointmentStartDate = trim($availableDate . ' ' . $startTime);
		$appointmentEndDate = null;
		if($endTime && date(CALENDARISTA_DATEFORMAT, strtotime($item['fromDate'])) === date(CALENDARISTA_DATEFORMAT, strtotime($item['toDate']))){
			$appointmentStartDate .= sprintf(' - %s', $endTime);
		}else if($endDate){
			$appointmentEndDate = trim($endDate . ' ' . $endTime);
		}
		$startLabel = null;
		$endLabel = null;
		if($appointmentEndDate){
			$startLabel = __('Starts on: ', 'calendarista');
			$endLabel = __('Ends on: ', 'calendarista');
		}
		$description = '';
		$optionals = Calendarista_NotificationEmailer::getOptionals((int)$item['orderId']);
		$customFormFields = Calendarista_NotificationEmailer::getCustomFormElements((int)$item['orderId']);
		$dynamicFields = Calendarista_NotificationEmailer::getDynamicFields((int)$item['orderId']);
		if($optionals){
			$description .= sprintf('<div class="calendarista_child_item%d collapse mb-1 calendarista-typography--caption1 calendarista-description-toggle">%s</div>', $item['id'], $optionals);
		}
		if($customFormFields){
			$description .= sprintf('<div class="calendarista_child_item%d collapse mb-1 calendarista-typography--caption1 calendarista-description-toggle">%s</div>', $item['id'], $customFormFields);
		}
		if($dynamicFields){
			$description .= sprintf('<div class="calendarista_child_item%d collapse mb-1 calendarista-typography--caption1 calendarista-description-toggle">%s</div>', $item['id'], $dynamicFields);
		}
		if($description){
			$description = sprintf('<div class="mb-1 calendarista-viewmore" data-bs-toggle="collapse" data-bs-target=".calendarista_child_item%d" data-calendarista-id="calendarista_child_item%d"><span class="badge text-bg-info"><i class="fa fa-plus"></i> %s</span></div>%s',$item['id'] ,$item['id'], __('Appointment details', 'calendarista'), $description);
		}
		$result = '<div class="container">';
		$result .= 		'<div class="row align-items-center">';
		$result .= 			'<div class="col-1">';
		$result .= 				$appointmentStatus;
		$result .=			'</div>';//col-1
		$result .= 			'<div class="col-11">';
		$result .= 				'<div class="container">';
		$result .= 					'<div class="row align-items-center">';
		$result .= 							'<div class="col-md-auto h-100">';
		$result .= 								'<div class="mb-1 calendarista-typography--subtitle2">' . $title . '</div>';
		$result .= 								'<div class="mb-1 calendarista-typography--subtitle2"><i class="fa fa-calendar"></i> ' . trim(sprintf('%s %s', $startLabel, $appointmentStartDate)) . '</div>';
		if($appointmentEndDate){
			$result .= 							'<div class="mb-1 calendarista-typography--subtitle2"><i class="fa fa-calendar"></i> ' . trim(sprintf('%s %s', $endLabel, $appointmentEndDate)) . '</div>';
		}
		if($description){
			$result .= $description;
		}
		$result .= 							'</div>';//col h-100
		$result .= 					'</div>';//row
		$result .= 				'</div>';//container
		$result .= 			'</div>';//col-11
		$result .= 		'</div>';//row
		$result .= 	'</div>';//container
		return $result;
	}
    function get_columns(){
        $columns = array(
			'item'=>''
        );
		
        return $columns;
    }
    function get_sortable_columns() {
		//true means its already sorted
        $sortable_columns = array();
        return $sortable_columns;
    }
    
    /**
		@description binds to data
	*/
    function bind() {
        $per_page = 10;
        
        $columns = $this->get_columns();
        $hidden = array();
        $sortable = $this->get_sortable_columns();
        
        $this->_column_headers = array($columns, $hidden, $sortable);
        $currentPage = $this->get_pagenum() - 1;
		if($currentPage){
			$currentPage = $currentPage * $per_page;
		}
		$cancelId = isset($_POST['cancelId']) ? (int)$_POST['cancelId'] : null;
		if($cancelId){
			$this->cancelAppointment($cancelId);
		}
		$userInfo = Calendarista_PermissionHelper::getUserInfo();
		$result = null;
		if($userInfo){
			$orderRepo = new Calendarista_OrderRepository();
			$orderIdList = $orderRepo->readByUserIdOrEmail($userInfo);
			if($orderIdList && count($orderIdList) > 0){
				$bookedAvailabilityRepo = new Calendarista_BookedAvailabilityRepository();
				$result = $bookedAvailabilityRepo->readByOrderIdList(array(
					'orderIdList'=>$orderIdList
					, 'upcoming'=>false
					, 'pageIndex'=>$currentPage
					, 'limit'=>$per_page
				));
			}
		}
		if(!$result || count($result['resultset']) === 0){
			$this->items = array();
			$this->set_pagination_args(array(
				'total_items' => 0,
				'per_page'    => $per_page,
				'total_pages' => 0
			));
			return;
		}
		$total = $result['total'];
        $total_pages = ceil($total / $per_page);
        $this->items = $result['resultset'];
        $this->set_pagination_args(array(
            'total_items' => $total,
            'per_page'    => $per_page,
            'total_pages' => $total_pages
        ));
    }
	function get_table_classes() {
		return array('calendarista-upcoming-appointment-list list-group');
	}
	public function no_items() {
		if(!Calendarista_PermissionHelper::isUserLoggedIn()){
			echo sprintf('<div class="alert alert-warning" role="alert">%s</div>', __('Please login to view your appointments.', 'calendarista'));
			return;
		}
		echo sprintf('<div class="alert alert-warning" role="alert">%s</div>', __('No items found.', 'calendarista'));
	}
}
?>