<?php
session_start();
require_once 'db/config.php';
require_once 'lib/ErrorHandler.php';
require_once 'lib/WorkflowExceptions.php';

if (!isset($_SESSION['user_id'])) {
    throw new WorkflowNotAllowedException('Authentication required.');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $event_id = $_POST['event_id'] ?? null;
    $title = $_POST['title'] ?? '';
    $description = $_POST['description'] ?? '';
    $start_datetime = $_POST['start_datetime'] ?? '';
    $end_datetime = $_POST['end_datetime'] ?? '';
    $event_type_id = $_POST['event_type_id'] ?? null;
    $update_scope = $_POST['update_scope'] ?? 'one';
    $group_ids = $_POST['group_ids'] ?? [];

    if (empty($event_id) || empty($title) || empty($event_type_id) || !is_array($group_ids)) {
        throw new WorkflowRuleFailedException('Empty fields');
    }

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

        $event_ids_to_update = [];

        if ($update_scope === 'all') {
            // Find the parent event id
            $stmt = $pdo->prepare("SELECT parent_event_id, recurrence FROM calendar_events WHERE id = ?");
            $stmt->execute([$event_id]);
            $event = $stmt->fetch();

            $parent_event_id = $event['parent_event_id'] ?? $event_id;
            
            // Get all event ids in the series
            $stmt = $pdo->prepare("SELECT id FROM calendar_events WHERE id = ? OR parent_event_id = ?");
            $stmt->execute([$parent_event_id, $parent_event_id]);
            $event_ids_to_update = $stmt->fetchAll(PDO::FETCH_COLUMN);
        } else {
            $event_ids_to_update[] = $event_id;
        }
        
        // Prepare statements
        $stmt_update_event = $pdo->prepare("UPDATE calendar_events SET title = ?, description = ?, event_type_id = ? WHERE id = ?");
        if($update_scope === 'one'){
             $stmt_update_event = $pdo->prepare("UPDATE calendar_events SET title = ?, description = ?, start_datetime = ?, end_datetime = ?, event_type_id = ? WHERE id = ?");
        }

        $stmt_delete_groups = $pdo->prepare("DELETE FROM calendar_event_groups WHERE calendar_event_id = ?");
        $stmt_add_groups = $pdo->prepare("INSERT INTO calendar_event_groups (calendar_event_id, bni_group_id) VALUES (?, ?)");

        foreach ($event_ids_to_update as $id) {
            // Update event details
             if($update_scope === 'one'){
                $stmt_update_event->execute([$title, $description, $start_datetime, $end_datetime, $event_type_id, $id]);
             } else {
                $stmt_update_event->execute([$title, $description, $event_type_id, $id]);
             }

            // Update group associations
            $stmt_delete_groups->execute([$id]);
            foreach ($group_ids as $group_id) {
                $stmt_add_groups->execute([$id, $group_id]);
            }
        }

        $pdo->commit();

        header("Location: calendar.php");
        exit();
    } catch (Exception $e) {
        $pdo->rollBack();
        error_log("Error updating event: " . $e->getMessage());
        throw $e;
    }
}
