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


<style>
/* Custom Styles for classroom grid cards */
.classroom-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
    gap: 8px;
}

.classroom-card {
    border: 1.5px solid #dee2e6;
    border-radius: 8px;
    padding: 10px;
    cursor: pointer;
    transition: all 0.2s ease-in-out;
    background-color: #fff;
    user-select: none;
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    min-height: 65px;
}

.classroom-card:hover {
    border-color: #0d6efd;
    box-shadow: 0 4px 8px rgba(13, 110, 253, 0.1);
    transform: translateY(-1px);
}

/* State: Checked / Selected Current */
.classroom-card-input:checked + .classroom-card {
    border-color: #0d6efd;
    background-color: #ecf3fe;
    box-shadow: 0 4px 12px rgba(13, 110, 253, 0.15);
}

.classroom-card-input:checked + .classroom-card .check-icon {
    opacity: 1;
    transform: scale(1);
}

.classroom-card .check-icon {
    position: absolute;
    top: 6px;
    right: 8px;
    color: #0d6efd;
    font-size: 1.1rem;
    opacity: 0;
    transform: scale(0.5);
    transition: all 0.2s cubic-bezier(0.34, 1.56, 0.64, 1);
}

/* State: Assigned to Other Teacher */
.classroom-card-input:disabled + .classroom-card {
    background-color: #f8f9fa;
    border-color: #e9ecef;
    cursor: not-allowed;
    opacity: 0.75;
}

.classroom-card-input:disabled + .classroom-card:hover {
    border-color: #e9ecef;
    box-shadow: none;
    transform: none;
}

.classroom-card-input:disabled + .classroom-card .class-name {
    color: #6c757d;
}

.classroom-card .teacher-label {
    font-size: 10px;
    color: #6c757d;
    margin-top: 4px;
    font-weight: 500;
}

.hover-badge {
    transition: all 0.2s ease;
    border-radius: 6px;
    padding: 6px 10px;
}
.hover-badge:hover {
    background-color: #f8d7da !important;
    border-color: #f5c2c7 !important;
    color: #842029 !important;
}

/* Smooth card active highlight */
.card-active-highlight {
    transition: border-color 0.5s ease, box-shadow 0.5s ease;
}
</style>

<div class="row">
    <div class="col-md-5">
        <div class="card card-active-highlight">
            <div class="card-header">
                <div class="d-flex align-items-center gap-2 py-1">
                    <i class="bi bi-person-badge text-primary fs-5"></i>
                    <span class="fw-semibold">Tambah / Edit Assignment BK</span>
                </div>
            </div>
            <div class="card-body">
                <?php if (session()->getFlashdata('error')): ?>
                <div class="alert alert-danger alert-dismissible fade show py-2 small" role="alert">
                    <i class="bi bi-exclamation-circle me-1"></i><?= session()->getFlashdata('error') ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>

                <?php if (session()->getFlashdata('success')): ?>
                <div class="alert alert-success alert-dismissible fade show py-2 small" role="alert">
                    <i class="bi bi-check-circle me-1"></i><?= session()->getFlashdata('success') ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>

                <form action="/bk-assignment/save" method="post" id="formAssignment">
                    <?= csrf_field() ?>
                    
                    <div class="mb-3">
                        <label class="form-label fw-medium small">Periode Akademik</label>
                        <select name="academic_period_id" id="period_id" class="form-select select2-simple" required>
                            <option value="">-- Pilih Periode --</option>
                            <?php foreach ($periods as $p): ?>
                            <option value="<?= $p['id'] ?>" <?= ($activePeriod && $activePeriod['id'] == $p['id']) ? 'selected' : '' ?>>
                                <?= esc($p['year_name']) ?> - <?= esc($p['semester']) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-medium small">Pilih Guru BK <span class="text-danger">*</span></label>
                        <select name="teacher_id" id="teacher_id" class="form-select select2-teacher" required>
                            <option value="">-- Pilih Guru --</option>
                            <?php foreach ($teachers as $t): ?>
                            <option value="<?= $t['id'] ?>"><?= esc($t['name']) ?> (<?= esc($t['nip'] ?? '-') ?>)</option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-medium small d-flex justify-content-between">
                            <span>Kelas yang Diampu</span>
                            <span class="text-muted small fw-normal" id="selected-counter">0 kelas terpilih</span>
                        </label>
                        
                        <div class="border rounded p-3 bg-light" style="max-height: 400px; overflow-y: auto;">
                            <?php if (empty($groupedClassrooms)): ?>
                                <div class="text-center py-4">
                                    <p class="text-muted small mb-0">Belum ada data kelas</p>
                                </div>
                            <?php else: ?>
                                <?php foreach ($groupedClassrooms as $gradeName => $classrooms): ?>
                                    <div class="mb-3">
                                        <div class="fw-bold small text-primary mb-2 border-bottom pb-1" style="font-size: 11px; letter-spacing: 0.5px;">
                                            Tingkat <?= esc($gradeName) ?>
                                        </div>
                                        <div class="classroom-grid">
                                            <?php foreach ($classrooms as $c): ?>
                                                <?php 
                                                    $assignment = $assignedMap[$c['id']] ?? null;
                                                    $isDisabled = ($assignment !== null);
                                                    $labelClass = $isDisabled ? 'text-danger' : 'text-muted';
                                                    $labelText = $isDisabled ? 'BK: ' . esc($assignment['teacher_name']) : 'Belum diampu';
                                                ?>
                                                <label class="w-100 mb-0">
                                                    <input type="checkbox" 
                                                        name="classroom_ids[]" 
                                                        value="<?= $c['id'] ?>" 
                                                        id="class_<?= $c['id'] ?>" 
                                                        class="classroom-card-input classroom-check d-none"
                                                        <?= $isDisabled ? 'disabled' : '' ?>>
                                                    <div class="classroom-card" id="card_<?= $c['id'] ?>">
                                                        <i class="bi bi-check-circle-fill check-icon"></i>
                                                        <div class="class-name fw-semibold small"><?= esc($c['name']) ?></div>
                                                        <div class="teacher-label text-truncate <?= $labelClass ?>" id="label_teacher_<?= $c['id'] ?>"><?= $labelText ?></div>
                                                    </div>
                                                </label>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                        <div class="form-text text-muted small mt-2">
                            <i class="bi bi-info-circle me-1"></i> Klik untuk memilih kelas tanggung jawab Guru BK.
                            Kelas yang sudah diampu guru lain akan terkunci secara otomatis.
                        </div>
                    </div>

                    <button type="submit" class="btn btn-primary w-100 py-2">
                        <i class="bi bi-save me-2"></i>Simpan Penugasan
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-md-7">
        <div class="card">
            <div class="card-header">
                <div class="d-flex align-items-center justify-content-between py-1">
                    <div class="d-flex align-items-center gap-2">
                        <i class="bi bi-table text-primary fs-5"></i>
                        <span class="fw-semibold">Daftar Guru BK</span>
                        <span class="badge bg-secondary"><?= count($assignments) ?></span>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover align-middle table-sm" id="dataTable">
                        <thead class="table-light">
                            <tr>
                                <th width="50" class="text-center">#</th>
                                <th width="200">Guru BK</th>
                                <th>Kelas yang Diampu</th>
                                <th width="100">Periode</th>
                                <th width="80" class="text-center">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($assignments)): ?>
                            <tr class="text-center">
                                <td colspan="5" class="text-muted py-5">
                                    <i class="bi bi-inbox fs-2 d-block mb-2 opacity-25"></i>
                                    <small>Belum ada data assignment BK</small>
                                </td>
                            </tr>
                            <?php else: ?>
                                <?php 
                                    $grouped = [];
                                    foreach ($assignments as $a) {
                                        $key = $a['teacher_id'];
                                        if (!isset($grouped[$key])) {
                                            $grouped[$key] = [
                                                'teacher_id'   => $a['teacher_id'],
                                                'teacher_name' => $a['teacher_name'],
                                                'nip' => $a['nip'],
                                                'classes' => [],
                                                'period' => $a['semester'] . ' - ' . $a['year_name'],
                                            ];
                                        }
                                        $grouped[$key]['classes'][] = [
                                            'id' => $a['id'],
                                            'name' => $a['classroom_name'] . ' (' . $a['grade_name'] . ')'
                                        ];
                                    }
                                ?>
                                <?php $no = 1; foreach ($grouped as $g): ?>
                                <tr>
                                    <td class="text-center fw-medium text-muted"><?= $no++ ?></td>
                                    <td>
                                        <div class="fw-semibold text-dark"><?= esc($g['teacher_name']) ?></div>
                                        <?php if ($g['nip']): ?>
                                        <small class="text-muted" style="font-size: 11px;"><?= teacher_id_label($g['status_kepegawaian'] ?? null) ?>: <?= esc(teacher_id_display($g)) ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="d-flex flex-wrap gap-1">
                                            <?php foreach ($g['classes'] as $cls): ?>
                                            <a href="/bk-assignment/delete/<?= $cls['id'] ?>" 
                                                class="badge bg-light text-dark border d-inline-flex align-items-center gap-1 text-decoration-none shadow-sm hover-badge" 
                                                onclick="return confirm('Hapus kelas <?= esc($cls['name']) ?> dari guru ini?')"
                                                title="Hapus kelas ini dari <?= esc($g['teacher_name']) ?>">
                                                <?= esc($cls['name']) ?> 
                                                <i class="bi bi-x-circle-fill text-danger fs-6 ms-1"></i>
                                            </a>
                                            <?php endforeach; ?>
                                        </div>
                                    </td>
                                    <td><span class="badge bg-secondary py-1 px-2"><?= esc($g['period']) ?></span></td>
                                    <td class="text-center">
                                        <button type="button" 
                                            class="btn btn-sm btn-outline-primary btn-edit-assignment"
                                            data-teacher-id="<?= $g['teacher_id'] ?>"
                                            title="Edit Penugasan">
                                            <i class="bi bi-pencil-square me-1"></i>Edit
                                        </button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<!-- Load Select2 CDN -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
$(document).ready(function() {
    // Inisialisasi Select2
    $('.select2-teacher').select2({
        theme: 'bootstrap-5',
        placeholder: '-- Pilih Guru --',
        allowClear: true,
        width: '100%'
    });

    $('.select2-simple').select2({
        theme: 'bootstrap-5',
        width: '100%'
    });

    const assignedMap = <?= json_encode($assignedMap) ?>;

    // Fungsi untuk memperbarui status visual & properti kartu kelas
    function updateClassroomStates() {
        const teacherId = $('#teacher_id').val();
        const periodId = $('#period_id').val();
        
        // Reset checkbox & label kembali ke default
        $('.classroom-card-input').prop('checked', false).prop('disabled', false);
        $('.teacher-label').text('Belum diampu').removeClass('text-success text-danger').addClass('text-muted');
        
        if (!teacherId) {
            // Jika tidak ada guru terpilih: kunci kelas yang sudah diampu orang lain
            $('.classroom-card-input').each(function() {
                const classId = $(this).val();
                const assignment = assignedMap[classId];
                if (assignment) {
                    $(this).prop('disabled', true);
                    $(`#label_teacher_${classId}`).text('BK: ' + assignment.teacher_name).removeClass('text-success text-muted').addClass('text-danger');
                }
            });
            updateSelectedCount();
            return;
        }
        
        // Load kelas-kelas milik guru terpilih
        $.ajax({
            url: '/bk-assignment/get-by-teacher',
            method: 'GET',
            data: { teacher_id: teacherId, period_id: periodId },
            dataType: 'json',
            success: function(data) {
                const currentTeacherClasses = (data.classroom_ids || []).map(String);
                
                $('.classroom-card-input').each(function() {
                    const classId = $(this).val();
                    const assignment = assignedMap[classId];
                    
                    if (currentTeacherClasses.includes(classId)) {
                        // Diampu oleh guru ini
                        $(this).prop('checked', true);
                        $(`#label_teacher_${classId}`).text('BK Anda').removeClass('text-danger text-muted').addClass('text-success');
                    } else if (assignment) {
                        // Diampu guru lain -> Lock
                        $(this).prop('disabled', true);
                        $(`#label_teacher_${classId}`).text('BK: ' + assignment.teacher_name).removeClass('text-success text-muted').addClass('text-danger');
                    } else {
                        // Kosong / Bebas
                        $(`#label_teacher_${classId}`).text('Belum diampu').removeClass('text-success text-danger').addClass('text-muted');
                    }
                });
                
                updateSelectedCount();
            }
        });
    }

    // Fungsi menghitung jumlah terpilih
    function updateSelectedCount() {
        const checkedCount = $('.classroom-check:checked').length;
        $('#selected-counter').text(checkedCount + ' kelas terpilih');
    }

    // Triggers
    $('#teacher_id').change(updateClassroomStates);
    $('#period_id').change(updateClassroomStates);
    
    // Pemicu manual ketika admin mengklik checkbox yang aktif
    $(document).on('change', '.classroom-check', function() {
        updateSelectedCount();
        const classId = $(this).val();
        if ($(this).is(':checked')) {
            $(`#label_teacher_${classId}`).text('BK Anda').removeClass('text-danger text-muted').addClass('text-success');
        } else {
            $(`#label_teacher_${classId}`).text('Belum diampu').removeClass('text-success text-danger').addClass('text-muted');
        }
    });

    // Jalankan inisialisasi awal
    updateClassroomStates();

    // Handler Tombol Edit di Tabel
    $(document).on('click', '.btn-edit-assignment', function() {
        const teacherId = $(this).data('teacher-id');
        
        // Set nilai Select2 dan trigger change event
        $('#teacher_id').val(teacherId).trigger('change');
        
        // Scroll halus ke form
        $('html, body').animate({
            scrollTop: $("#formAssignment").offset().top - 120
        }, 500);
        
        // Animasi highlight card
        const card = $("#formAssignment").closest('.card');
        card.addClass('border-primary shadow-lg');
        setTimeout(() => {
            card.removeClass('border-primary shadow-lg');
        }, 1500);
    });

    // Validasi submit
    $('#formAssignment').submit(function(e) {
        const teacherId = $('#teacher_id').val();
        const checked = $('.classroom-check:checked').length;
        
        if (!teacherId) {
            e.preventDefault();
            alert('Silakan pilih guru terlebih dahulu!');
            return false;
        }
        
        if (checked === 0) {
            if (!confirm('Anda tidak memilih kelas satu pun. Menyimpan akan menghapus seluruh penugasan untuk guru BK ini. Lanjutkan?')) {
                e.preventDefault();
                return false;
            }
        }
    });
});
</script>
<?= $this->endSection() ?>