<?php
/********************************************************************************
 * (c)1337 aheadware.com - All rights reserved
 ********************************************************************************/
require_once __DIR__ . '/../../../server/server/config/boot_global.php';
require_once __DIR__ . '/../../../server/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" );

$returnJson = false;
if ( array_key_exists( 'format', $_GET ) && 'json' === $_GET[ 'format' ] )
{
    $returnJson = true;
}

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

$apps = array();
$calendarId = '';
$calenderName = '';

// Profile OR Group ???

if ( 4 === strlen( $publicId ) )
{
    // Group
    $team = TB_Shared_Ent_TeamData_Team::getByPublicId( $publicId );

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

    $calendarId = 'probuddy-' . $publicId;
    $calenderName = 'ProBuddy: Gruppentermine ' . $team->display_name;

    // Last 30 days
    $daysInPast = 30;
    $daysInFuture = 365;
    $nowDt = TB_Server_Utils_Helper::getUTCNowDateTime();
    $fromDt = $nowDt->sub( DateInterval::createFromDateString( $daysInPast .' days' ) );
    $nowDt = TB_Server_Utils_Helper::getUTCNowDateTime();
    $untilDt = $nowDt->add( DateInterval::createFromDateString( $daysInFuture .' days' ) );

    $apps = TB_Shared_Ent_TeamData_Appointment::getByTeamIdAndTimespan( $team->id, $fromDt, $untilDt );
}
else
{
    // Profile
    /** @var TB_Shared_Ent_TeamData_Profile $profile */
    $profile = TB_Shared_Ent_TeamData_Profile::getByPublicId( $publicId );

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

    $calendarId = 'probuddy-' . $publicId;
    $calenderName = 'ProBuddy: Deine Termine';

    // Get appointments filetered by profile id
    $apps = TB_Shared_Ent_TeamData_Appointment::getAcceptedByProfile( $profile->id, true );
}


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

// Allow cors

if ( true === $returnJson )
{
    $jsonApps = array();
    /** @var TB_Shared_Ent_TeamData_Appointment $app */
    foreach( $apps as $app )
    {
        array_push( $jsonApps, $app->asArray() );
    }
        $jsonStruct = array(
        "name" => $calenderName,
        "appointments" => $jsonApps
    );
    header("Access-Control-Allow-Origin: *");
    header('Content-Type: application/json');
    echo json_encode( $jsonStruct );
}
else
{
    // 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( $app->start_dt );
        $vEvent->setDtEnd( $app->end_dt );
        $vEvent->setNoTime(false);
        $vEvent->setSummary( $app->subject );
        $vEvent->setLocation( $app->location );
        $vEvent->setDescription( $app->comment );

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

    }

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

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