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

<div class="row justify-content-center">
<div class="col-12">
<div class="card">
    <div class="card-header d-flex align-items-center justify-content-between">
        <div class="d-flex align-items-center gap-2">
            <i class="bi bi-person-check text-warning"></i>
            <span class="fw-semibold">Surat Tugas</span>
        </div>
        <a href="/letter" class="btn btn-sm btn-outline-secondary">
            <i class="bi bi-arrow-left me-1"></i>Kembali
        </a>
    </div>
    <div class="card-body">

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

        <div class="alert alert-info py-2 small">
            <i class="bi bi-info-circle me-1"></i>
            Format nomor surat tugas Kemenag: <strong>B-{urut}/MTs.xx.xx/PP.00.7/{bulan}/{tahun}</strong>
        </div>

        <form action="/letter/surat-tugas/preview" method="post">
            <input type="hidden" name="teacher_id" id="teacherId">
            <?= csrf_field() ?>

            <!-- Jenis Surat Tugas -->
            <div class="mb-4">
                <h6 class="fw-semibold mb-3"><i class="bi bi-gear me-1 text-primary"></i>Kategori Surat Tugas</h6>
                <div class="p-3 rounded border bg-light bg-opacity-50">
                    <div class="row g-3">
                        <div class="col-md-12">
                            <label class="form-label d-block fw-semibold small text-muted mb-2">Pilih Kategori Penugasan <span class="text-danger">*</span></label>
                            <div class="form-check form-check-inline me-4">
                                <input class="form-check-input" type="radio" name="is_reference" id="typeMandiri" value="0" checked onchange="toggleReferenceFields(this.value)">
                                <label class="form-check-label fw-semibold" for="typeMandiri">
                                    <i class="bi bi-briefcase me-1 text-success"></i>Tugas Mandiri / Internal Madrasah
                                </label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="is_reference" id="typeRujukan" value="1" onchange="toggleReferenceFields(this.value)">
                                <label class="form-check-label fw-semibold" for="typeRujukan">
                                    <i class="bi bi-reply-all me-1 text-info"></i>Menindaklanjuti Surat Dinas / Undangan Atasan
                                </label>
                            </div>
                            <div class="form-text small text-muted mt-2">
                                <i class="bi bi-info-circle"></i> <strong>Mandiri:</strong> Penugasan langsung dari Kepala Madrasah (contoh: Panitia PPDB, Panitia Ujian, Wali Kelas).<br>
                                <i class="bi bi-info-circle"></i> <strong>Menindaklanjuti Surat:</strong> Penugasan berdasarkan surat undangan/perintah dari luar (contoh: Panggilan Bimtek dari Kemenag/Kanwil).
                            </div>
                        </div>
                    </div>

                    <!-- Input Surat Rujukan (Tampil jika memilih Menindaklanjuti) -->
                    <div id="referenceFormFields" class="mt-3 p-3 rounded bg-white border border-info" style="display:none">
                        <h6 class="fw-semibold text-info mb-3 small" style="font-size:0.9rem">
                            <i class="bi bi-file-earmark-text me-1"></i>Data Surat Rujukan / Undangan Masuk
                        </h6>
                        <div class="row g-3">
                            <div class="col-md-8">
                                <label class="form-label small fw-semibold">Jabatan Pengirim Surat / Instansi <span class="text-danger">*</span></label>
                                <input type="text" name="reference_officer" id="refOfficer" class="form-control form-control-sm"
                                    placeholder="Contoh: Kepala Kantor Wilayah Kementerian Agama Provinsi Sumatera Selatan">
                                <div class="form-text small text-muted">Jabatan resmi penandatangan surat yang mengundang/memerintahkan tugas.</div>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label small fw-semibold">Nomor Surat Rujukan <span class="text-danger">*</span></label>
                                <input type="text" name="reference_number" id="refNumber" class="form-control form-control-sm"
                                    placeholder="Contoh: B-123/Kw.06.1/2/PP.00/06/2026">
                                <div class="form-text small text-muted">Nomor surat undangan atau disposisi resmi.</div>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label small fw-semibold">Tanggal Surat Rujukan <span class="text-danger">*</span></label>
                                <input type="date" name="reference_date" id="refDate" class="form-control form-control-sm">
                                <div class="form-text small text-muted">Tanggal diterbitkannya surat rujukan tersebut.</div>
                            </div>
                            <div class="col-md-9">
                                <label class="form-label small fw-semibold">Hal / Judul Kegiatan Pada Surat Rujukan <span class="text-danger">*</span></label>
                                <input type="text" name="reference_theme" id="refTheme" class="form-control form-control-sm"
                                    placeholder="Contoh: Orientasi Penyusunan LAKIP Angkatan II">
                                <div class="form-text small text-muted">Perihal atau judul acara pada surat rujukan (tidak perlu menulis tanda kutip).</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Pilih Guru -->
            <div class="mb-4">
                <h6 class="fw-semibold mb-3"><i class="bi bi-person me-1"></i>Pilih Guru / Pegawai</h6>
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">Cari Guru <span class="text-danger">*</span></label>
                        <select id="teacherSelect" class="form-select">
                            <option value="">-- Ketik nama untuk mencari --</option>
                            <?php foreach ($teachers as $t): ?>
                            <option value="<?= $t['id'] ?>"
                                data-name="<?= esc($t['name']) ?>"
                                data-nip="<?= esc($t['nip'] ?? '') ?>"
                                data-peg_id="<?= esc($t['peg_id'] ?? '') ?>"
                                data-status="<?= esc($t['status_kepegawaian'] ?? '') ?>"
                                data-golongan="<?= esc($t['golongan'] ?? '') ?>"
                                data-jabatan="<?= esc($t['jabatan'] ?? '') ?>"><?= esc($t['name']) ?><?php $idNum = teacher_id_number($t); ?><?= !empty($idNum) ? ' — ' . esc($idNum) : '' ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="form-text">Pilih dari daftar, data akan terisi otomatis. Bisa diedit jika perlu.</div>
                    </div>
                </div>
            </div>

            <!-- Data Pelaksana (auto-fill, editable) -->
            <div class="mb-4">
                <h6 class="fw-semibold mb-3"><i class="bi bi-person-badge me-1"></i>Data Pelaksana Tugas</h6>
                <div class="row g-3">
                    <div class="col-md-8">
                        <label class="form-label">Nama Lengkap <span class="text-danger">*</span></label>
                        <input type="text" name="officer_name" id="officerName" class="form-control" required
                            value="<?= old('officer_name') ?>"
                            placeholder="Nama lengkap guru / pegawai">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">NIP / PEG ID / NPK / NUPTK</label>
                        <input type="text" name="officer_nip" id="officerNip" class="form-control"
                            value="<?= old('officer_nip') ?>"
                            placeholder="Contoh: 197604122005011002">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Pangkat / Golongan</label>
                        <input type="text" name="officer_rank" id="officerRank" class="form-control"
                            value="<?= old('officer_rank') ?>"
                            placeholder="Contoh: Penata, III/c">
                    </div>
                    <div class="col-md-8">
                        <label class="form-label">Jabatan / Mata Pelajaran</label>
                        <input type="text" name="officer_position" id="officerPosition" class="form-control"
                            value="<?= old('officer_position') ?>"
                            placeholder="Contoh: Guru Matematika / Bendahara BOS">
                    </div>
                </div>
            </div>

            <!-- Data Surat -->
            <div class="mb-4">
                <h6 class="fw-semibold mb-3"><i class="bi bi-envelope me-1"></i>Data Surat</h6>
                <div class="row g-3">
                    <div class="col-md-5">
                        <label class="form-label">Nomor Surat <span class="text-danger">*</span></label>
                        <input type="text" name="letter_number" class="form-control" required
                            value="<?= old('letter_number') ?>"
                            placeholder="B-001/MTs.xx.xx/PP.00.7/06/2026">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Tanggal Surat <span class="text-danger">*</span></label>
                        <input type="date" name="letter_date" class="form-control" required
                            value="<?= old('letter_date', date('Y-m-d')) ?>">
                    </div>
                </div>
            </div>

            <!-- Detail Penugasan -->
            <div class="mb-4">
                <h6 class="fw-semibold mb-3"><i class="bi bi-clipboard-check me-1"></i>Detail Penugasan</h6>
                <div class="row g-3">
                    <div class="col-12">
                        <label class="form-label">Uraian Tugas / Kegiatan <span class="text-danger">*</span></label>
                        <textarea name="assignment_detail" class="form-control" rows="3" required
                            placeholder="Contoh: menghadiri Workshop Penguatan Kompetensi Guru Madrasah yang diselenggarakan oleh Kantor Wilayah Kemenag Provinsi Jawa Tengah"><?= old('assignment_detail') ?></textarea>
                    </div>
                    <div class="col-md-5">
                        <label class="form-label">Tempat Pelaksanaan <span class="text-danger">*</span></label>
                        <input type="text" name="assignment_place" class="form-control" required
                            value="<?= old('assignment_place') ?>"
                            placeholder="Contoh: Aula Kanwil Kemenag Jateng, Semarang">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Tanggal Mulai <span class="text-danger">*</span></label>
                        <input type="date" name="assignment_start" class="form-control" required
                            value="<?= old('assignment_start') ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Tanggal Selesai <span class="text-danger">*</span></label>
                        <input type="date" name="assignment_end" class="form-control" required
                            value="<?= old('assignment_end') ?>">
                    </div>
                </div>
            </div>

            <div class="d-flex justify-content-end gap-2">
                <a href="/letter" class="btn btn-secondary"><i class="bi bi-x-circle me-1"></i>Batal</a>
                <button type="submit" class="btn btn-warning">
                    <i class="bi bi-save me-1"></i>Simpan Surat
                </button>
            </div>
        </form>
    </div>
</div>
</div>
</div>

<script>
function fillTeacherData() {
    const sel = document.getElementById('teacherSelect');
    const opt = sel.options[sel.selectedIndex];
    if (!sel.value) { document.getElementById('teacherId').value = ''; return; }

    document.getElementById('teacherId').value        = sel.value;
    document.getElementById('officerName').value      = opt.dataset.name     || '';
    document.getElementById('officerNip').value       = opt.dataset.nip || opt.dataset.peg_id || '';
    document.getElementById('officerRank').value      = opt.dataset.golongan || '';
    document.getElementById('officerPosition').value  = opt.dataset.jabatan  || '';
    document.getElementById('officerPosition').focus();
}

function toggleReferenceFields(val) {
    const isRef = parseInt(val) === 1;
    const refContainer = document.getElementById('referenceFormFields');
    refContainer.style.display = isRef ? '' : 'none';
    
    // Set/unset required attributes dynamically
    document.getElementById('refOfficer').required = isRef;
    document.getElementById('refNumber').required = isRef;
    document.getElementById('refDate').required = isRef;
    document.getElementById('refTheme').required = isRef;
}
</script>

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

<?= $this->section('scripts') ?>
<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() {
    $('#teacherSelect').select2({
        placeholder: '-- Ketik nama untuk mencari --',
        allowClear: true,
        width: '100%',
        theme: 'bootstrap-5'
    }).on('change', fillTeacherData);
});
</script>
<?= $this->endSection() ?>