<?php

require_once "common.php";

//require_once "_include/calendar/autoload.php";

use ICal\ICal;

try {
    $ical = new ICal('https://www.usrspace.at/termine.ics', array(
        'defaultSpan'                 => 2,     // Default value
        'defaultTimeZone'             => 'UTC',
        'defaultWeekStart'            => 'MO',  // Default value
        'disableCharacterReplacement' => false, // Default value
        'skipRecurrence'              => false, // Default value
        'useTimeZoneWithRRules'       => false, // Default value
    ));
} catch (\Exception $e) {
    die($e);
}

if (isset($_GET['o']) and ($_GET['o'] === 'json')) {
    if (isset($_GET['r']) and is_numeric($_GET['r']) and (0 < $_GET['r']) and ($_GET['r'] < 366)) {
        $range = $_GET['r'] ;
    } else {
        $range = 31 ;
    }
    $result = array();
    $events = $ical->eventsFromRange(date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59', time() + ($range * 24 * 60 * 60)));
    if ($events) {
        foreach ($events as $event) {
            $dtstart = $ical->iCalDateToDateTime($event->dtstart_array[3]);
            $dtend = $ical->iCalDateToDateTime($event->dtend_array[3]);
            $result[] = array (
                "name" => $event->summary,
                "begin" => $dtstart->format(DATE_ATOM),
                "end" => $dtend->format(DATE_ATOM),
                "begin_date" => $dtstart->format('d.m.Y'),
                "begin_time" => $dtstart->format('H:i'),
                "end_date" => $dtend->format('d.m.Y'),
                "end_time" => $dtend->format('H:i'),
                "location" => $event->location,
                "description" => $event->description
            );
        }
    }
    header("Content-Type: application/json; charset=UTF-8");
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
} else if (isset($_GET['o']) and ($_GET['o'] === 'sidebar')) {
    header("Content-Type: text/plain; charset=UTF-8");

    $today = date("w") ; // 0 = Sonntag
	if ($today == 0) $today = 7;
	// Zeitraum 5 Wochen
	$first_day = strtotime("-1 week") - ((60*60*24)*($today-1)) ; // Erster Montag
	$last_day = strtotime("+3 weeks") + ((60*60*24)*(7-$today)) ; // letzter Sonntag
	$output = "";
	$day = $first_day;

    $events = $ical->eventsFromRange(date('Y-m-d 00:00:00', $first_day), date('Y-m-d 23:59:59', $last_day));

	for ($w = 0; $w < 5; $w++) {
		$output .= "<tr>";
		for ($d = 0; $d < 7; $d++) {
			if ($eventname = check_for_event($events, $day)) {
				$output .= '<td class="cal_event"><a href="https://cloud.usrspace.at/index.php/apps/calendar/p/zFFtLkG8aK9e7T9N/usrspace-Termine" title="' . $eventname . '">' . date("d",$day) . "</a></td>";
			} else if (date("Y-m-d", $day) == date("Y-m-d", time())) {
				$output .= '<td class="cal_today"><div>'.date("d",$day)."</div></td>";
			} else {
				$output .= "<td>".date("d",$day)."</td>";
			}
			$day = $day + (60*60*24);
		}
		$output .= "</tr>\n";
    }
    echo $output;
} else {
    $Content = get_template('/calendar.htm');

    $Entry = "<div class=\"4u 12u$(medium)\">
        <div class=\"box\">
            <h3><@Name@></h3>
            <ul class=\"alt\">
                <li><strong>Datum:</strong> <@Date@></li>
                <li><strong>Uhrzeit:</strong> <@Time@></li>
                <li><strong>Ort:</strong> <@Location@></li>
            </ul>
            <@Description@>
        </div>
    </div>";

    $Styles  = '' ;
    $Scripts  = '' ;

    $events = $ical->eventsFromRange(date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59', time() + (7 * 24 * 60 * 60)));
    if ($events) {
        $count = 1;
        $Row = "<div class=\"row\">";
        foreach ($events as $event) {
            $NewEvent = str_replace('<@Name@>',$event->summary,$Entry);
            $dtstart = $ical->iCalDateToDateTime($event->dtstart_array[3], $forceTimeZone);
            $dtend = $ical->iCalDateToDateTime($event->dtend_array[3], $forceTimeZone);
            if ($dtstart->format('d.m.Y') != $dtend->format('d.m.Y')) {
                $NewEvent = str_replace('<@Date@>',$dtstart->format('d.m.Y') . ' - ' . $dtend->format('d.m.Y'),$NewEvent);
                $NewEvent = str_replace('<@Time@>','--',$NewEvent);
            } else {
                $NewEvent = str_replace('<@Date@>',$dtstart->format('d.m.Y'),$NewEvent);
                if ($dtstart->format('H:i') != $dtend->format('H:i')) {
                    $NewEvent = str_replace('<@Time@>',$dtstart->format('H:i') . ' - ' . $dtend->format('H:i'),$NewEvent);
                }
            }
            $NewEvent = str_replace('<@Location@>',$event->location,$NewEvent);
            if ($event->description !== NULL) {
                $description = preg_replace('/(http(s)?:\/\/(.+))/m', '<a href="$1">$3</a>', $event->description);
                $NewEvent = str_replace('<@Description@>','<p>'.nl2br($description).'</p>',$NewEvent);
            } else {
                $NewEvent = str_replace('<@Description@>','',$NewEvent);
            }
            $Row .= $NewEvent;
            //var_dump($event);
            if (($count > 1) && ($count % 3 === 0)) {
                $Row .= "</div><div class=\"row\">";
            }
        }
        $Row .= "</div>";
        $Content = str_replace('<@NextWeek@>',$Row,$Content);
    } else {
        $Content = str_replace('<@NextWeek@>','<h4>Keine</h4>',$Content);
    }

    $events = $ical->eventsFromRange(date('Y-m-d 00:00:00', time() + (8 * 24 * 60 * 60)), date('Y-m-d 23:59:59', time() + (31 * 24 * 60 * 60)));
    if ($events) {
        $count = 1;
        $Row = "<div class=\"row\">";
        foreach ($events as $event) {
            $NewEvent = str_replace('<@Name@>',$event->summary,$Entry);
            $dtstart = $ical->iCalDateToDateTime($event->dtstart_array[3], $forceTimeZone);
            $dtend = $ical->iCalDateToDateTime($event->dtend_array[3], $forceTimeZone);
            if ($dtstart->format('d.m.Y') != $dtend->format('d.m.Y')) {
                $NewEvent = str_replace('<@Date@>',$dtstart->format('d.m.Y') . ' - ' . $dtend->format('d.m.Y'),$NewEvent);
                $NewEvent = str_replace('<@Time@>','ganztägig',$NewEvent);
            } else {
                $NewEvent = str_replace('<@Date@>',$dtstart->format('d.m.Y'),$NewEvent);
                if ($dtstart->format('H:i') != $dtend->format('H:i')) {
                    $NewEvent = str_replace('<@Time@>',$dtstart->format('H:i') . ' - ' . $dtend->format('H:i'),$NewEvent);
                }
            }
            $NewEvent = str_replace('<@Location@>',$event->location,$NewEvent);
            if ($event->description !== NULL) {
                $description = preg_replace('/(http(s)?:\/\/(.+))/', '<a href="$1">$3</a>', $event->description);
                $NewEvent = str_replace('<@Description@>','<p>'.nl2br($description).'</p>',$NewEvent);
            } else {
                $NewEvent = str_replace('<@Description@>','',$NewEvent);
            }
            $Row .= $NewEvent;
            //var_dump($event);
            if (($count > 1) && ($count % 3 === 0)) {
                $Row .= "</div><div class=\"row\">";
            }
        }
        $Row .= "</div>";
        $Content = str_replace('<@NextMonth@>',$Row,$Content);
    } else {
        $Content = str_replace('<@NextMonth@>','<h4>Keine</h4>',$Content);
    }

    $events = $ical->eventsFromRange(date('Y-m-d 00:00:00', time() + (32 * 24 * 60 * 60)), date('Y-m-d 23:59:59', time() + (124 * 24 * 60 * 60)));
    if ($events) {
        $count = 1;
        $Row = "<div class=\"row\">";
        foreach ($events as $event) {
            $NewEvent = str_replace('<@Name@>',$event->summary,$Entry);
            $dtstart = $ical->iCalDateToDateTime($event->dtstart_array[3], $forceTimeZone);
            $dtend = $ical->iCalDateToDateTime($event->dtend_array[3], $forceTimeZone);
            if ($dtstart->format('d.m.Y') != $dtend->format('d.m.Y')) {
                $NewEvent = str_replace('<@Date@>',$dtstart->format('d.m.Y') . ' - ' . $dtend->format('d.m.Y'),$NewEvent);
                $NewEvent = str_replace('<@Time@>','--',$NewEvent);
            } else {
                $NewEvent = str_replace('<@Date@>',$dtstart->format('d.m.Y'),$NewEvent);
                if ($dtstart->format('H:i') != $dtend->format('H:i')) {
                    $NewEvent = str_replace('<@Time@>',$dtstart->format('H:i') . ' - ' . $dtend->format('H:i'),$NewEvent);
                }
            }
            $NewEvent = str_replace('<@Location@>',$event->location,$NewEvent);
            if ($event->description !== NULL) {
                $description = preg_replace('/(http(s)?:\/\/(.+))/', '<a href="$1">$3</a>', $event->description);
                $NewEvent = str_replace('<@Description@>','<p>'.nl2br($description).'</p>',$NewEvent);
            } else {
                $NewEvent = str_replace('<@Description@>','',$NewEvent);
            }
            $Row .= $NewEvent;
            //var_dump($event);
            if (($count > 1) && ($count % 3 === 0)) {
                $Row .= "</div><div class=\"row\">";
            }
        }
        $Row .= "</div>";
        $Content = str_replace('<@NextYear@>',$Row,$Content);
    } else {
        $Content = str_replace('<@NextYear@>','<h4>Keine</h4>',$Content);
    }

    $template = get_template('/main.htm');
    $template = str_replace('<@Styles@>',$Styles,$template);
    $template = str_replace('<@Sidebar@>',get_template('/sidebar.htm'),$template);
    $template = str_replace('<@CalendarRange@>',gen_calendar_header(),$template);
    $template = str_replace('<@CalendarContent@>',gen_calendar_content(),$template);
    $template = str_replace('<@Content@>',$Content,$template);
    $template = str_replace('<@Scripts@>',$Scripts,$template);
    print_template($template);
}
?>
