<?php
/********************************************************************************
 * (c)1337 aheadware.com - All rights reserved
 ********************************************************************************/
require_once __DIR__ . '/../../../src/server/config/boot_global.php';
require_once __DIR__ . '/../../../src/server/config/boot_local.php';

require_once __DIR__ .'/vendor/autoload.php';

// Retrieve teamId and profileId
$relIds = explode( "/", trim( $_SERVER["REQUEST_URI"], "/" ) );
$profileId = 0;

if ( !is_array( $relIds ) ||  1 > count( $relIds ) ) die ( "EOF" );

$profileId = NULL;
$publicTeamId = $relIds[ 1 ];
$relIds = $relIds[ 1 ];

$relIds = explode( "-", $relIds );
if ( is_array( $relIds ) && 2 == count( $relIds ) )
{
    $publicTeamId = $relIds[ 0 ];
    $profileId = $relIds[ 1 ];
}

// Check if

/** @var TB_Shared_Ent_TeamData_Team $team */
$team = TB_Shared_Ent_TeamData_Team::getByPublicId( $publicTeamId );

if ( !isset( $team ) ) die("EOF");

$teamId = $team->id;

$apps = array();
if ( is_null( $profileId ) )
{
    // Get all appointments by team
    $apps = TB_Shared_Ent_TeamData_Appointment::getCurrentByTeamId( $teamId );
}
else
{
    // Get appointments filetered by profile id
    $apps = TB_Shared_Ent_TeamData_Appointment::getAcceptedByProfile( $teamId, $profileId );
}

// set default timezone (PHP 5.4)
date_default_timezone_set('Europe/Berlin');

$calendarId = 'tbuddy-' . $teamId;
$calenderName = 'TBuddy: ' . $team->display_name;
if ( 0 < (int)$profileId )
{
    $calendarId .= '-' . $profileId;
    $calenderName .= ' - Deine Termine';
}
else
{
    $calenderName .= ' - Alle Termine';
}

// 1. Create new calendar
$vCalendar = new \Eluceo\iCal\Component\Calendar($calendarId);
$vCalendar->setName( $calenderName );
$vCalendar->setDescription( $calenderName );

/** @var TB_Shared_Ent_TeamData_Appointment $app */
foreach( $apps as $app ) {

    $vEvent = new \Eluceo\iCal\Component\Event();
    $vEvent->setDtStart(new \DateTime("@$app->starttime" ) );
    $appEndTS = $app->starttime + ( $app->duration * 60 );
    $vEvent->setDtEnd(new \DateTime("@$appEndTS" ) );
    $vEvent->setNoTime(false);
    $vEvent->setSummary( is_null( $app->subject ) ? $app->home . ':' . $app->guest : $app->subject );
    $vEvent->setLocation( $app->location );
    $vEvent->setDescription( $app->comment );

    // 3. Add event to calendar
    $vCalendar->addComponent($vEvent);

}

// 4. Set headers
header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $calendarId . '.ics"');

// 5. Output
echo $vCalendar->render();