<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>

<div class="container mt-4">
    <h2>Edit Event</h2>

    <?php
    $defaultCategories = ['Fun Event-1', 'Fun Event-2', 'Fun Event-3'];
    $existingCategories = array_map('strval', $categories ?? []);
    $allCategories = array_unique(array_merge($defaultCategories, $existingCategories));
    ?>

    <?php if (session()->getFlashdata('error')): ?>
        <div class="alert alert-danger"><?= session()->getFlashdata('error') ?></div>
    <?php endif; ?>
    <?php if (session()->getFlashdata('success')): ?>
        <div class="alert alert-success"><?= session()->getFlashdata('success') ?></div>
    <?php endif; ?>

   <form method="post" action="<?= site_url('administrator/events/edit/' . $event['id']) ?>" enctype="multipart/form-data">

        <?= csrf_field() ?>
        <div class="mb-3">
            <label class="form-label">Event Name</label>
            <input type="text" name="event_name" class="form-control" value="<?= esc($event['event_name']) ?>" required>
        </div>

        <div class="mb-3">
            <label class="form-label">Category</label>
            <select name="event_category" class="form-control" required>
                <option value="" disabled <?= empty($event['event_category']) ? 'selected' : '' ?>>Select category</option>
                <?php foreach ($allCategories as $category): ?>
                    <option value="<?= esc($category) ?>" <?= (string)($event['event_category'] ?? '') === (string)$category ? 'selected' : '' ?>>
                        <?= esc(ucwords($category)) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="mb-3">
            <label class="form-label">Description</label>
            <textarea id="event_description" name="description" class="form-control"><?= esc($event['description']) ?></textarea>
        </div>

        <div class="mb-3">
            <label class="form-label">Amount</label>
            <input type="number" step="0.01" name="amount" class="form-control" value="<?= esc($event['amount']) ?>" required>
        </div>

        <div class="mb-3">
            <label class="form-label">Current Flyer</label><br>
            <?php if ($event['flyer']): ?>
                <img src="<?= base_url('uploads/' . ltrim((string) $event['flyer'], '/')) ?>" width="150" class="mb-2">
            <?php else: ?>
                <div class="text-muted">No flyer uploaded.</div>
            <?php endif; ?>
        </div>

        <div class="mb-3">
            <label class="form-label">New Flyer (optional)</label>
            <input type="file" name="flyer" class="form-control">
        </div>

        <div class="mb-3">
            <label class="form-label">Expiration Date</label>
            <input type="date" name="expiration_date" class="form-control" value="<?= esc($event['expiration_date']) ?>" required>
        </div>

        <div class="mb-3">
            <label class="form-label">Semester</label>
            <input type="text" name="semester" class="form-control" value="<?= esc($event['semester']) ?>" required>
        </div>

        <div class="mb-3">
            <label class="form-label">School Year</label>
            <input type="text" name="school_year" class="form-control" value="<?= esc($event['school_year']) ?>" required>
        </div>

        <div class="card mb-3">
            <div class="card-header">School Calendar</div>
            <div class="card-body">
                <div class="form-check mb-2">
                    <input class="form-check-input" type="checkbox" id="add_to_calendar" name="add_to_calendar" value="1">
                    <label class="form-check-label" for="add_to_calendar">
                        Add this event to the school calendar
                    </label>
                </div>

                <div id="calendar_recipients" class="ms-3" style="display:none;">
                    <div class="mb-2 fw-semibold">Visible On Calendars</div>
                    <div class="d-flex flex-wrap gap-3">
                        <label class="form-check-label">
                            <input class="form-check-input me-1" type="checkbox" name="notify_parent" value="1" checked>
                            Parents
                        </label>
                        <label class="form-check-label">
                            <input class="form-check-input me-1" type="checkbox" name="notify_teacher" value="1" checked>
                            Teachers
                        </label>
                        <label class="form-check-label">
                            <input class="form-check-input me-1" type="checkbox" name="notify_admin" value="1" checked>
                            Admins
                        </label>
                    </div>
                    <div class="form-text">If none are selected, the event is visible to everyone.</div>
                </div>
            </div>
        </div>

        <div class="card mb-3">
            <div class="card-header">Parent Email Broadcast</div>
            <div class="card-body">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="send_email_parent" name="send_email_parent" value="1">
                    <label class="form-check-label" for="send_email_parent">
                        Send one event email to all parents and add all parent emails in CC
                    </label>
                </div>
                <div class="form-text">Use this when you want to rebroadcast the updated event to all parents in a single email.</div>
            </div>
        </div>

        <button type="submit" class="btn btn-primary">Update Event</button>
        <a href="<?= site_url('administrator/events') ?>" class="btn btn-secondary">Cancel</a>
    </form>
</div>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script src="<?= base_url('assets/tinymce/tinymce.min.js') ?>"></script>
<script>
    (function () {
        const toggle = document.getElementById('add_to_calendar');
        const recipients = document.getElementById('calendar_recipients');
        const description = document.getElementById('event_description');

        if (toggle && recipients) {
            function sync() {
                recipients.style.display = toggle.checked ? '' : 'none';
            }
            toggle.addEventListener('change', sync);
            sync();
        }

        if (description && window.tinymce) {
            tinymce.init({
                selector: '#event_description',
                base_url: '<?= base_url('assets/tinymce') ?>',
                suffix: '.min',
                license_key: 'gpl',
                height: 320,
                menubar: true,
                branding: false,
                promotion: false,
                plugins: 'advlist autolink lists link charmap preview anchor searchreplace visualblocks code fullscreen insertdatetime table help wordcount',
                toolbar: 'undo redo | blocks | bold italic underline strikethrough forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link table | removeformat | preview code',
                convert_urls: false,
                content_style: 'body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif; font-size: 14px; }'
            });
        }
    })();
</script>
<?= $this->endSection() ?>
