<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

require_once 'db/config.php';

if (isset($_GET['id'])) {
    $event_id = $_GET['id'];
    $pdo = db();

    try {
        $pdo->beginTransaction();

        // Check if the event is a parent event
        $stmt = $pdo->prepare("SELECT parent_event_id FROM calendar_events WHERE id = ?");
        $stmt->execute([$event_id]);
        $event = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($event) {
            if ($event['parent_event_id'] === null) {
                // It's a parent event, delete it and all its children
                $stmt_delete_children = $pdo->prepare("DELETE FROM calendar_events WHERE parent_event_id = ?");
                $stmt_delete_children->execute([$event_id]);
            }

            // Delete the event itself
            $stmt_delete = $pdo->prepare("DELETE FROM calendar_events WHERE id = ?");
            $stmt_delete->execute([$event_id]);
        }

        $pdo->commit();
        header("Location: calendar.php");
        exit();

    } catch (Exception $e) {
        $pdo->rollBack();
        error_log($e->getMessage());
        header("Location: calendar.php?error=db_error");
        exit();
    }
} else {
    header("Location: calendar.php");
    exit();
}
