<?php

namespace Calendars;

class CalDAV {
  
  

  
  

    // --- Statische Methoden ---
  
  public static function updateMethod($item) { 
    
    
    // --- BLOCK: main ---
    
		// getICS, PUT [href] Content-Type: text/calendar; charset=utf-8 If-Match: "Etag"
		// return: header Etag (=ItemChange)
		// $http_response_header
		$calendar = \Tables\Calendar::view($item['parent'], false, true);
		$ics = \Tables\CalendarItem::getIcsAction($item, 'string'); // getICS nimmt nur das Datenobjekt
		$ctx = stream_context_create([
			'http' => [
				'method' => 'PUT',
				'header' => 'Authorization: Basic ' . base64_encode($calendar['username'] . ':' . $calendar['password']) . "\r\nContent-Type: text/calendar, encoding=UTF-8\r\n"
				."If-Match: \"".$item['ItemChange']."\"",
				'content' => $ics
			],
			'ssl' => []
		]);
		file_get_contents(\FOP\Util::rel2abs($item['ItemIdFull'], $calendar['url']), false, $ctx);
		// TODO: 412 abfangen (precondition failed) und behandeln: server hat neuere verion ...?
		// $http_response_header ist array mit header-Zeilen; starts_with 'Etag: '
		foreach ($http_response_header AS $line) {
			if (preg_match('/^Etag: "(.*)"/', $line, $matches)) {
				\FOP\Database::query('UPDATE calendarItem SET synced = 1, ItemChange = ' . \FOP\Database::quote($matches[1]) . ' WHERE ID = ' . intval($item['ID']));
			}
		}
	
    
  }

  public static function deleteMethod($calendar, $itemidfull, $itemchange) { 
    
    
    // --- BLOCK: main ---
    
		// DELETE [href] If-Match: Etag
		$calendar = \Tables\Calendar::view($calendar, false, true);
		$ctx = stream_context_create([
			'http' => [
				'method' => 'DELETE',
				'header' => 'Authorization: Basic ' . base64_encode($calendar['username'] . ':' . $calendar['password']) . "\r\nContent-Type: text/calendar, encoding=UTF-8\r\n"
				."If-Match: \"".$itemchange."\""
			],
			'ssl' => []
		]);
		file_get_contents(\FOP\Util::rel2abs($itemidfull, $calendar['url']), false, $ctx);
		// TODO: 412 abfangen (precondition failed) und behandeln: server hat neuere verion ...?
	
    
  }


  
  

  
  
}



