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

<?= $this->section('content') ?>

<div class="container-fluid px-4 py-4">
    <!-- Header -->
    <div class="d-flex align-items-center justify-content-between mb-4">
        <div>
            <h4 class="fw-bold text-dark mb-1 d-flex align-items-center gap-2">
                <i class="bi bi-calendar-event text-orange"></i> Rincian Pekan Efektif (RPE)
            </h4>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-0 small">
                    <li class="breadcrumb-item"><a href="/dashboard" class="text-decoration-none text-muted">Dashboard</a></li>
                    <li class="breadcrumb-item"><a href="/guru/learning-devices" class="text-decoration-none text-muted">Perangkat Pembelajaran</a></li>
                    <li class="breadcrumb-item active text-dark fw-medium" aria-current="page">RPE</li>
                </ol>
            </nav>
        </div>
        <div class="d-flex gap-2 align-items-center flex-wrap">
            <div class="d-flex align-items-center gap-2 me-2">
                <label for="jpPerWeekSelect" class="small fw-bold text-muted text-nowrap mb-0"><i class="bi bi-clock-history"></i> JP / Minggu:</label>
                <select id="jpPerWeekSelect" class="form-select form-select-sm border-light-subtle shadow-sm" style="width: 90px; border-radius: 8px;">
                    <?php for($i=1; $i<=10; $i++): ?>
                        <option value="<?= $i ?>" <?= ($device['jp_per_week'] ?? 4) == $i ? 'selected' : '' ?>><?= $i ?> JP</option>
                    <?php endfor; ?>
                </select>
            </div>

            <button type="button" class="btn btn-outline-orange border-1 shadow-sm hover-bg-light transition-all rounded-pill px-3" id="btnSyncKaldik">
                <i class="bi bi-arrow-repeat me-1"></i> Sinkronkan dengan Kaldik
            </button>
            <button type="button" class="btn btn-orange text-white border-0 shadow-sm hover-bg-light transition-all rounded-pill px-4" id="btnSaveRpeHeader" style="background-color: #f97316; color: white;">
                <i class="bi bi-save me-1"></i> Simpan
            </button>

            <a href="/guru/learning-devices" class="btn btn-light border-0 shadow-sm text-muted hover-bg-light transition-all rounded-pill px-3">
                <i class="bi bi-arrow-left me-1"></i> Kembali
            </a>
        </div>
    </div>

    <!-- Alert Messages -->
    <div id="alert-container">
        <?php if (session()->getFlashdata('success')): ?>
            <div class="alert alert-success alert-dismissible fade show border-0 shadow-sm" role="alert" style="border-radius: 10px;">
                <i class="bi bi-check-circle-fill me-2 text-success"></i><?= session()->getFlashdata('success') ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        <?php if (session()->getFlashdata('error')): ?>
            <div class="alert alert-danger alert-dismissible fade show border-0 shadow-sm" role="alert" style="border-radius: 10px;">
                <i class="bi bi-exclamation-triangle-fill me-2 text-danger"></i><?= session()->getFlashdata('error') ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
    </div>

    <div class="row g-4">
        <div class="col-lg-8">
            <form id="rpeForm">
                <div class="card shadow-sm border-0 rounded-3 mb-4">
                    <div class="card-body p-4">
                        <ul class="nav nav-pills mb-4 gap-2" id="semesterTab" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active px-4 py-2 fw-semibold" id="sem1-tab" data-bs-toggle="tab" data-bs-target="#sem1-pane" type="button" role="tab" aria-selected="true" style="border-radius: 30px;">
                                    <i class="bi bi-calendar3 me-1"></i> Semester 1 (Ganjil)
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link px-4 py-2 fw-semibold" id="sem2-tab" data-bs-toggle="tab" data-bs-target="#sem2-pane" type="button" role="tab" aria-selected="false" style="border-radius: 30px;">
                                    <i class="bi bi-calendar3-fill me-1"></i> Semester 2 (Genap)
                                </button>
                            </li>
                        </ul>

                        <div class="tab-content" id="semesterTabContent">
                            <!-- Semester 1 Pane -->
                            <div class="tab-pane fade show active" id="sem1-pane" role="tabpanel" aria-labelledby="sem1-tab">
                                <div class="table-responsive">
                                    <table class="table table-bordered table-hover align-middle table-rpe" id="tableSem1">
                                        <thead class="table-light">
                                            <tr>
                                                <th width="150">Bulan</th>
                                                <th width="120" class="text-center">Jumlah Minggu</th>
                                                <th width="120" class="text-center">Minggu Efektif</th>
                                                <th width="120" class="text-center">Minggu Tidak Efektif</th>
                                                <th>Keterangan Kegiatan / Alasan</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $monthsS1 = [
                                                7 => 'Juli', 8 => 'Agustus', 9 => 'September', 
                                                10 => 'Oktober', 11 => 'November', 12 => 'Desember'
                                            ];
                                            foreach ($monthsS1 as $mNum => $mName): 
                                                $row = $rpeData['sem1'][$mNum] ?? [
                                                    'total_weeks' => ($mNum == 8 || $mNum == 11) ? 5 : 4,
                                                    'effective_weeks' => ($mNum == 7) ? 2 : (($mNum == 12) ? 0 : (($mNum == 8 || $mNum == 11) ? 4 : 4)),
                                                    'non_effective_weeks' => ($mNum == 7) ? 2 : (($mNum == 12) ? 4 : (($mNum == 8 || $mNum == 11) ? 1 : 0)),
                                                    'note' => ($mNum == 7) ? 'Libur Akhir Semester & MPLS' : (($mNum == 8) ? 'HUT RI' : (($mNum == 11) ? 'Asesmen Akhir Semester' : (($mNum == 12) ? 'Libur Semester 1' : '')))
                                                ];
                                                $weekStatuses = $row['week_statuses'] ?? [];
                                                if (empty($weekStatuses)) {
                                                    for ($w = 1; $w <= 5; $w++) {
                                                        $weekStatuses[$w] = ($w <= $row['effective_weeks'] && $w <= $row['total_weeks']);
                                                    }
                                                }
                                            ?>
                                            <tr data-month="<?= $mNum ?>" data-week-statuses='<?= json_encode($weekStatuses) ?>'>
                                                <td class="fw-semibold text-dark"><?= $mName ?></td>
                                                <td>
                                                    <input type="number" name="sem1[<?= $mNum ?>][total_weeks]" class="form-control form-control-sm text-center input-total" min="1" max="6" value="<?= $row['total_weeks'] ?>">
                                                </td>
                                                <td>
                                                    <input type="number" name="sem1[<?= $mNum ?>][effective_weeks]" class="form-control form-control-sm text-center input-effective" min="0" max="6" value="<?= $row['effective_weeks'] ?>">
                                                </td>
                                                <td>
                                                    <input type="number" name="sem1[<?= $mNum ?>][non_effective_weeks]" class="form-control form-control-sm text-center input-noneffective" min="0" max="6" value="<?= $row['non_effective_weeks'] ?>" readonly>
                                                </td>
                                                <td>
                                                    <input type="text" name="sem1[<?= $mNum ?>][note]" class="form-control form-control-sm" placeholder="Contoh: Libur Semester..." value="<?= esc($row['note']) ?>">
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                        <tfoot class="table-light fw-bold text-dark">
                                            <tr>
                                                <td>Total Pekan</td>
                                                <td class="text-center total-weeks-sum-s1">0</td>
                                                <td class="text-center total-eff-sum-s1">0</td>
                                                <td class="text-center total-noneff-sum-s1">0</td>
                                                <td></td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>

                            <!-- Semester 2 Pane -->
                            <div class="tab-pane fade" id="sem2-pane" role="tabpanel" aria-labelledby="sem2-tab">
                                <div class="table-responsive">
                                    <table class="table table-bordered table-hover align-middle table-rpe" id="tableSem2">
                                        <thead class="table-light">
                                            <tr>
                                                <th width="150">Bulan</th>
                                                <th width="120" class="text-center">Jumlah Minggu</th>
                                                <th width="120" class="text-center">Minggu Efektif</th>
                                                <th width="120" class="text-center">Minggu Tidak Efektif</th>
                                                <th>Keterangan Kegiatan / Alasan</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $monthsS2 = [
                                                1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 
                                                4 => 'April', 5 => 'Mei', 6 => 'Juni'
                                            ];
                                            foreach ($monthsS2 as $mNum => $mName): 
                                                $row = $rpeData['sem2'][$mNum] ?? [
                                                    'total_weeks' => ($mNum == 3 || $mNum == 6) ? 5 : 4,
                                                    'effective_weeks' => ($mNum == 3) ? 3 : (($mNum == 4) ? 2 : (($mNum == 6) ? 0 : 4)),
                                                    'non_effective_weeks' => ($mNum == 3) ? 2 : (($mNum == 4) ? 2 : (($mNum == 6) ? 5 : 0)),
                                                    'note' => ($mNum == 3) ? 'Libur Awal Ramadhan' : (($mNum == 4) ? 'Libur Idul Fitri' : (($mNum == 6) ? 'Libur Akhir Tahun Ajaran' : ''))
                                                ];
                                                $weekStatuses = $row['week_statuses'] ?? [];
                                                if (empty($weekStatuses)) {
                                                    for ($w = 1; $w <= 5; $w++) {
                                                        $weekStatuses[$w] = ($w <= $row['effective_weeks'] && $w <= $row['total_weeks']);
                                                    }
                                                }
                                            ?>
                                            <tr data-month="<?= $mNum ?>" data-week-statuses='<?= json_encode($weekStatuses) ?>'>
                                                <td class="fw-semibold text-dark"><?= $mName ?></td>
                                                <td>
                                                    <input type="number" name="sem2[<?= $mNum ?>][total_weeks]" class="form-control form-control-sm text-center input-total" min="1" max="6" value="<?= $row['total_weeks'] ?>">
                                                </td>
                                                <td>
                                                    <input type="number" name="sem2[<?= $mNum ?>][effective_weeks]" class="form-control form-control-sm text-center input-effective" min="0" max="6" value="<?= $row['effective_weeks'] ?>">
                                                </td>
                                                <td>
                                                    <input type="number" name="sem2[<?= $mNum ?>][non_effective_weeks]" class="form-control form-control-sm text-center input-noneffective" min="0" max="6" value="<?= $row['non_effective_weeks'] ?>" readonly>
                                                </td>
                                                <td>
                                                    <input type="text" name="sem2[<?= $mNum ?>][note]" class="form-control form-control-sm" placeholder="Contoh: Libur Keagamaan..." value="<?= esc($row['note']) ?>">
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                        <tfoot class="table-light fw-bold text-dark">
                                            <tr>
                                                <td>Total Pekan</td>
                                                <td class="text-center total-weeks-sum-s2">0</td>
                                                <td class="text-center total-eff-sum-s2">0</td>
                                                <td class="text-center total-noneff-sum-s2">0</td>
                                                <td></td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <div class="mt-4 pt-3 border-top text-end">
                            <button type="button" class="btn btn-orange text-white px-4 shadow-sm rounded-pill" id="btnSaveRpe" style="background-color: #f97316; color: white;">
                                <i class="bi bi-save me-1"></i> Simpan Pekan Efektif
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <div class="col-lg-4">
            <!-- Dynamic Information Card -->
            <div class="card shadow-sm border-0 rounded-3 mb-4">
                <div class="card-body p-4 bg-light-subtle">
                    <h6 class="fw-bold text-dark mb-3"><i class="bi bi-calculator text-primary me-2"></i> Rekapitulasi RPE</h6>
                    <div class="d-flex justify-content-between mb-2">
                        <span class="text-muted">Total Minggu Efektif S1:</span>
                        <span class="fw-bold text-success total-eff-sum-s1-badge">0 Pekan</span>
                    </div>
                    <div class="d-flex justify-content-between mb-2">
                        <span class="text-muted">Total Minggu Efektif S2:</span>
                        <span class="fw-bold text-success total-eff-sum-s2-badge">0 Pekan</span>
                    </div>
                    <hr class="my-2">
                    <div class="d-flex justify-content-between">
                        <span class="text-muted font-bold">Total Efektif Setahun:</span>
                        <span class="fw-bold text-primary total-eff-sum-annual">0 Pekan</span>
                    </div>
                </div>
            </div>

            <!-- Kaldik Holiday events reference card -->
            <div class="card shadow-sm border-0 rounded-3 mb-4">
                <div class="card-body p-4">
                    <h6 class="fw-bold text-dark mb-3">
                        <i class="bi bi-calendar-range text-orange me-2"></i> Libur Akademik (Kaldik)
                    </h6>
                    <div style="max-height: 250px; overflow-y: auto;" class="pe-1">
                        <?php if (!empty($liburEvents)): ?>
                            <ul class="list-group list-group-flush small">
                                <?php foreach ($liburEvents as $ev): 
                                    $start = new \DateTime($ev['start_date']);
                                    $end = new \DateTime($ev['end_date']);
                                    $dateRange = $start->format('d M Y');
                                    if ($ev['start_date'] !== $ev['end_date']) {
                                        $dateRange .= ' - ' . $end->format('d M Y');
                                    }
                                ?>
                                    <li class="list-group-item px-0 py-2 bg-transparent">
                                        <div class="fw-semibold text-dark"><?= esc($ev['title']) ?></div>
                                        <div class="text-muted" style="font-size: 0.75rem;">
                                            <i class="bi bi-calendar-event me-1"></i><?= $dateRange ?> 
                                            <span class="badge bg-secondary-subtle text-secondary ms-1"><?= esc($ev['category_name']) ?></span>
                                        </div>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        <?php else: ?>
                            <p class="text-muted small mb-0">Tidak ada event libur khusus tercatat pada kalender tahun ajaran ini.</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="card shadow-sm border-0 rounded-3">
                <div class="card-body p-4">
                    <h6 class="fw-bold text-dark d-flex align-items-center gap-2 mb-3">
                        <i class="bi bi-info-circle-fill text-primary"></i> Panduan Penyusunan
                    </h6>
                    <p class="text-muted small text-justify leading-relaxed mb-0" style="font-size: 0.85rem;">
                        <strong>Rincian Pekan Efektif (RPE)</strong> adalah dasar pembagian alokasi waktu pembelajaran di Program Tahunan (Prota) dan Program Semester (Promes).<br><br>
                        1. Tentukan jumlah minggu kalender tiap bulan.<br>
                        2. Isi jumlah minggu efektif mengajar.<br>
                        3. Minggu tidak efektif akan dihitung otomatis beserta total akumulasinya.
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>
<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
$(document).ready(function() {
    const deviceId = <?= $device['id'] ?>;

    // Hitung otomatis minggu tidak efektif & total sum
    function calculateRpeTotals() {
        // Semester 1
        let s1TotalWeeks = 0;
        let s1EffWeeks = 0;
        let s1NonEffWeeks = 0;

        $('#tableSem1 tbody tr').each(function() {
            const tr = $(this);
            const total = parseInt(tr.find('.input-total').val()) || 0;
            const eff = parseInt(tr.find('.input-effective').val()) || 0;
            
            // Limit effective weeks to total weeks
            let finalEff = eff;
            if (eff > total) {
                finalEff = total;
                tr.find('.input-effective').val(total);
            }
            
            const nonEff = total - finalEff;
            tr.find('.input-noneffective').val(nonEff);

            s1TotalWeeks += total;
            s1EffWeeks += finalEff;
            s1NonEffWeeks += nonEff;
        });

        $('.total-weeks-sum-s1').text(s1TotalWeeks);
        $('.total-eff-sum-s1').text(s1EffWeeks);
        $('.total-noneff-sum-s1').text(s1NonEffWeeks);
        $('.total-eff-sum-s1-badge').text(s1EffWeeks + ' Pekan');

        // Semester 2
        let s2TotalWeeks = 0;
        let s2EffWeeks = 0;
        let s2NonEffWeeks = 0;

        $('#tableSem2 tbody tr').each(function() {
            const tr = $(this);
            const total = parseInt(tr.find('.input-total').val()) || 0;
            const eff = parseInt(tr.find('.input-effective').val()) || 0;
            
            // Limit effective weeks to total weeks
            let finalEff = eff;
            if (eff > total) {
                finalEff = total;
                tr.find('.input-effective').val(total);
            }
            
            const nonEff = total - finalEff;
            tr.find('.input-noneffective').val(nonEff);

            s2TotalWeeks += total;
            s2EffWeeks += finalEff;
            s2NonEffWeeks += nonEff;
        });

        $('.total-weeks-sum-s2').text(s2TotalWeeks);
        $('.total-eff-sum-s2').text(s2EffWeeks);
        $('.total-noneff-sum-s2').text(s2NonEffWeeks);
        $('.total-eff-sum-s2-badge').text(s2EffWeeks + ' Pekan');

        // Annual
        $('.total-eff-sum-annual').text((s1EffWeeks + s2EffWeeks) + ' Pekan');
    }

    // Bind event listeners to input changes
    $(document).on('input', '.input-total, .input-effective', function() {
        calculateRpeTotals();
    });

    // Run initial calculations
    calculateRpeTotals();

    // Helper serialize JSON
    function serializeRpeForm() {
        const payload = {
            sem1: {},
            sem2: {}
        };

        $('#tableSem1 tbody tr').each(function() {
            const tr = $(this);
            const m = tr.data('month');
            const total = parseInt(tr.find('.input-total').val()) || 0;
            const eff = parseInt(tr.find('.input-effective').val()) || 0;
            const nonEff = parseInt(tr.find('.input-noneffective').val()) || 0;
            const note = tr.find('input[type="text"]').val() || '';
            
            // Re-calculate week statuses based on total and effective weeks inputs
            let weekStatuses = tr.data('week-statuses') || {};
            let updatedStatuses = {};
            for (let w = 1; w <= 5; w++) {
                if (w <= total) {
                    // Try to preserve original week status if we have it, else distribute
                    if (weekStatuses.hasOwnProperty(w)) {
                        updatedStatuses[w] = weekStatuses[w];
                    } else {
                        updatedStatuses[w] = (w <= eff);
                    }
                } else {
                    updatedStatuses[w] = false;
                }
            }

            // Adjust true values count to match input 'eff'
            let trueKeys = Object.keys(updatedStatuses).filter(k => updatedStatuses[k] === true);
            if (trueKeys.length !== eff) {
                // reset and activate first 'eff' weeks
                for (let w = 1; w <= 5; w++) {
                    updatedStatuses[w] = (w <= eff && w <= total);
                }
            }

            payload.sem1[m] = {
                total_weeks: total,
                effective_weeks: eff,
                non_effective_weeks: nonEff,
                note: note,
                week_statuses: updatedStatuses
            };
        });

        $('#tableSem2 tbody tr').each(function() {
            const tr = $(this);
            const m = tr.data('month');
            const total = parseInt(tr.find('.input-total').val()) || 0;
            const eff = parseInt(tr.find('.input-effective').val()) || 0;
            const nonEff = parseInt(tr.find('.input-noneffective').val()) || 0;
            const note = tr.find('input[type="text"]').val() || '';
            
            // Re-calculate week statuses based on total and effective weeks inputs
            let weekStatuses = tr.data('week-statuses') || {};
            let updatedStatuses = {};
            for (let w = 1; w <= 5; w++) {
                if (w <= total) {
                    if (weekStatuses.hasOwnProperty(w)) {
                        updatedStatuses[w] = weekStatuses[w];
                    } else {
                        updatedStatuses[w] = (w <= eff);
                    }
                } else {
                    updatedStatuses[w] = false;
                }
            }

            // Adjust true values count to match input 'eff'
            let trueKeys = Object.keys(updatedStatuses).filter(k => updatedStatuses[k] === true);
            if (trueKeys.length !== eff) {
                for (let w = 1; w <= 5; w++) {
                    updatedStatuses[w] = (w <= eff && w <= total);
                }
            }

            payload.sem2[m] = {
                total_weeks: total,
                effective_weeks: eff,
                non_effective_weeks: nonEff,
                note: note,
                week_statuses: updatedStatuses
            };
        });

        return payload;
    }

    // Save Action
    $('#btnSaveRpe, #btnSaveRpeHeader').on('click', function() {
        const btn = $(this);
        const originalText = btn.html();
        btn.html('<span class="spinner-border spinner-border-sm"></span> Menyimpan...').prop('disabled', true);

        const payload = serializeRpeForm();

        $.ajax({
            url: '/guru/learning-devices/rpe/save/' + deviceId,
            type: 'POST',
            contentType: 'application/json',
            headers: {
                'X-CSRF-TOKEN': '<?= csrf_hash() ?>'
            },
            data: JSON.stringify(payload),
            success: function(res) {
                if (res.status === 'success') {
                    Swal.fire({
                        toast: true,
                        position: 'top-end',
                        icon: 'success',
                        title: 'Rincian Pekan Efektif Berhasil Disimpan',
                        showConfirmButton: false,
                        timer: 3000
                    });
                } else {
                    Swal.fire('Gagal', res.message, 'error');
                }
            },
            error: function() {
                Swal.fire('Error', 'Gagal menyimpan data.', 'error');
            },
            complete: function() {
                btn.html(originalText).prop('disabled', false);
            }
        });
    });

    // Sync Kaldik action
    $('#btnSyncKaldik').on('click', function() {
        Swal.fire({
            title: 'Sinkronkan dengan Kaldik?',
            text: 'Tindakan ini akan memuat ulang data RPE berdasarkan Kalender Akademik Admin. Data yang belum Anda simpan akan hilang.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#e05638',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Ya, Sinkronkan!',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = '/guru/learning-devices/rpe/' + deviceId + '?sync=kaldik';
            }
        });
    });

    // Update JP Per Minggu action
    $('#jpPerWeekSelect').on('change', function() {
        const val = $(this).val();
        $.ajax({
            url: '/guru/learning-devices/update-jp-per-week',
            type: 'POST',
            data: {
                device_id: deviceId,
                jp_per_week: val,
                '<?= csrf_token() ?>': '<?= csrf_hash() ?>'
            },
            success: function(res) {
                if (res.status === 'success') {
                    Swal.fire({
                        toast: true,
                        position: 'top-end',
                        icon: 'success',
                        title: res.message,
                        showConfirmButton: false,
                        timer: 2000
                    });
                } else {
                    Swal.fire('Gagal', res.message, 'error');
                }
            },
            error: function() {
                Swal.fire('Error', 'Gagal memperbarui JP per minggu.', 'error');
            }
        });
    });
});
</script>
<?= $this->endSection() ?>
