<?php

// Fügen Sie DIESE ZEILE am Anfang Ihrer PHP-Skripte ein:
require __DIR__ . '/config.php'; // Pfad anpassen, falls config.php nicht im selben Ordner ist

// WICHTIG: Die ID des Kalenders, den Sie bearbeiten möchten (muss mit get_events.php übereinstimmen).
define('TARGET_CALENDAR_ID', 1); // BITTE ANPASSEN!

// ----------------------------------------------------
// 2. ERFORDERLICHE BIBLIOTHEKEN & SETUP
// ----------------------------------------------------
// Dies setzt voraus, dass Sie Sabre/VObject via Composer installiert haben.
require 'vendor/autoload.php'; 

use Sabre\VObject;

// Setzt den Content-Type-Header und empfängt die JSON-Daten aus dem Frontend
header('Content-Type: application/json');
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// Prüfen auf minimale Daten (Aktion ist immer erforderlich)
if (!isset($data['action'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Ungültige Anfrage: Fehlende Aktion.']);
    exit;
}

$action = $data['action'];
$eventId = $data['id'] ?? null; // ID ist optional (bei INSERT fehlt sie)
$timestamp = time();

try {
    // 3. Datenbankverbindung herstellen (PDO)
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4", DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // ====================================================
    // A) AKTION ERSTELLEN (INSERT)
    // ====================================================
    if ($action === 'insert') {
        
        if (!isset($data['title']) || !isset($data['start'])) {
            throw new Exception("Fehlender Titel oder Startdatum für das neue Event.");
        }

        $newUid = uniqid() . '-' . $timestamp . '@familienkalender.de'; // Eindeutige UID
        $newUri = str_replace(['@', '.'], '', $newUid) . '.ics';    // Eindeutige URI (Dateiname)
        $isAllDay = $data['allDay'] ?? false;
        
        // VCALENDAR-Struktur erstellen
        $vcalendar = new VObject\Component\VCalendar();
        $vevent = $vcalendar->addComponent('VEVENT');
        
        // VEVENT-EIGENSCHAFTEN setzen
        $vevent->UID = $newUid;
        $vevent->DTSTAMP = $timestamp;
        $vevent->SUMMARY = $data['title'];
        $vevent->{'LAST-MODIFIED'} = $timestamp; 
        $vevent->{'X-SABRE-UPDATE-HASH'} = hash('sha1', $newUid);
        
        // Start und Ende
        $start = new DateTime($data['start']);
        $vevent->DTSTART = $start;
        
        if (isset($data['end']) && !empty($data['end'])) {
            $end = new DateTime($data['end']);
            $vevent->DTEND = $end;
        }

        // Ganztägige Markierungen setzen
        if ($isAllDay) {
            $vevent->DTSTART['VALUE'] = 'DATE';
            if (isset($vevent->DTEND)) {
                $vevent->DTEND['VALUE'] = 'DATE';
            }
        }
        
        // Serialisieren und INSERT durchführen
        $newIcsData = $vcalendar->serialize();

        $insertStmt = $pdo->prepare("
            INSERT INTO calendarobjects 
            (calendarid, uri, lastmodified, etag, uid, calendardata, size, componenttype, firstoccurence, lastoccurence) 
            VALUES 
            (:calendarid, :uri, :lastmodified, :etag, :uid, :calendardata, :size, :componenttype, :firstoccurence, :lastoccurence)
        ");
        
        $insertStmt->execute([
            ':calendarid' => TARGET_CALENDAR_ID,
            ':uri' => $newUri,
            ':lastmodified' => $timestamp,
            ':etag' => hash('crc32', $newIcsData), 
            ':uid' => $newUid,
            ':calendardata' => $newIcsData,
            ':size' => strlen($newIcsData),
            ':componenttype' => 'VEVENT',
            ':firstoccurence' => $start->getTimestamp(),
            ':lastoccurence' => $start->getTimestamp(), // Einfache Lösung für Einzeltermine
        ]);
        
        $newDbId = $pdo->lastInsertId();

        echo json_encode(['success' => true, 'action' => 'inserted', 'newId' => $newDbId]);
        exit;
    }


    // ====================================================
    // B) AKTION LÖSCHEN (DELETE)
    // ====================================================
    if ($action === 'delete') {
        if (!$eventId) { throw new Exception("ID für Löschung fehlt."); }
        
        $stmt = $pdo->prepare("DELETE FROM calendarobjects WHERE id = :id AND calendarid = :calendar_id");
        $stmt->bindParam(':id', $eventId);
        $stmt->bindParam(':calendar_id', TARGET_CALENDAR_ID);
        $stmt->execute();
        
        echo json_encode(['success' => true, 'action' => 'deleted']);
        exit;
    }

    // ====================================================
    // C) AKTION BEARBEITEN/VERSCHIEBEN (UPDATE)
    // ====================================================
    if ($action === 'update') {
        if (!$eventId) { throw new Exception("ID für Update fehlt."); }

        // 4. Originalen Event aus DB lesen
        $stmt = $pdo->prepare("
            SELECT calendardata
            FROM calendarobjects
            WHERE id = :id AND calendarid = :calendar_id
        ");
        $stmt->bindParam(':id', $eventId);
        $stmt->bindParam(':calendar_id', TARGET_CALENDAR_ID);
        $stmt->execute();
        $originalEvent = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$originalEvent) {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Event nicht gefunden.']);
            exit;
        }
        
        // 5. ICS parsen
        $vcalendar = VObject\Reader::read($originalEvent['calendardata']);
        $vevent = $vcalendar->VEVENT;
        
        if (!$vevent) {
            throw new Exception("VEVENT konnte nicht im ICS-Datenblock gefunden werden.");
        }
        
        // 6. VObject aktualisieren
        $isAllDay = $data['allDay'] ?? false;
        
        // DTSTART & DTEND aktualisieren
        if (isset($data['start'])) {
            $start = new DateTime($data['start']);
            $vevent->DTSTART = $start;
            $vevent->DTSTART['VALUE'] = $isAllDay ? 'DATE' : 'DATE-TIME';

            if (isset($data['end']) && !empty($data['end'])) {
                $end = new DateTime($data['end']);
                $vevent->DTEND = $end;
                $vevent->DTEND['VALUE'] = $isAllDay ? 'DATE' : 'DATE-TIME';
            } else {
                 // Wenn Enddatum im Frontend gelöscht wird, auch im ICS löschen
                 unset($vevent->DTEND);
            }
        }
        
        // Titel (SUMMARY) aktualisieren
        if (isset($data['title'])) {
            $vevent->SUMMARY = $data['title'];
        }

        // Metadaten aktualisieren
        $vevent->{'LAST-MODIFIED'} = $timestamp; 
        $vevent->DTSTAMP = $timestamp;
        $vevent->{'X-SABRE-UPDATE-HASH'} = hash('sha1', uniqid()); 

        // 7. Zurück in ICS stringen
        $updatedIcsData = $vcalendar->serialize();

        // 8. Datenbank-Update durchführen
        $updateStmt = $pdo->prepare("
            UPDATE calendarobjects
            SET calendardata = :calendardata, lastmodified = :timestamp, etag = :etag, size = :size
            WHERE id = :id AND calendarid = :calendar_id
        ");
        $updateStmt->execute([
            ':calendardata' => $updatedIcsData,
            ':timestamp' => $timestamp,
            ':etag' => hash('crc32', $updatedIcsData),
            ':size' => strlen($updatedIcsData),
            ':id' => $eventId,
            ':calendar_id' => TARGET_CALENDAR_ID
        ]);

        echo json_encode(['success' => true, 'action' => 'updated']);
        exit;
    }


} catch (PDOException $e) {
    http_response_code(500);
    // Nur generische Fehler im Produktivsystem ausgeben!
    echo json_encode(['success' => false, 'message' => 'Datenbankfehler: ' . $e->getMessage()]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Event-Verarbeitungsfehler: ' . $e->getMessage()]);
}
?>
