<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<div class="container-fluid py-4">

    <div class="d-flex align-items-center gap-2 mb-4">
        <a href="/exam-event" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-arrow-left"></i>
        </a>
        <div>
            <h4 class="mb-0 fw-bold">Jadwal Asesmen</h4>
            <small class="text-muted">Kelola jadwal ujian untuk dicetak di kartu peserta: <strong><?= esc($event['name']) ?></strong></small>
        </div>
    </div>

    <?php if (session()->getFlashdata('success')): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <?= session()->getFlashdata('success') ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if (session()->getFlashdata('error')): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <?= session()->getFlashdata('error') ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if (session()->getFlashdata('errors')): ?>
        <div class="alert alert-danger">
            <ul class="mb-0">
                <?php foreach (session()->getFlashdata('errors') as $err): ?>
                    <li><?= esc($err) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <div class="row g-4">
        <!-- Kolom Kiri: Tabel Jadwal -->
        <div class="col-lg-8">
            <div class="card shadow-sm border-0">
                <div class="card-header fw-semibold bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <span><i class="bi bi-calendar3 me-2 text-primary"></i>Daftar Hari & Mapel Ujian</span>
                    <?php if (!$event['is_locked'] && !empty($otherEvents)): ?>
                        <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#copyScheduleModal">
                            <i class="bi bi-copy me-1"></i> Salin Jadwal
                        </button>
                    <?php endif; ?>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th class="ps-3" width="8%">#</th>
                                    <th width="32%">Hari & Tanggal</th>
                                    <th width="45%">Daftar Mata Pelajaran</th>
                                    <th class="text-center" width="15%">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($schedules)): ?>
                                    <tr>
                                        <td colspan="4" class="text-center py-5 text-muted">
                                            <i class="bi bi-calendar-x fs-3 d-block mb-2"></i>
                                            Belum ada jadwal asesmen yang ditambahkan
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php $no = 1; foreach ($schedules as $s): 
                                        $subjects = json_decode($s['subject_list'], true) ?: [];
                                    ?>
                                    <tr>
                                        <td class="ps-3"><?= $no++ ?></td>
                                        <td>
                                            <div class="fw-bold text-dark"><?= esc($s['exam_day']) ?></div>
                                            <small class="text-muted"><?= date('d F Y', strtotime($s['exam_date'])) ?></small>
                                        </td>
                                        <td>
                                            <ul class="mb-0 ps-3">
                                                <?php foreach ($subjects as $sub): 
                                                    if (is_array($sub)) {
                                                        $subName = $sub['name'] ?? '';
                                                        $subTime = $sub['time'] ?? '';
                                                    } else {
                                                        $subName = $sub;
                                                        $subTime = '';
                                                    }
                                                ?>
                                                    <li class="mb-1">
                                                        <span><?= esc($subName) ?></span>
                                                        <?php if (!empty($subTime)): ?>
                                                            <span class="badge bg-secondary-subtle text-secondary ms-1 fw-normal"><?= esc($subTime) ?></span>
                                                        <?php endif; ?>
                                                    </li>
                                                <?php endforeach; ?>
                                            </ul>
                                        </td>
                                        <td class="text-center">
                                            <div class="d-flex gap-1 justify-content-center">
                                                <button type="button" 
                                                        class="btn btn-sm btn-outline-warning <?= $event['is_locked'] ? 'disabled' : '' ?>" 
                                                        title="Edit Jadwal"
                                                        data-bs-toggle="modal" 
                                                        data-bs-target="#editScheduleModal_<?= $s['id'] ?>">
                                                    <i class="bi bi-pencil"></i>
                                                </button>
                                                <a href="/exam-event/schedule/delete/<?= $s['id'] ?>" 
                                                   class="btn btn-sm btn-outline-danger <?= $event['is_locked'] ? 'disabled' : '' ?>" 
                                                   title="Hapus Jadwal" 
                                                   onclick="return confirm('Yakin hapus jadwal hari ini?')">
                                                    <i class="bi bi-trash"></i>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Kolom Kanan: Form Tambah -->
        <div class="col-lg-4">
            <div class="card shadow-sm border-0">
                <div class="card-header fw-semibold bg-white border-bottom py-3">
                    <i class="bi bi-plus-circle me-2 text-success"></i>Tambah Jadwal Asesmen
                </div>
                <div class="card-body p-4">
                    <?php if ($event['is_locked']): ?>
                        <div class="alert alert-warning mb-0">
                            <i class="bi bi-lock-fill me-1"></i>
                            Event ini telah <strong>dikunci</strong>. Anda tidak dapat menambah atau mengubah jadwal asesmen saat ini.
                        </div>
                    <?php else: ?>
                        <form action="/exam-event/<?= $event['id'] ?>/schedule/store" method="POST">
                            <?= csrf_field() ?>
                            <div class="mb-3">
                                <label class="form-label fw-bold">Tanggal Ujian <span class="text-danger">*</span></label>
                                <input type="date" name="exam_date" id="exam_date" class="form-control" value="<?= old('exam_date') ?>" onchange="updateDayName(this.value)" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label fw-bold">Nama Hari <span class="text-danger">*</span></label>
                                <input type="text" name="exam_day" id="exam_day" class="form-control" placeholder="misal: Senin, Selasa..." value="<?= old('exam_day') ?>" required>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label fw-bold">Mata Pelajaran & Waktu <span class="text-danger">*</span></label>
                                <div id="add-subjects-container">
                                    <div class="subject-row row g-2 mb-2">
                                        <div class="col-7">
                                            <input type="text" name="subjects[0][name]" class="form-control form-control-sm" placeholder="Contoh: 1. Bahasa Indonesia" required>
                                        </div>
                                        <div class="col-4">
                                            <input type="text" name="subjects[0][time]" class="form-control form-control-sm" placeholder="Contoh: 07.00 - 09.30" required>
                                        </div>
                                        <div class="col-1 text-end">
                                            <button type="button" class="btn btn-sm btn-outline-danger remove-subject-btn" disabled onclick="removeSubjectRow(this)">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-success mt-2" id="add-subject-row-btn">
                                    <i class="bi bi-plus-lg me-1"></i> Tambah Mapel
                                </button>
                                <div class="form-text mt-2">Gunakan penomoran pada mata pelajaran agar tampil rapi dan berurutan pada kartu peserta.</div>
                            </div>
                            
                            <div class="d-grid mt-4">
                                <button type="submit" class="btn btn-success"><i class="bi bi-plus-lg me-1"></i>Tambah Jadwal</button>
                            </div>
                        </form>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Edit Schedule Modals -->
<?php if (!empty($schedules)): ?>
    <?php foreach ($schedules as $s): 
        $subjects = json_decode($s['subject_list'], true) ?: [];
    ?>
    <div class="modal fade" id="editScheduleModal_<?= $s['id'] ?>" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form action="/exam-event/schedule/update/<?= $s['id'] ?>" method="POST">
                    <?= csrf_field() ?>
                    <div class="modal-header">
                        <h5 class="modal-title"><i class="bi bi-pencil-square me-2 text-warning"></i>Edit Jadwal Asesmen</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Tanggal Ujian <span class="text-danger">*</span></label>
                                <input type="date" name="exam_date" class="form-control" value="<?= esc($s['exam_date']) ?>" onchange="updateEditDayName(this, 'exam_day_<?= $s['id'] ?>')" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Nama Hari <span class="text-danger">*</span></label>
                                <input type="text" name="exam_day" id="exam_day_<?= $s['id'] ?>" class="form-control" value="<?= esc($s['exam_day']) ?>" required>
                            </div>
                        </div>
                        
                        <div class="mb-2">
                            <label class="form-label fw-bold">Daftar Mata Pelajaran & Waktu <span class="text-danger">*</span></label>
                            <div class="edit-subjects-container" id="edit-subjects-container-<?= $s['id'] ?>">
                                <?php if (empty($subjects)): ?>
                                    <div class="subject-row row g-2 mb-2">
                                        <div class="col-7">
                                            <input type="text" name="subjects[0][name]" class="form-control form-control-sm" placeholder="Contoh: 1. Bahasa Indonesia" required>
                                        </div>
                                        <div class="col-4">
                                            <input type="text" name="subjects[0][time]" class="form-control form-control-sm" placeholder="Contoh: 07.00 - 09.30" required>
                                        </div>
                                        <div class="col-1 text-end">
                                            <button type="button" class="btn btn-sm btn-outline-danger remove-subject-btn" disabled onclick="removeSubjectRow(this)">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </div>
                                    </div>
                                <?php else: ?>
                                    <?php foreach ($subjects as $idx => $sub): 
                                        if (is_array($sub)) {
                                            $subName = $sub['name'] ?? '';
                                            $subTime = $sub['time'] ?? '';
                                        } else {
                                            $subName = $sub;
                                            $subTime = '';
                                        }
                                    ?>
                                        <div class="subject-row row g-2 mb-2">
                                            <div class="col-7">
                                                <input type="text" name="subjects[<?= $idx ?>][name]" class="form-control form-control-sm" placeholder="Contoh: 1. Bahasa Indonesia" value="<?= esc($subName) ?>" required>
                                            </div>
                                            <div class="col-4">
                                                <input type="text" name="subjects[<?= $idx ?>][time]" class="form-control form-control-sm" placeholder="Contoh: 07.00 - 09.30" value="<?= esc($subTime) ?>" required>
                                            </div>
                                            <div class="col-1 text-end">
                                                <button type="button" class="btn btn-sm btn-outline-danger remove-subject-btn" onclick="removeSubjectRow(this)">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                            
                            <button type="button" class="btn btn-sm btn-outline-success mt-2" onclick="addEditSubjectRow('<?= $s['id'] ?>')">
                                <i class="bi bi-plus-lg me-1"></i> Tambah Mapel
                            </button>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-warning"><i class="bi bi-save me-1"></i>Simpan Perubahan</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
<?php endif; ?>

<!-- Modal Salin dari Event Lain -->
<?php if (!empty($otherEvents) && !$event['is_locked']): ?>
<div class="modal fade" id="copyScheduleModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form action="/exam-event/<?= $event['id'] ?>/schedule/copy-from-event" method="POST">
            <?= csrf_field() ?>
            <div class="modal-content border-0 shadow">
                <div class="modal-header bg-primary-subtle py-3">
                    <h5 class="modal-title fw-bold text-dark"><i class="bi bi-copy me-2"></i>Salin Jadwal dari Event Lain</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label class="form-label fw-bold">Pilih Event Asal <span class="text-danger">*</span></label>
                        <select name="from_event_id" class="form-select" required>
                            <option value="">-- Pilih Event --</option>
                            <?php foreach ($otherEvents as $oe): ?>
                                <option value="<?= $oe['id'] ?>"><?= esc($oe['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <div class="form-text text-muted mt-2">
                            Semua jadwal dari event asal akan disalin ke event ini (jadwal dengan tanggal yang sama akan dilewati).
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-top-0">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-copy me-1"></i>Salin Jadwal</button>
                </div>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<script>
function updateDayName(dateString) {
    if (!dateString) return;
    const date = new Date(dateString);
    const options = { weekday: 'long' };
    const formatter = new Intl.DateTimeFormat('id-ID', options);
    document.getElementById('exam_day').value = formatter.format(date);
}

document.getElementById('add-subject-row-btn')?.addEventListener('click', function() {
    const container = document.getElementById('add-subjects-container');
    const rowCount = container.getElementsByClassName('subject-row').length;
    const newRow = document.createElement('div');
    newRow.className = 'subject-row row g-2 mb-2';
    newRow.innerHTML = `
        <div class="col-7">
            <input type="text" name="subjects[${rowCount}][name]" class="form-control form-control-sm" placeholder="Contoh: 1. Bahasa Indonesia" required>
        </div>
        <div class="col-4">
            <input type="text" name="subjects[${rowCount}][time]" class="form-control form-control-sm" placeholder="Contoh: 07.00 - 09.30" required>
        </div>
        <div class="col-1 text-end">
            <button type="button" class="btn btn-sm btn-outline-danger remove-subject-btn" onclick="removeSubjectRow(this)">
                <i class="bi bi-trash"></i>
            </button>
        </div>
    `;
    container.appendChild(newRow);
    updateRemoveButtons(container);
});

function removeSubjectRow(button) {
    const row = button.closest('.subject-row');
    const container = row.parentNode;
    row.remove();
    updateRemoveButtons(container);
    reindexRows(container);
}

function updateRemoveButtons(container) {
    const rows = container.getElementsByClassName('subject-row');
    if (rows.length === 1) {
        const btn = rows[0].querySelector('.remove-subject-btn');
        if (btn) btn.disabled = true;
    } else {
        for (let i = 0; i < rows.length; i++) {
            const btn = rows[i].querySelector('.remove-subject-btn');
            if (btn) btn.disabled = false;
        }
    }
}

function reindexRows(container) {
    const rows = container.getElementsByClassName('subject-row');
    for (let i = 0; i < rows.length; i++) {
        const inputs = rows[i].getElementsByTagName('input');
        if (inputs.length >= 2) {
            inputs[0].name = `subjects[${i}][name]`;
            inputs[1].name = `subjects[${i}][time]`;
        }
    }
}

function addEditSubjectRow(scheduleId) {
    const container = document.getElementById(`edit-subjects-container-${scheduleId}`);
    const rowCount = container.getElementsByClassName('subject-row').length;
    const newRow = document.createElement('div');
    newRow.className = 'subject-row row g-2 mb-2';
    newRow.innerHTML = `
        <div class="col-7">
            <input type="text" name="subjects[${rowCount}][name]" class="form-control form-control-sm" placeholder="Contoh: 1. Bahasa Indonesia" required>
        </div>
        <div class="col-4">
            <input type="text" name="subjects[${rowCount}][time]" class="form-control form-control-sm" placeholder="Contoh: 07.00 - 09.30" required>
        </div>
        <div class="col-1 text-end">
            <button type="button" class="btn btn-sm btn-outline-danger remove-subject-btn" onclick="removeSubjectRow(this)">
                <i class="bi bi-trash"></i>
            </button>
        </div>
    `;
    container.appendChild(newRow);
    updateRemoveButtons(container);
}

function updateEditDayName(input, targetId) {
    if (!input.value) return;
    const date = new Date(input.value);
    const options = { weekday: 'long' };
    const formatter = new Intl.DateTimeFormat('id-ID', options);
    const targetEl = document.getElementById(targetId);
    if (targetEl) {
        targetEl.value = formatter.format(date);
    }
}

// Initial setup of remove buttons on load
document.addEventListener('DOMContentLoaded', function() {
    const addContainer = document.getElementById('add-subjects-container');
    if (addContainer) {
        updateRemoveButtons(addContainer);
    }
    document.querySelectorAll('.edit-subjects-container').forEach(container => {
        updateRemoveButtons(container);
    });
});
</script>

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