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

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

<style>
.btn-indigo {
    background-color: #4f46e5 !important;
    border-color: #4f46e5 !important;
    color: #fff !important;
    transition: all 0.2s ease-in-out;
}
.btn-indigo:hover {
    background-color: #3730a3 !important;
    border-color: #3730a3 !important;
    color: #fff !important;
    box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
}
.btn-cancel-custom {
    background-color: #f1f5f9 !important;
    border: 1px solid #cbd5e1 !important;
    color: #475569 !important;
    transition: all 0.2s ease-in-out;
}
.btn-cancel-custom:hover {
    background-color: #e2e8f0 !important;
    color: #334155 !important;
    border-color: #94a3b8 !important;
}
</style>

<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-check text-indigo"></i> Program Semester (PROMES)
            </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">PROMES</li>
                </ol>
            </nav>
        </div>
        <div class="d-flex gap-2">

            <a href="/guru/learning-devices" class="btn btn-sm btn-outline-secondary py-2 px-3" style="border-radius: 8px;">
                <i class="bi bi-arrow-left me-1"></i> Kembali
            </a>
        </div>
    </div>

    <!-- Alert Messages -->
    <div id="alert-container"></div>

    <div class="row g-4">
        <div class="col-12">
            <form id="promesForm" action="/guru/learning-devices/promes/save/<?= $device['id'] ?>" method="post">
                <?= csrf_field() ?>
                <div class="card shadow-sm border-0 rounded-3">
                    <div class="card-body p-4">
                        <ul class="nav nav-pills mb-4 gap-2" id="promesTab" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active px-4 py-2 fw-semibold" id="promes1-tab" data-bs-toggle="tab" data-bs-target="#promes1-pane" type="button" role="tab" aria-selected="true" style="border-radius: 30px;">
                                    <i class="bi bi-1-circle me-1"></i> Promes Semester 1
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link px-4 py-2 fw-semibold" id="promes2-tab" data-bs-toggle="tab" data-bs-target="#promes2-pane" type="button" role="tab" aria-selected="false" style="border-radius: 30px;">
                                    <i class="bi bi-2-circle me-1"></i> Promes Semester 2
                                </button>
                            </li>
                        </ul>

                        <div class="tab-content" id="promesTabContent">
                            <!-- Pane 1: Promes Semester 1 -->
                            <div class="tab-pane fade show active" id="promes1-pane" role="tabpanel" aria-labelledby="promes1-tab">
                                <div class="alert alert-info py-2 px-3 small border-0 mb-3 d-flex align-items-center justify-content-between text-indigo" style="border-radius: 8px; background-color: #eef2ff;">
                                    <div>
                                        <i class="bi bi-info-circle-fill me-1"></i> **Panduan**: Masukkan beban JP mengajar guru untuk masing-masing TP di kolom minggu efektif (Juli s/d Desember) semester 1.
                                    </div>
                                    <button type="button" class="btn btn-xs text-white btn-promes-ai" data-semester="1" style="background: linear-gradient(135deg, #4f46e5 0%, #3730a3 100%); border: none; border-radius: 20px; padding: 4px 12px; font-weight: 600; font-size: 0.75rem; box-shadow: 0 2px 8px rgba(79, 70, 229, 0.2); white-space: nowrap;">
                                        <i class="bi bi-stars me-1"></i> Rekomendasi AI S1
                                    </button>
                                </div>
                                <div class="table-responsive">
                                    <table class="table table-hover align-middle table-sm border" style="font-size: 0.8rem;">
                                        <thead class="table-light">
                                            <tr>
                                                <th rowspan="2" class="text-center align-middle" width="50">Kode</th>
                                                <th rowspan="2" class="align-middle">Tujuan Pembelajaran</th>
                                                <th rowspan="2" class="text-center align-middle" width="90">Target JP</th>
                                                <?php 
                                                $monthsS1 = [7 => 'Juli', 8 => 'Agustus', 9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'];
                                                foreach ($monthsS1 as $mNum => $mName): ?>
                                                    <th colspan="5" class="text-center border-bottom" style="background-color: #f8fafc; font-weight: bold;"><?= $mName ?></th>
                                                <?php endforeach; ?>
                                            </tr>
                                            <tr>
                                                <?php foreach ($monthsS1 as $mNum => $mName): ?>
                                                    <?php for ($w = 1; $w <= 5; $w++): ?>
                                                        <th class="text-center p-0 fw-normal text-muted" style="width: 25px; font-size: 0.72rem;">W<?= $w ?></th>
                                                    <?php endfor; ?>
                                                <?php endforeach; ?>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($tps as $index => $tp): 
                                                $tpId = $tp['id'];
                                                $pSemester = $protaMap[$tpId]['semester'] ?? (($index < ceil(count($tps)/2)) ? 1 : 2);
                                                $pHours = $protaMap[$tpId]['allocated_hours'] ?? $tp['allocated_hours'];
                                            ?>
                                            <tr class="promes-row-s1" data-tp-id="<?= $tpId ?>" style="<?= $pSemester != 1 ? 'display: none;' : '' ?>">
                                                <td class="text-center"><strong><?= esc($tp['code']) ?></strong></td>
                                                <td><p class="mb-0 text-truncate" style="max-width: 200px;" title="<?= esc($tp['description']) ?>"><?= esc($tp['description']) ?></p></td>
                                                <td class="text-center">
                                                    <span class="allocated-jp-val d-none"><?= $pHours ?></span>
                                                    <span class="badge bg-indigo text-indigo py-1 px-2 filled-jp-badge">Terisi: 0 / <?= $pHours ?> JP</span>
                                                </td>
                                                <?php foreach ($monthsS1 as $mNum => $mName): 
                                                    $mRpe = $rpeData['sem1'][$mNum] ?? [];
                                                    $totalWeeks = $mRpe['total_weeks'] ?? 4;
                                                    $weekStatuses = $mRpe['week_statuses'] ?? [];
                                                ?>
                                                    <?php for ($w = 1; $w <= 5; $w++): 
                                                        $val = $promesMap[$tpId][$mNum][$w] ?? '';
                                                        
                                                        // Check if this week is effective
                                                        $isEffective = true;
                                                        $reason = '';
                                                        if ($w > $totalWeeks) {
                                                            $isEffective = false;
                                                            $reason = 'Pekan ke-' . $w . ' tidak ada di bulan ini';
                                                        } elseif (!empty($weekStatuses)) {
                                                            $isEffective = (bool)($weekStatuses[$w] ?? ($weekStatuses[(string)$w] ?? false));
                                                            if (!$isEffective) {
                                                                $reason = $mRpe['note'] ?: 'Libur/Non-Efektif';
                                                            }
                                                        } else {
                                                            $effCount = $mRpe['effective_weeks'] ?? 4;
                                                            $isEffective = ($w <= $effCount);
                                                            if (!$isEffective) {
                                                                $reason = $mRpe['note'] ?: 'Libur/Non-Efektif';
                                                            }
                                                        }
                                                    ?>
                                                    <td class="p-1 text-center align-middle <?= !$isEffective ? 'bg-secondary-subtle' : '' ?>" style="<?= !$isEffective ? 'background-color: #f1f5f9 !important;' : '' ?>">
                                                        <?php if ($isEffective): ?>
                                                            <input type="number" name="promes[<?= $tpId ?>][<?= $mNum ?>][<?= $w ?>]" class="form-control text-center p-0 promes-week-input" data-tp-id="<?= $tpId ?>" min="0" max="24" value="<?= $val ?>" style="font-size: 0.75rem; height: 26px; width: 28px; border-radius: 4px;">
                                                        <?php else: ?>
                                                            <input type="text" class="form-control text-center p-0 bg-secondary-subtle border-0" value="-" readonly disabled title="<?= esc($reason) ?>" style="font-size: 0.75rem; height: 26px; width: 28px; border-radius: 4px; color: #94a3b8; cursor: not-allowed;" data-bs-toggle="tooltip">
                                                        <?php endif; ?>
                                                    </td>
                                                    <?php endfor; ?>
                                                <?php endforeach; ?>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                            <!-- Pane 2: Promes Semester 2 -->
                            <div class="tab-pane fade" id="promes2-pane" role="tabpanel" aria-labelledby="promes2-tab">
                                <div class="alert alert-info py-2 px-3 small border-0 mb-3 d-flex align-items-center justify-content-between text-indigo" style="border-radius: 8px; background-color: #eef2ff;">
                                    <div>
                                        <i class="bi bi-info-circle-fill me-1"></i> **Panduan**: Masukkan beban JP mengajar guru untuk masing-masing TP di kolom minggu efektif (Januari s/d Juni) semester 2.
                                    </div>
                                    <button type="button" class="btn btn-xs text-white btn-promes-ai" data-semester="2" style="background: linear-gradient(135deg, #4f46e5 0%, #3730a3 100%); border: none; border-radius: 20px; padding: 4px 12px; font-weight: 600; font-size: 0.75rem; box-shadow: 0 2px 8px rgba(79, 70, 229, 0.2); white-space: nowrap;">
                                        <i class="bi bi-stars me-1"></i> Rekomendasi AI S2
                                    </button>
                                </div>
                                <div class="table-responsive">
                                    <table class="table table-hover align-middle table-sm border" style="font-size: 0.8rem;">
                                        <thead class="table-light">
                                            <tr>
                                                <th rowspan="2" class="text-center align-middle" width="50">Kode</th>
                                                <th rowspan="2" class="align-middle">Tujuan Pembelajaran</th>
                                                <th rowspan="2" class="text-center align-middle" width="90">Target JP</th>
                                                <?php 
                                                $monthsS2 = [1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April', 5 => 'Mei', 6 => 'Juni'];
                                                foreach ($monthsS2 as $mNum => $mName): ?>
                                                    <th colspan="5" class="text-center border-bottom" style="background-color: #f8fafc; font-weight: bold;"><?= $mName ?></th>
                                                <?php endforeach; ?>
                                            </tr>
                                            <tr>
                                                <?php foreach ($monthsS2 as $mNum => $mName): ?>
                                                    <?php for ($w = 1; $w <= 5; $w++): ?>
                                                        <th class="text-center p-0 fw-normal text-muted" style="width: 25px; font-size: 0.72rem;">W<?= $w ?></th>
                                                    <?php endfor; ?>
                                                <?php endforeach; ?>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($tps as $index => $tp): 
                                                $tpId = $tp['id'];
                                                $pSemester = $protaMap[$tpId]['semester'] ?? (($index < ceil(count($tps)/2)) ? 1 : 2);
                                                $pHours = $protaMap[$tpId]['allocated_hours'] ?? $tp['allocated_hours'];
                                            ?>
                                            <tr class="promes-row-s2" data-tp-id="<?= $tpId ?>" style="<?= $pSemester != 2 ? 'display: none;' : '' ?>">
                                                <td class="text-center"><strong><?= esc($tp['code']) ?></strong></td>
                                                <td><p class="mb-0 text-truncate" style="max-width: 200px;" title="<?= esc($tp['description']) ?>"><?= esc($tp['description']) ?></p></td>
                                                <td class="text-center">
                                                    <span class="allocated-jp-val d-none"><?= $pHours ?></span>
                                                    <span class="badge bg-indigo text-indigo py-1 px-2 filled-jp-badge">Terisi: 0 / <?= $pHours ?> JP</span>
                                                </td>
                                                <?php foreach ($monthsS2 as $mNum => $mName): 
                                                    $mRpe = $rpeData['sem2'][$mNum] ?? [];
                                                    $totalWeeks = $mRpe['total_weeks'] ?? 4;
                                                    $weekStatuses = $mRpe['week_statuses'] ?? [];
                                                ?>
                                                    <?php for ($w = 1; $w <= 5; $w++): 
                                                        $val = $promesMap[$tpId][$mNum][$w] ?? '';
                                                        
                                                        // Check if this week is effective
                                                        $isEffective = true;
                                                        $reason = '';
                                                        if ($w > $totalWeeks) {
                                                            $isEffective = false;
                                                            $reason = 'Pekan ke-' . $w . ' tidak ada di bulan ini';
                                                        } elseif (!empty($weekStatuses)) {
                                                            $isEffective = (bool)($weekStatuses[$w] ?? ($weekStatuses[(string)$w] ?? false));
                                                            if (!$isEffective) {
                                                                $reason = $mRpe['note'] ?: 'Libur/Non-Efektif';
                                                            }
                                                        } else {
                                                            $effCount = $mRpe['effective_weeks'] ?? 4;
                                                            $isEffective = ($w <= $effCount);
                                                            if (!$isEffective) {
                                                                $reason = $mRpe['note'] ?: 'Libur/Non-Efektif';
                                                            }
                                                        }
                                                    ?>
                                                    <td class="p-1 text-center align-middle <?= !$isEffective ? 'bg-secondary-subtle' : '' ?>" style="<?= !$isEffective ? 'background-color: #f1f5f9 !important;' : '' ?>">
                                                        <?php if ($isEffective): ?>
                                                            <input type="number" name="promes[<?= $tpId ?>][<?= $mNum ?>][<?= $w ?>]" class="form-control text-center p-0 promes-week-input" data-tp-id="<?= $tpId ?>" min="0" max="24" value="<?= $val ?>" style="font-size: 0.75rem; height: 26px; width: 28px; border-radius: 4px;">
                                                        <?php else: ?>
                                                            <input type="text" class="form-control text-center p-0 bg-secondary-subtle border-0" value="-" readonly disabled title="<?= esc($reason) ?>" style="font-size: 0.75rem; height: 26px; width: 28px; border-radius: 4px; color: #94a3b8; cursor: not-allowed;" data-bs-toggle="tooltip">
                                                        <?php endif; ?>
                                                    </td>
                                                    <?php endfor; ?>
                                                <?php endforeach; ?>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <div class="d-flex justify-content-between border-top pt-4 mt-4">
                            <a href="/guru/learning-devices" class="btn btn-cancel-custom px-4 py-2 fw-medium" style="border-radius: 8px;">
                                <i class="bi bi-x-lg me-1"></i> Batal
                            </a>
                            <button type="submit" class="btn btn-indigo px-4 py-2 fw-semibold" id="btnSubmitPromes" style="border-radius: 8px;">
                                <i class="bi bi-save me-1"></i> Simpan Program Semester
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$(document).ready(function() {
    // Initialize Bootstrap tooltips
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    function calculatePromesSums() {
        $('.promes-week-input').each(function() {
            const tpId = $(this).data('tp-id');
            const row = $(this).closest('tr');
            const allocatedJp = parseInt(row.find('.allocated-jp-val').text()) || 0;
            
            let totalFilled = 0;
            row.find('.promes-week-input').each(function() {
                totalFilled += parseInt($(this).val()) || 0;
            });
            
            const badge = row.find('.filled-jp-badge');
            badge.text(`Terisi: ${totalFilled} / ${allocatedJp} JP`);
            
            if (totalFilled === allocatedJp) {
                badge.removeClass('bg-warning bg-danger bg-indigo').addClass('bg-success');
            } else if (totalFilled > allocatedJp) {
                badge.removeClass('bg-warning bg-success bg-indigo').addClass('bg-danger');
            } else {
                badge.removeClass('bg-success bg-danger bg-indigo').addClass('bg-warning');
            }
        });
    }

    $(document).on('input', '.promes-week-input', function() {
        const row = $(this).closest('tr');
        const allocatedJp = parseInt(row.find('.allocated-jp-val').text()) || 0;
        
        let totalFilled = 0;
        row.find('.promes-week-input').each(function() {
            totalFilled += parseInt($(this).val()) || 0;
        });
        
        const badge = row.find('.filled-jp-badge');
        badge.text(`Terisi: ${totalFilled} / ${allocatedJp} JP`);
        
        if (totalFilled === allocatedJp) {
            badge.removeClass('bg-warning bg-danger').addClass('bg-success');
        } else if (totalFilled > allocatedJp) {
            badge.removeClass('bg-warning bg-success').addClass('bg-danger');
        } else {
            badge.removeClass('bg-success bg-danger').addClass('bg-warning');
        }
    });

    // Run initial sum calculations
    calculatePromesSums();

    $('#promesForm').on('submit', function(e) {
        e.preventDefault();
        const form = $(this);
        const submitBtn = $('#btnSubmitPromes');
        
        let isValid = true;
        $('.promes-row-s1, .promes-row-s2').each(function() {
            if ($(this).is(':visible')) {
                const tpId = $(this).data('tp-id');
                const allocatedJp = parseInt($(this).find('.allocated-jp-val').text()) || 0;
                
                let totalFilled = 0;
                $(this).find('.promes-week-input').each(function() {
                    totalFilled += parseInt($(this).val()) || 0;
                });
                
                if (totalFilled !== allocatedJp) {
                    isValid = false;
                }
            }
        });

        if (!isValid) {
            Swal.fire({
                icon: 'warning',
                title: 'Alokasi JP Tidak Cocok',
                text: 'Ada beberapa TP yang total JP di Program Semester berbeda dengan Target JP dari Prota. Apakah Anda yakin ingin tetap menyimpan?',
                showCancelButton: true,
                confirmButtonColor: '#4f46e5',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Ya, Tetap Simpan',
                cancelButtonText: 'Batal, Perbaiki Dulu'
            }).then((result) => {
                if (result.isConfirmed) {
                    executePromesSave(form, submitBtn);
                }
            });
        } else {
            executePromesSave(form, submitBtn);
        }
    });

    function executePromesSave(form, submitBtn) {
        submitBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span> Menyimpan...');
        $.ajax({
            url: form.attr('action'),
            method: 'POST',
            data: form.serialize(),
            dataType: 'json',
            success: function(res) {
                if (res.status === 'success') {
                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil',
                        text: 'Program Semester berhasil disimpan!',
                        timer: 1500,
                        showConfirmButton: false
                    }).then(() => {
                        window.location.href = '/guru/learning-devices?device_id=<?= $device['id'] ?>';
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Gagal',
                        text: res.message || 'Gagal menyimpan data.',
                        confirmButtonText: 'Tutup'
                    });
                    submitBtn.prop('disabled', false).html('<i class="bi bi-save me-1"></i> Simpan Program Semester');
                }
            },
            error: function() {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Terjadi kesalahan sistem saat menyimpan Promes.',
                    confirmButtonText: 'Tutup'
                });
                submitBtn.prop('disabled', false).html('<i class="bi bi-save me-1"></i> Simpan Program Semester');
            }
        });
    }
    // AI Autocomplete click handler for Promes
    $('.btn-promes-ai').on('click', function() {
        const btn = $(this);
        const semester = btn.data('semester');
        const originalHtml = btn.html();
        
        Swal.fire({
            title: `Gunakan Rekomendasi AI S${semester}?`,
            text: `AI akan menganalisis alokasi JP dari Prota dan mendistribusikannya secara otomatis hanya pada minggu-minggu efektif Semester ${semester}.`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#4f46e5',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Ya, Jalankan AI!',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span> AI mendistribusikan...');
                
                $.ajax({
                    url: `/guru/learning-devices/promes/generate-ai/<?= $device['id'] ?>/${semester}`,
                    type: 'GET',
                    dataType: 'json',
                    success: function(res) {
                        if (res.status === 'success' && Array.isArray(res.data)) {
                            // Clear inputs on active pane first
                            if (semester === 1) {
                                $('#promes1-pane .promes-week-input').val('');
                            } else {
                                $('#promes2-pane .promes-week-input').val('');
                            }
                            
                            // Autofill JP from AI
                            res.data.forEach(function(item) {
                                const input = $(`[name="promes[${item.tp_id}][${item.month}][${item.week_number}]"]`);
                                if (input.length && !input.is(':disabled') && !input.is('[readonly]')) {
                                    input.val(item.allocated_hours);
                                }
                            });
                            
                            calculatePromesSums();
                            
                            Swal.fire({
                                toast: true,
                                position: 'top-end',
                                icon: 'success',
                                title: `Rekomendasi Promes Semester ${semester} berhasil diterapkan!`,
                                showConfirmButton: false,
                                timer: 3000
                            });
                        } else {
                            Swal.fire('Gagal', res.message || 'Gagal menyusun Promes.', 'error');
                        }
                    },
                    error: function() {
                        Swal.fire('Error', 'Terjadi kesalahan sistem saat menghubungi AI.', 'error');
                    },
                    complete: function() {
                        btn.prop('disabled', false).html(originalHtml);
                    }
                });
            }
        });
    });
});
</script>
<?= $this->endSection() ?>
