<?php

namespace api;
use PT;
use Sabre;

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    @header('Access-Control-Allow-Origin: *');
    @header("Access-Control-Allow-Credentials: true");
    @header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS, PROPFIND, REPORT');
    @header('Access-Control-Max-Age: 1000');
    @header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization, Depth, If-Match');
    @header('Control-Type: text/plain');
    @header('Control-Length: 0');
    http_response_code(204);
    die;
}

@header('Access-Control-Allow-Origin: *');

// settings
date_default_timezone_set('Europe/London');
$host = getenv("MYSQL_HOST");
$user = getenv("MYSQL_USER");
$password = getenv("MYSQL_PASSWORD");
$db = getenv("MYSQL_DATABASE");

$pdo = new \PDO('mysql:host=' . $host . ';dbname=' . $db, $user, $password);
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
// Files we need
require_once 'vendor/autoload.php';
// Backends
$authBackend = new Sabre\DAV\Auth\Backend\PDO($pdo);
$tokenBackend = new PT\TokenAuth($pdo);
$calendarBackend = new Sabre\CalDAV\Backend\PDO($pdo);
$principalBackend = new Sabre\DAVACL\PrincipalBackend\PDO($pdo);
// Directory structure
$tree = [
    new Sabre\CalDAV\Principal\Collection($principalBackend),
    new Sabre\CalDAV\CalendarRoot($principalBackend, $calendarBackend),
];
$server = new Sabre\DAV\Server($tree);
if (isset($baseUri))
    $server->setBaseUri($baseUri);
/* Server Plugins */

$authPlugin = new Sabre\DAV\Auth\Plugin($authBackend);
$authPlugin->addBackend($tokenBackend);
$server->addPlugin($authPlugin);
$aclPlugin = new Sabre\DAVACL\Plugin();
$server->addPlugin($aclPlugin);
/* CalDAV support */
$caldavPlugin = new Sabre\CalDAV\Plugin();
$server->addPlugin($caldavPlugin);
/* Calendar subscription support */
$server->addPlugin(
    new Sabre\CalDAV\Subscriptions\Plugin()
);
/* Calendar scheduling support */
$server->addPlugin(
    new Sabre\CalDAV\Schedule\Plugin()
);
/* WebDAV-Sync plugin */
$server->addPlugin(new Sabre\DAV\Sync\Plugin());
/* CalDAV Sharing support */
$server->addPlugin(new Sabre\DAV\Sharing\Plugin());
$server->addPlugin(new Sabre\CalDAV\SharingPlugin());
// Support for html frontend
$browser = new Sabre\DAV\Browser\Plugin();
$server->addPlugin($browser);
// And off we go!
$server->exec();