<?php
try {
	include 'config.php';
	$conn = new PDO("mysql:dbname=$MYSQL_DBNAME;host=$MYSQL_HOST", $MYSQL_USERNAME, $MYSQL_PASSWORD);
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn-> exec("SET CHARACTER SET utf8");

	header('Content-type: text/calendar; charset=utf-8');

} catch(PDOException $e) {
	echo "Webseite wird momentan überarbeitet";
	return;
}

$stmt = $conn->prepare('select * from places');
if(isset($_GET["places_id"])){
	$stmt = $conn->prepare('select * from places where id = :id');
	$stmt->bindParam(':id', $_GET["places_id"]);
}else{

	$filename = "all.ics";
}
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if(isset($_GET["places_id"])){
	$filename =  $result['name'].'.ics';
}else{
	$filename = "all.ics";
}
header('Content-Disposition: inline; filename=' . $filename);

function dateToCal($timestamp) {
  return date('Ymd\THis\Z', strtotime($timestamp));
}
// Escapes a string of characters
function escapeString($string) {
  return preg_replace('/([\,;])/','\\\$1', str_replace("\n","\r\n ", str_replace("\r\n","\n",$string)));
}

$stmt = $conn->prepare('select events.*,places.address from events join places on events.places_id=places.id');
if(isset($_GET["places_id"])){
	$stmt = $conn->prepare('select events.*,places.address from events join places on events.places_id=places.id where places_id = :id');
	$stmt->bindParam(':id', $_GET["places_id"]);
}
$stmt->execute();

?>
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
CALSCALE:GREGORIAN
<?php
  foreach($stmt->fetchAll() as $row) {
 ?>
BEGIN:VEVENT
UID:<?= uniqid() ?>

DTSTAMP:<?= date('Ymd\THis\Z',time()) ?>

LOCATION:<?= escapeString($row['address']) ?>

DESCRIPTION:<?= escapeString($row['description']) ?>

URL;VALUE=URI:<?= escapeString("http://kartontage.de/") ?>

SUMMARY:<?= escapeString($row['title']) ?>

CATEGORIES:<?= escapeString($row['category']) ?>

DTSTART:<?= dateToCal($row['time']) ?>

END:VEVENT
<?php } ?>
END:VCALENDAR
