<?php
$calendar_id = $_GET['calendar'];

//Wird benötigt um Enviroment Variable zu holen
session_start();
$currDir = __DIR__;
$rootDir = dirname(dirname($currDir));
$mysydeDir = $rootDir . '/mysyde';

require_once($rootDir .  '/vendor/autoload.php');
require_once($rootDir . "/mysyde/frontend/frontend_functions.inc.php");
 
// $baseDir = rtrim(dirname(dirname(__DIR__,2),'/'));

$envDir = $rootDir . '/config';
$envFilePath = $envDir . '/.env';
if (is_dir($envDir) && file_exists($envFilePath) && is_file($envFilePath) && is_readable($envFilePath)) {
    $dotenv = new \Dotenv\Dotenv($envDir);
    $dotenv->load();
}
 $common = $mysydeDir ."/common/common_functions.inc.php";
require_once($common);

$connEnv = (local_environment()) ? $mysydeDir."/dc.config.php" : $mysydeDir."/dc-server.config.php";

require_once($connEnv);

db_connect();

function get_collection_data($collection_id, $content_id){
    $query  = "SELECT * FROM main_collection_link WHERE main_collection_id = ".$collection_id . " AND main_collection_setup_content_id = ".$content_id;
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    $row = @mysqli_fetch_array($result);
    return $row['data'];
}

$query  = "SELECT * FROM main_collection WHERE id = ".$calendar_id;
$result = @mysqli_query($GLOBALS['mysql_con'], $query);
$row = @mysqli_fetch_array($result);

$uid = get_collection_rewrite($row['description'], $row['id']);

$start_date = new DateTime(get_collection_data($calendar_id, 54));

// ICS-Daten generieren
$icsData = "BEGIN:VCALENDAR
VERSION:2.0
PRODID: ".$uid."
BEGIN:VEVENT
DTSTART:".$start_date->format('Ymd')."T100000Z
DTEND:".$start_date->format('Ymd')."T100000Z
SUMMARY: ".$row['description']."
DESCRIPTION: ".$row['description']."
END:VEVENT
END:VCALENDAR";
    
// Dateinamen festlegen

$filename = $uid.".ics";
    
// ICS-Datei generieren
header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: attachment; filename=' . $filename);
    
echo $icsData;


?>