<?php
/**
 * Event add/edit form
 */

$isEdit = ($action === 'edit' && $id);
$event = null;
$errors = [];

// Phase 6: ensure reminder columns exist
try {
    $pdo->query("SELECT reminder_enabled FROM events LIMIT 1");
} catch (PDOException $e) {
    if (strpos($e->getMessage(), 'Unknown column') !== false) {
        $pdo->exec("ALTER TABLE events ADD COLUMN reminder_enabled TINYINT(1) DEFAULT 0");
        $pdo->exec("ALTER TABLE events ADD COLUMN reminder_when ENUM('day_before', 'morning_of') DEFAULT 'day_before'");
        $pdo->exec("ALTER TABLE events ADD COLUMN reminder_recipient_type ENUM('all', 'groups') DEFAULT 'all'");
        $pdo->exec("ALTER TABLE events ADD COLUMN reminder_group_ids TEXT NULL");
        $pdo->exec("ALTER TABLE events ADD COLUMN reminder_sent_at DATETIME NULL");
    }
}

if ($isEdit) {
    $stmt = $pdo->prepare('SELECT * FROM events WHERE id = ?');
    $stmt->execute([$id]);
    $event = $stmt->fetch();
    if (!$event) {
        header('Location: ' . BASE_PATH . '/events');
        exit;
    }
}

// Load groups for recipient selection
$groups = [];
try {
    $groups = $pdo->query('SELECT id, name FROM `groups` ORDER BY name')->fetchAll();
} catch (PDOException $e) {
    // groups table may not exist
}

// Load event types
$eventTypes = [];
$hasEventTypeColumn = false;
try {
    $pdo->query("SELECT event_type_id FROM events LIMIT 1");
    $hasEventTypeColumn = true;
} catch (PDOException $e) {
    // event_type_id column may not exist yet
}
try {
    $eventTypes = $pdo->query('SELECT id, name, color FROM event_types ORDER BY display_order, name')->fetchAll();
} catch (PDOException $e) {
    // event_types may not exist
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $event_date = trim($_POST['event_date'] ?? '');
    $event_time = trim($_POST['event_time'] ?? '') ?: null;
    $location = trim($_POST['location'] ?? '');
    $reminderEnabled = !empty($_POST['reminder_enabled']);
    $reminderWhen = in_array($_POST['reminder_when'] ?? '', ['day_before', 'morning_of']) ? $_POST['reminder_when'] : 'day_before';
    $reminderRecipientType = in_array($_POST['reminder_recipient_type'] ?? '', ['all', 'groups']) ? $_POST['reminder_recipient_type'] : 'all';
    $reminderGroupIds = $reminderRecipientType === 'groups' && !empty($_POST['reminder_group_ids']) ? json_encode(array_map('intval', $_POST['reminder_group_ids'])) : null;
    $eventTypeId = !empty($_POST['event_type_id']) ? (int) $_POST['event_type_id'] : null;

    if (empty($title)) $errors[] = 'Title is required.';
    if (empty($event_date)) $errors[] = 'Date is required.';

    if (empty($errors)) {
        if ($isEdit) {
            if ($hasEventTypeColumn) {
                $stmt = $pdo->prepare('UPDATE events SET title=?, description=?, event_date=?, event_time=?, location=?, event_type_id=?, reminder_enabled=?, reminder_when=?, reminder_recipient_type=?, reminder_group_ids=?, reminder_sent_at=NULL WHERE id=?');
                $stmt->execute([$title, $description, $event_date, $event_time, $location, $eventTypeId ?: null, $reminderEnabled ? 1 : 0, $reminderWhen, $reminderRecipientType, $reminderGroupIds, $id]);
            } else {
                $stmt = $pdo->prepare('UPDATE events SET title=?, description=?, event_date=?, event_time=?, location=?, reminder_enabled=?, reminder_when=?, reminder_recipient_type=?, reminder_group_ids=?, reminder_sent_at=NULL WHERE id=?');
                $stmt->execute([$title, $description, $event_date, $event_time, $location, $reminderEnabled ? 1 : 0, $reminderWhen, $reminderRecipientType, $reminderGroupIds, $id]);
            }
        } else {
            if ($hasEventTypeColumn) {
                $stmt = $pdo->prepare('INSERT INTO events (title, description, event_date, event_time, location, event_type_id, reminder_enabled, reminder_when, reminder_recipient_type, reminder_group_ids) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
                $stmt->execute([$title, $description, $event_date, $event_time, $location, $eventTypeId ?: null, $reminderEnabled ? 1 : 0, $reminderWhen, $reminderRecipientType, $reminderGroupIds]);
            } else {
                $stmt = $pdo->prepare('INSERT INTO events (title, description, event_date, event_time, location, reminder_enabled, reminder_when, reminder_recipient_type, reminder_group_ids) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
                $stmt->execute([$title, $description, $event_date, $event_time, $location, $reminderEnabled ? 1 : 0, $reminderWhen, $reminderRecipientType, $reminderGroupIds]);
            }
        }
        $returnMonth = trim($_POST['return_month'] ?? '');
        if (preg_match('/^\d{4}-\d{2}$/', $returnMonth)) {
            header('Location: ' . BASE_PATH . '/events?month=' . $returnMonth . '&toast=' . urlencode('Event saved successfully.'));
        } else {
            header('Location: ' . BASE_PATH . '/events?toast=' . urlencode('Event saved successfully.'));
        }
        exit;
    }

    $event = [
        'title' => $title,
        'description' => $description,
        'event_date' => $event_date,
        'event_time' => $event_time,
        'location' => $location,
        'event_type_id' => $eventTypeId,
        'reminder_enabled' => $reminderEnabled ? 1 : 0,
        'reminder_when' => $reminderWhen,
        'reminder_recipient_type' => $reminderRecipientType,
        'reminder_group_ids' => $reminderGroupIds,
    ];
}

$pageTitle = $isEdit ? 'Edit Event' : 'Add Event';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="header">
    <h1><?= $isEdit ? 'Edit Event' : 'Add Event' ?></h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/events">Back to Events</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<?php if (!empty($errors)): ?>
    <div data-toast="error" data-toast-msg="<?= htmlspecialchars(implode(' ', $errors)) ?>" style="display:none"></div>
<?php endif; ?>

<div class="card">
    <form method="post">
        <div class="form-group">
            <label for="title">Title *</label>
            <input type="text" id="title" name="title" required
                value="<?= htmlspecialchars($event['title'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label for="description">Description</label>
            <textarea id="description" name="description"><?= htmlspecialchars($event['description'] ?? '') ?></textarea>
        </div>
        <div class="form-group">
            <label for="event_date">Date *</label>
            <input type="date" id="event_date" name="event_date" required
                value="<?= htmlspecialchars($event['event_date'] ?? date('Y-m-d')) ?>">
        </div>
        <div class="form-group">
            <label for="event_time">Time</label>
            <input type="time" id="event_time" name="event_time"
                value="<?= htmlspecialchars($event['event_time'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label for="location">Location</label>
            <input type="text" id="location" name="location"
                value="<?= htmlspecialchars($event['location'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label for="event_type_id">Event type</label>
            <select id="event_type_id" name="event_type_id">
                <option value="">— None —</option>
                <?php foreach ($eventTypes as $et): ?>
                <option value="<?= (int) $et['id'] ?>" <?= (isset($event['event_type_id']) && (int)$event['event_type_id'] === (int)$et['id']) ? 'selected' : '' ?>><?= htmlspecialchars($et['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <div style="margin-top: 1.5rem; padding-top: 1.5rem; border-top: 1px solid #e2e8f0;">
            <h3 style="font-size: 1rem; margin: 0 0 1rem 0;">Reminder settings</h3>
            <div class="form-group checkbox-row">
                <label>
                    <input type="checkbox" id="reminder_enabled" name="reminder_enabled" value="1" <?= !empty($event['reminder_enabled']) ? 'checked' : '' ?> onchange="document.getElementById('reminder-options').style.display = this.checked ? 'block' : 'none';">
                    Send reminder to members
                </label>
            </div>
            <div id="reminder-options" style="display: <?= !empty($event['reminder_enabled']) ? 'block' : 'none' ?>; margin-top: 1rem;">
                <div class="form-group">
                    <label for="reminder_when">When to send</label>
                    <select id="reminder_when" name="reminder_when">
                        <option value="day_before" <?= ($event['reminder_when'] ?? 'day_before') === 'day_before' ? 'selected' : '' ?>>1 day before event</option>
                        <option value="morning_of" <?= ($event['reminder_when'] ?? '') === 'morning_of' ? 'selected' : '' ?>>Morning of event (9:00 AM)</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="reminder_recipient_type">Recipients</label>
                    <select id="reminder_recipient_type" name="reminder_recipient_type" onchange="document.getElementById('reminder-groups').style.display = this.value === 'groups' ? 'block' : 'none';">
                        <option value="all" <?= ($event['reminder_recipient_type'] ?? 'all') === 'all' ? 'selected' : '' ?>>All members</option>
                        <option value="groups" <?= ($event['reminder_recipient_type'] ?? '') === 'groups' ? 'selected' : '' ?>>Selected groups</option>
                    </select>
                </div>
                <div id="reminder-groups" class="form-group" style="display: <?= ($event['reminder_recipient_type'] ?? 'all') === 'groups' ? 'block' : 'none' ?>;">
                    <label>Select groups</label>
                    <?php
                    $selectedGroupIds = [];
                    if (!empty($event['reminder_group_ids'])) {
                        $selectedGroupIds = json_decode($event['reminder_group_ids'], true) ?: [];
                    }
                    ?>
                    <?php if (empty($groups)): ?>
                    <p class="text-muted" style="font-size: 0.875rem;">No groups available. <a href="<?= BASE_PATH ?>/groups">Create groups</a> first.</p>
                    <?php else: ?>
                    <div style="display: flex; flex-direction: column; gap: 0.5rem; max-height: 200px; overflow-y: auto; padding: 0.5rem; border: 1px solid #e2e8f0; border-radius: 4px;">
                        <?php foreach ($groups as $g): ?>
                        <label style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer;">
                            <input type="checkbox" name="reminder_group_ids[]" value="<?= (int) $g['id'] ?>" <?= in_array((int) $g['id'], $selectedGroupIds) ? 'checked' : '' ?>>
                            <span><?= htmlspecialchars($g['name']) ?></span>
                        </label>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <button type="submit" class="btn"><?= $isEdit ? 'Update' : 'Add' ?> Event</button>
        <a href="<?= BASE_PATH ?>/events" class="btn btn-secondary">Cancel</a>
    </form>
</div>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
