<!DOCTYPE html>
<html>
    <head>
        <title>Evénements à venir</title>
        <meta charset="utf-8">
    </head>
    <body style="font-family: helvetica; line-height: 24px; font-size: 16px;">
        <div id="content">
<?php

require 'settings.php';

// authent
if ($password && (!isset($_SERVER['PHP_AUTH_PW']) || $_SERVER['PHP_AUTH_PW'] != $password))
{
	header('WWW-Authenticate: Basic realm="bbn"');
	header('HTTP/1.0 401 Unauthorized');
	echo '<p>Access denied.</p></body></html>';
	exit;
}

// Enable error reporting for debugging
//error_reporting(E_ALL);
//ini_set('display_errors', 1);

function ics2json($input)
{
    $id = 0;
    $root = [];
    $curr = &$root;
    $lines = explode("\r\n", $input);
    foreach ($lines as $line)
    {
        $parts = explode(":", $line, 2);
        $key = explode(";", $parts[0])[0];
        $val = isset($parts[1]) ? $parts[1] : '';
        if ($key == "BEGIN")
        {
            if (isset($curr[$val]))
            {
                $val .= "_" . ($id++);
            }
            $curr[$val] = ['parent' => &$curr];
            $curr = &$curr[$val];
        } 
        elseif ($key == "END")
        {
            $parent = &$curr['parent'];
            unset($curr['parent']);
            $curr = &$parent;
        }
        else
        {
            $curr[$key] = (strpos($key, "DT") === 0) ? dt($val) : $val;
        }
    }
    $root['VCALENDAR']['VEVENTS'] = [];
    foreach ($root['VCALENDAR'] as $k => $v)
    {
        if ($k == "VEVENT" || strpos($k, "VEVENT_") === 0)
        {
            $root['VCALENDAR']['VEVENTS'][] = $v;
            unset($root['VCALENDAR'][$k]);
        }
    }
    return $root['VCALENDAR'];
}

function dt($s)
{
    $formatted = substr($s, 0, 4) . "-" . substr($s, 4, 2) . "-" . substr($s, 6, 2);
    if (strlen($s) > 8)
    {
        $formatted .= "T" . substr($s, 9, 2) . ":" . substr($s, 11, 2) . ":" . substr($s, 13, 2);
    }
    return new DateTime($formatted);
}

function formatdate($d)
{
    return strftime('%A, %e %B %Y %H:%M', $d->getTimestamp());
}

function getWeek($date)
{
    $dto = new DateTime();
    $dto->setISODate($date->format('o'), $date->format('W'));
    return $dto->format('W');
}

setlocale(LC_TIME, 'fr_FR.UTF-8');

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $davurl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERPWD, $davuser . ':' . $davpassword);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$result = curl_exec($curl);
if (!$result)
{
    die('error');
}
curl_close($curl);

$params = [];
parse_str($_SERVER['QUERY_STRING'], $params);
$recent = isset($params['recent']) ? (int)$params['recent'] : 7;
$recentonly = isset($params['recentonly']);

$html = "<h1>Evénements à venir</h1>";
$html .= "<div>Récent : $recent derniers jours</div>";

$o = ics2json($result);
$lastmodified = new DateTime();
$lastmodified->modify("-$recent days");
$group = [];
usort($o['VEVENTS'], function($a, $b)
{
    return $a['DTSTART'] <=> $b['DTSTART'];
});

foreach ($o['VEVENTS'] as $e)
{
    if ($e['DTSTART'] >= new DateTime() && (!$recentonly || $e['DTSTAMP'] >= $lastmodified))
    {

        $formatteddate = strftime('%A %d %B %Y %H:%M', $e['DTSTART']->getTimestamp());
        $splitdate = explode(' ', $formatteddate);
        $year = $splitdate[3];
        $month = $splitdate[2];
        $week = getWeek($e['DTSTART']);
        if (!isset($group[$year]))
        {
            $html .= "<h2>$year</h2>";
            $group[$year] = [];
        }
        if (!isset($group[$year][$month]))
        {
            $html .= "<h3>". ucfirst($month) ."</h3>";
            $group[$year][$month] = [];
        }
        if (!isset($group[$year][$month][$week]))
        {
            $html .= "<h4>Semaine $week</h4>";
            $group[$year][$month][$week] = true;
        }
        $line = "<li title=\"modifié le " . strftime('%A, %e %B %Y %H:%M', $e['DTSTAMP']->getTimestamp()) . "\">";
        $line .= ucfirst($formatteddate) . ": " . $e['SUMMARY'];
        if ($e['DTSTAMP'] >= $lastmodified)
        {
            $line .= " 🆕";
        }
        $line .= '</li>';
        $html .= $line;
    }
}
echo $html;
?>
        </div>
    </body>
</html>