<?php
// 1. CORS & Security Header
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit(0);
}

// 2. KONFIGURATION
$json_file = __DIR__ . '/termine.json';
$blacklist_file = __DIR__ . '/google_sperrliste.json';
$admin_password = "volker04";

// Deine iCal-Liste (Google, iCloud etc.)
$ical_urls = [
    "https://calendar.google.com/calendar/ical/8c45044855d4158f25be510e19b0e60032573e2249c75431edf73a6682c6bd22%40group.calendar.google.com/public/basic.ics"
];

if (!file_exists($json_file)) file_put_contents($json_file, json_encode([]));
if (!file_exists($blacklist_file)) file_put_contents($blacklist_file, json_encode([]));

$local_data = json_decode(file_get_contents($json_file), true) ?? [];
$blacklist = json_decode(file_get_contents($blacklist_file), true) ?? [];

$method = $_SERVER['REQUEST_METHOD'];

// 3. TERMINE AUSLESEN (GET)
if ($method === 'GET') {
    $external_events = [];
    
    foreach ($ical_urls as $url) {
        if (!empty($url) && strpos($url, 'http') === 0) {
            $ics_content = @file_get_contents($url);
            
            if ($ics_content !== false) {
                preg_match_all('/BEGIN:VEVENT.*?END:VEVENT/si', $ics_content, $vevents);
                
                foreach ($vevents[0] as $vevent) {
                    preg_match('/SUMMARY:(.*?)\r?\n/si', $vevent, $summary);
                    $title = isset($summary[1]) ? trim($summary[1]) : 'Externer Termin';
                    
                    preg_match('/DESCRIPTION:(.*?)\r?\n/si', $vevent, $description);
                    $desc = isset($description[1]) ? trim($description[1]) : '';
                    $desc = str_replace(['\\n', '\\,', '\\;'], ["\n", ',', ';'], $desc);
                    
                    preg_match('/DTSTART(?:;VALUE=DATE)?:([0-9TZ]+)/si', $vevent, $dtstart);
                    
                    if (isset($dtstart[1])) {
                        $raw_date = trim($dtstart[1]);
                        
                        if (strpos($raw_date, 'T') !== false) {
                            $parts = explode('T', $raw_date);
                            $date_y_m_d = date('Y-m-d', strtotime($parts[0]));
                            $time_h_m = date('H:i', strtotime($parts[0] . ' ' . substr($parts[1], 0, 6)));
                        } else {
                            $date_y_m_d = date('Y-m-d', strtotime($raw_date));
                            $time_h_m = null;
                        }
                        
                        $event_id = "google_" . md5(trim($title) . $date_y_m_d);
                        
                        if (in_array($event_id, $blacklist)) {
                            continue;
                        }
                        
                        $icon = (strpos($url, 'icloud.com') !== false) ? " 🍏" : " 📅";
                        
                        $external_events[] = [
                            "id" => $event_id,
                            "title" => htmlspecialchars($title) . $icon,
                            "date" => $date_y_m_d,
                            "time" => $time_h_m,
                            "description" => htmlspecialchars($desc) . "\n\n(Synchronisiert aus externem Kalender)"
                        ];
                    }
                }
            }
        }
    }
    
    $combined_data = array_merge($local_data, $external_events);
    echo json_encode($combined_data);
    exit;
}

// 4. AKTIONEN VERARBEITEN (POST)
if ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['password']) || $input['password'] !== $admin_password) {
        http_response_code(401);
        echo json_encode(["error" => "Falsches Passwort!"]);
        exit;
    }

    if (isset($input['action']) && $input['action'] === 'check') {
        echo json_encode(["success" => true]);
        exit;
    }

    // A) TERMIN HINZUFÜGEN
    if (isset($input['action']) && $input['action'] === 'add') {
        $newEvent = [
            "id" => time() . rand(10, 99),
            "title" => isset($input['title']) ? htmlspecialchars($input['title']) : 'Unbenannt',
            "date" => $input['date'],
            "time" => !empty($input['time']) ? $input['time'] : null,
            "description" => isset($input['description']) ? htmlspecialchars($input['description']) : ''
        ];
        $local_data[] = $newEvent;
        file_put_contents($json_file, json_encode($local_data, JSON_PRETTY_PRINT));
        echo json_encode(["success" => true, "event" => $newEvent]);
        exit;
    }

    // B)  TERMIN EDITIEREN
    if (isset($input['action']) && $input['action'] === 'edit') {
        $idToEdit = $input['id'];
        
        foreach ($local_data as &$ev) {
            if ($ev['id'] == $idToEdit) {
                $ev['title'] = isset($input['title']) ? htmlspecialchars($input['title']) : $ev['title'];
                $ev['date'] = $input['date'];
                $ev['time'] = !empty($input['time']) ? $input['time'] : null;
                $ev['description'] = isset($input['description']) ? htmlspecialchars($input['description']) : '';
                break;
            }
        }
        
        file_put_contents($json_file, json_encode($local_data, JSON_PRETTY_PRINT));
        echo json_encode(["success" => true]);
        exit;
    }

    // C) TERMIN LÖSCHEN
    if (isset($input['action']) && $input['action'] === 'delete') {
        $idToDelete = $input['id'];
        
        if (strpos($idToDelete, 'google_') === 0) {
            if (!in_array($idToDelete, $blacklist)) {
                $blacklist[] = $idToDelete;
                file_put_contents($blacklist_file, json_encode($blacklist, JSON_PRETTY_PRINT));
            }
            echo json_encode(["success" => true, "isGoogle" => true]);
            exit;
        }
        
        $local_data = array_filter($local_data, function($ev) use ($idToDelete) {
            return $ev['id'] != $idToDelete;
        });
        $local_data = array_values($local_data);
        file_put_contents($json_file, json_encode($local_data, JSON_PRETTY_PRINT));
        echo json_encode(["success" => true]);
        exit;
    }
}
?>