<?php
session_start();

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

require_once 'db/config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'] ?? '';
    $description = $_POST['description'] ?? '';
    $start_datetime = $_POST['start_datetime'] ?? '';
    $end_datetime = $_POST['end_datetime'] ?? '';
    $event_type_id = $_POST['event_type_id'] ?? null;
    $recurrence = $_POST['recurrence'] ?? '';
    $recurrence_end_date = $_POST['recurrence_end_date'] ?? '';

    if (empty($recurrence)) {
        $recurrence = null;
    }
    if (empty($recurrence_end_date)) {
        $recurrence_end_date = null;
    }

    if (empty($title) || empty($start_datetime) || empty($end_datetime) || empty($event_type_id)) {
        header("Location: calendar.php?error=empty_fields");
        exit();
    }

    $pdo = db();
    
    try {
        $pdo->beginTransaction();

        // Insert the main event
        $stmt = $pdo->prepare("INSERT INTO calendar_events (title, description, start_datetime, end_datetime, event_type_id, recurrence, recurrence_end_date) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$title, $description, $start_datetime, $end_datetime, $event_type_id, $recurrence, $recurrence_end_date]);
        $parent_event_id = $pdo->lastInsertId();

        // Handle group associations
        if (isset($_POST['group_ids']) && is_array($_POST['group_ids'])) {
            $stmt_groups = $pdo->prepare("INSERT INTO calendar_event_groups (calendar_event_id, bni_group_id) VALUES (?, ?)");
            foreach ($_POST['group_ids'] as $group_id) {
                $stmt_groups->execute([$parent_event_id, $group_id]);
            }
        } else {
            // The field is required, so this is a failure case.
            throw new Exception("Group IDs are required.");
        }

        if ($recurrence && !empty($recurrence_end_date)) {
            $start_date = new DateTime($start_datetime);
            $end_date = new DateTime($end_datetime);
            $recurrence_end = new DateTime($recurrence_end_date);
            $interval_spec = '';

            switch ($recurrence) {
                case 'daily':
                    $interval_spec = 'P1D';
                    break;
                case 'weekly':
                    $interval_spec = 'P1W';
                    break;
                case 'monthly':
                    $interval_spec = 'P1M';
                    break;
            }

            if ($interval_spec) {
                $interval = new DateInterval($interval_spec);
                $period_start = clone $start_date;
                $period_start->add($interval);
 
                $period = new DatePeriod($period_start, $interval, $recurrence_end);

                $stmt_recur = $pdo->prepare("INSERT INTO calendar_events (title, description, start_datetime, end_datetime, event_type_id, parent_event_id) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt_recur_groups = $pdo->prepare("INSERT INTO calendar_event_groups (calendar_event_id, bni_group_id) VALUES (?, ?)");

                foreach ($period as $date) {
                    $new_start_datetime = $date->format('Y-m-d H:i:s');
                    $end_date_clone = clone $date;
                    $new_end_datetime = $end_date_clone->add($start_date->diff($end_date))->format('Y-m-d H:i:s');
                    $stmt_recur->execute([$title, $description, $new_start_datetime, $new_end_datetime, $event_type_id, $parent_event_id]);
                    $new_event_id = $pdo->lastInsertId();
                    foreach ($_POST['group_ids'] as $group_id) {
                        $stmt_recur_groups->execute([$new_event_id, $group_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();
    }
}
