<?php

//namespace donatj;

/**
 * Simple Calendar
 *
 * @author Jesse G. Donat <donatj@gmail.com>
 * @link http://donatstudios.com
 * @license http://opensource.org/licenses/mit-license.php
 *
 */
class SimpleCalendar {

	/**
	 * Array of Week Day Names
	 *
	 * @var array
	 */
	public $wday_names = false;

	private $now;
	private $dailyHtml = array();
	private $dailyHtmlAdd = array();
	private $offset = 0;

	/**
	 * Constructor - Calls the setDate function
	 *
	 * @see setDate
	 * @param null|string $date_string
	 */
	function __construct( $date_string = null ) {
		$this->setDate($date_string);
	}

	/**
	 * Sets the date for the calendar
	 *
	 * @param null|string $date_string Date string parsed by strtotime for the calendar date. If null set to current timestamp.
	 */
	public function setDate( $date_string = null ) {
		if( $date_string ) {
			$this->now = getdate(strtotime($date_string));
		} else {
			$this->now = getdate();
		}
	}

	/**
	 * Add a daily event to the calendar
	 *
	 * @param string      $html The raw HTML to place on the calendar for this event
	 * @param string      $start_date_string Date string for when the event starts
	 * @param null|string $end_date_string Date string for when the event ends. Defaults to start date
	 */
	
	public function addDailyHtml($html, $start_date_string, $end_date_string = null, $current_month_holiday_array = null) {
    static $htmlCount = 0;
    $start_date = strtotime($start_date_string);
    
    $end_date = $end_date_string ? strtotime($end_date_string) : $start_date;
    $working_date = $start_date;

    // Ensure $current_month_holiday_array is an array
    if (!is_array($current_month_holiday_array)) {
        $current_month_holiday_array = [];
    }

    while ($working_date <= $end_date) {
        if (in_array($working_date, $current_month_holiday_array)) {
            $working_date += 86400; // Move to the next day
            continue;
        }

        $tDate = getdate($working_date);
        $this->dailyHtml[$tDate['year']][$tDate['mon']][$tDate['mday']][$htmlCount] = $html;
        $working_date += 86400; // Move to the next day
    }

    $htmlCount++;
}

	
	public function addDailyHtmlAdd( $html, $date_array , $current_month_array ) {
		
		$result_array = array_diff($current_month_array,$date_array);
		static $htmlCount = 0;
		
		$current_date = strtotime(date("j-n-Y"));
		$c_date = strtotime(date('Y-m-d'));
		$six_month_after_date = strtotime(date('j-n-Y',strtotime('+180 days',$c_date)));
		foreach($result_array as $date_string){
			$date_in_time_format = strtotime($date_string);
			if((!($date_in_time_format < $current_date)) && ($date_in_time_format < $six_month_after_date)){
				$tDate = getdate($date_in_time_format);
				$this->dailyHtmlAdd[$tDate['year']][$tDate['mon']][$tDate['mday']][$htmlCount] = $html;
			}
			/*if($date_in_time_format < $six_month_after_date){
				$tDate = getdate($date_in_time_format);
				$this->dailyHtmlAdd[$tDate['year']][$tDate['mon']][$tDate['mday']][$htmlCount] = $html;
			}*/
		}
		$htmlCount++;
	}
	
	
	public function addDailyHtmlForHoliday( $current_month_holiday_html_array, $date_array , $current_month_array ) {
		global $bebcrm;
		$result_array = $date_array;
		static $htmlCount = 0;
		
		$current_date = strtotime(date("j-n-Y"));
		foreach($result_array as $date_string){
			$appointment_id = $current_month_holiday_html_array[$date_string];
			$job_id = utility::getTableFieldById("appointment","job_id","id",$appointment_id);
			$admin_id = utility::getTableFieldById("appointment","admin_id","id",$appointment_id);
			$admin = Admin::getAdminsById($admin_id);
			$job = $gsi->getEnqQuoteJobById($job_id);
			$date_in_time_format = strtotime($date_string);
				$tDate = getdate($date_in_time_format);
				$this->dailyHtmlAddHoliday[$tDate['year']][$tDate['mon']][$tDate['mday']][$htmlCount] = $job." (".ucfirst($admin).")";
		}
		$htmlCount++;
	}

	/**
	 * Clear all daily events for the calendar
	 */
	public function clearDailyHtml() { $this->dailyHtml = array(); }

	/**
	 * Sets the first day of the week
	 *
	 * @param int|string $offset Day to start on, ex: "Monday" or 0-6 where 0 is Sunday
	 */
	public function setStartOfWeek( $offset ) {
		if( is_int($offset) ) {
			$this->offset = $offset % 7;
		} else {
			$this->offset = date('N', strtotime($offset)) % 7;
		}
	}

	/**
	 * Returns/Outputs the Calendar
	 *
	 * @param bool $echo Whether to echo resulting calendar
	 * @return string HTML of the Calendar
	 */
	public function show( $echo = true ) {
		global $config;
		if( $this->wday_names ) {
			$wdays = $this->wday_names;
		} else {
			$today = (86400 * (date("N")));
			$wdays = array();
			for( $i = 0; $i < 7; $i++ ) {
				$wdays[] = strftime('%a', time() - $today + ($i * 86400));
			}
		}

		$this->arrayRotate($wdays, $this->offset);
		$wday    = date('N', mktime(0, 0, 1, $this->now['mon'], 1, $this->now['year'])) - $this->offset;
		$no_days = cal_days_in_month(CAL_GREGORIAN, $this->now['mon'], $this->now['year']);

		$out = '<div class="box-body table-responsive no-padding">';
		$out .= '<table cellpadding="0" cellspacing="0" class="SimpleCalendar"><thead><tr>';

		for( $i = 0; $i < 7; $i++ ) {
			$out .= '<th>' . $wdays[$i] . '</th>';
		}

		$out .= "</tr></thead>\n<tbody>\n<tr>";

		$wday = ($wday + 7) % 7;

		if( $wday == 7 ) {
			$wday = 0;
		} else {
			$out .= str_repeat('<td class="SCprefix">&nbsp;</td>', $wday);
		}

		$count = $wday + 1;
		for( $i = 1; $i <= $no_days; $i++ ) {
			$out .= '<td' . ($i == $this->now['mday'] && $this->now['mon'] == date('n') && $this->now['year'] == date('Y') ? ' class="today"' : '') . ' style="position:relative;">';

			$datetime = mktime(0, 0, 1, $this->now['mon'], $i, $this->now['year']);

			$out .= '<time datetime="' . date('Y-m-d', $datetime) . '">' . $i . '</time>';

			$dHtml_arr = false;
			if( isset($this->dailyHtml[$this->now['year']][$this->now['mon']][$i]) ) {
				$dHtml_arr = $this->dailyHtml[$this->now['year']][$this->now['mon']][$i];
			}

			if( is_array($dHtml_arr) ) {
				foreach( $dHtml_arr as $dHtml ) {
					$out .= '<div class="event">' . $dHtml . '</div>';
				}
			}
			
			$dHtml_arr_add = false;
			if( isset($this->dailyHtmlAdd[$this->now['year']][$this->now['mon']][$i]) ) {
				$dHtml_arr_add = $this->dailyHtmlAdd[$this->now['year']][$this->now['mon']][$i];
			}

			if( is_array($dHtml_arr_add) ) {
				foreach( $dHtml_arr_add as $dHtml ) {
					$date_str = str_pad($i,2,0,STR_PAD_LEFT)."-". str_pad($this->now['mon'],2,0,STR_PAD_LEFT)."-".$this->now['year'];
					$out .= '<div style="position: absolute;bottom: 7px;right:10px;cursor:pointer;font-weight:bold;"><a href="" data-toggle="modal" data-target="#myModal"  class="add_appointment" alt="'.$date_str.'">' . $dHtml . '</a></div>';
				}
			}
			
			$dHtml_arr_add_holiday = false;
			if( isset($this->dailyHtmlAddHoliday[$this->now['year']][$this->now['mon']][$i]) ) {
				$dHtml_arr_add_holiday = $this->dailyHtmlAddHoliday[$this->now['year']][$this->now['mon']][$i];
			}

			if( is_array($dHtml_arr_add_holiday) ) {
				foreach( $dHtml_arr_add_holiday as $dHtml ) {
					$date_str = $i."-".$this->now['mon']."-".$this->now['year'];
					$out .= '<div style="display: table;margin: auto;color:#3C8DBC;">' . $dHtml . '</div>';
				}
			}
			
			//$out .= '<div class="add" style="position: absolute;bottom: 0px;cursor:pointer;font-weight:bold;">Add</div>';

			$out .= "</td>";

			if( $count > 6 ) {
				$out .= "</tr>\n" . ($i != $count ? '<tr>' : '');
				$count = 0;
			}
			$count++;
		}
		$out .= ($count != 1 ? str_repeat('<td class="SCsuffix">&nbsp;</td>', 8 - $count) : '') . "</tr>\n</tbody></table></div>\n";
		if( $echo ) {
			echo $out;
		}

		return $out;
	}

	private function arrayRotate( &$data, $steps ) {
		$count = count($data);
		if( $steps < 0 ) {
			$steps = $count + $steps;
		}
		$steps = $steps % $count;
		for( $i = 0; $i < $steps; $i++ ) {
			array_push($data, array_shift($data));
		}
	}
}
