<?php
class Calendarista_HolidayList extends Calendarista_List {
	public $totalPages;
	public $currentPage;
	public $perPage;
	public $orderBy;
	public $order;
	public $availability;
	public $holidays;
	public $projectId;
	public $availabilityId;
	public $availabilityHelper;
	public $startDate;
	public $fullDay;
	function __construct( ){
		$this->projectId =  isset($_GET['projectId']) ? (int)$_GET['projectId'] : null;
		$this->availabilityId = isset($_GET['availabilityId']) ? (int)$_GET['availabilityId'] : null;
		$this->startDate =  isset($_GET['month']) ? strtotime(sanitize_text_field($_GET['month'])) : strtotime(date(CALENDARISTA_DATEFORMAT));
		if(isset($this->projectId) && isset($this->availabilityId)){
			$this->availabilityHelper = new Calendarista_AvailabilityHelper(array(
				'projectId'=>$this->projectId
				, 'availabilityId'=>$this->availabilityId
			));
			$this->availability = $this->availabilityHelper->availability;
			$this->fullDay = $this->availability->fullDay;
		}
		$this->perPage = 32;
		$this->uniqueNamespace = 'calendarista_holiday_';
        parent::__construct( array(
            'singular'  => 'order', 
            'plural'    => 'orders', 
            'ajax'      => false    
        ) );
    }
    function column_default($item, $column_name){
        switch($column_name){
            default:
                return print_r($item,true); 
        }
    }
	function column_ck($item){
		$label = $this->fullDay ? __('Day off', 'calendarista') : __('Entire day off', 'calendarista');
		if(is_null($item['id'])){
			return sprintf('<input type="checkbox" name="holidays[]" value="%s">&nbsp;%s', $item['shortDate'], $label);
		}
		return sprintf('<input type="checkbox" name="holidays_undo[]" value="%s">&nbsp;%s', $item['id'], $label);
	}
	function column_longDate($item){
		if(!is_null($item['id'])){
			if(!$item['timeslotId']){
				return sprintf('<span class="calendarista-linethrough">%s</span>', $item['longDate']);
			}else{
				return sprintf('%s **', iconv("ISO-8859-1", "UTF-8", $item['longDate']));
			}
		}
		return iconv("ISO-8859-1", "UTF-8", $item['longDate']);
	}
	function column_action($item){
		$result = array();
		if(!$this->fullDay){
			array_push($result, sprintf('<button type="submit" name="update" value="1" class="button button-primary timeoff" %s data-selected-date="%s">%s</button>'
				, !$item['timeslotId'] && $item['id'] ? 'disabled' : ''
				, $item['shortDate']
				, __('Time slots', 'calendarista'))
			);
		}
		array_push($result, '</form>');
		return implode('', $result);
	}
    function get_columns(){
        $columns = array();
		$columns['ck'] = '<input type="checkbox" name="updateall">';
		$columns['longDate'] = __('Date', 'calendarista');
		
		if(!$this->fullDay){
			$columns['action'] = __('Action', 'calendarista');
		}
        return $columns;
    }    
    /**
		@description binds to data
	*/
    function bind() {
        
        $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 * $this->perPage;
		}
		$this->items = $this->getListOfDays();
		$total = count($this->items);
		if(!$total){
			return;
		}
        $this->totalPages = ceil($total / $this->perPage);
        $this->set_pagination_args( array(
            'total_items' => $total,
            'per_page'    => $this->perPage,
            'total_pages' => $this->totalPages
        ));
    }
	function getListOfDays(){
		$result = array();
		if(!isset($this->availability)){
			return $result;
		}
		$excludedDates = $this->availabilityHelper->getAllExcludedDates($this->startDate);
		$lastDayOfMonth = strtotime(date('Y-m-t', $this->startDate));
		$this->holidays = $this->getHolidays($this->startDate, $lastDayOfMonth, $this->availabilityId);
		$startDate = $this->startDate;
		setlocale(LC_TIME, get_locale());
		while ($startDate <= $lastDayOfMonth){
			$currentDate = date(CALENDARISTA_DATEFORMAT, $startDate);
			$holiday = $this->findHolidayId($currentDate, $this->holidays);
			if(!in_array($currentDate, $excludedDates['exclusions']) || !is_null($holiday)){
				$id = isset($holiday) ? $holiday['id'] : null;
				$timeslotId = isset($holiday) ? $holiday['timeslotId'] : null;
				array_push($result, array('shortDate'=>$currentDate, 'longDate'=>strftime('%A, %d %b, %Y', $startDate), 'id'=>$id, 'timeslotId'=>$timeslotId));
			}
			$startDate = strtotime('+1 day', $startDate);
		}
		return $result;
	}
	protected function getHolidays($startDate, $endDate, $availabilityId){
		$repo = new Calendarista_HolidaysRepository();
		return $repo->readByDateRange(date(CALENDARISTA_DATEFORMAT, $startDate), date(CALENDARISTA_DATEFORMAT, $endDate), $availabilityId, $this->fullDay);
	}
	protected function findHolidayId($date, $holidays){
		foreach($holidays as $holiday){
			if($date == $holiday['holiday']){
				return array('id'=>$holiday['id'], 'timeslotId'=>$holiday['timeslotId']);
			}
		}
		return null;
	}
	function get_table_classes() {
		return array('wp-list-table', 'calendarista',  'widefat', 'fixed', 'striped', 'calendarista-holiday-list');
	}
	public function no_items() {
		if(!isset($this->projectId) || !isset($this->availabilityId)){
			echo __('Ensure that a service, availability and month are selected.', 'calendarista');
			return;
		}
		echo __('No days found for selected month.', 'calendarista');
	}
}
?>