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

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

<style>
.btn-teal {
    background-color: #0d9488 !important;
    border-color: #0d9488 !important;
    color: #fff !important;
    transition: all 0.2s ease-in-out;
}
.btn-teal:hover {
    background-color: #0f766e !important;
    border-color: #0f766e !important;
    color: #fff !important;
    box-shadow: 0 4px 12px rgba(13, 148, 136, 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-calendar2-range text-teal"></i> Program Tahunan (PROTA)
            </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">PROTA</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="protaForm" action="/guru/learning-devices/prota/save/<?= $device['id'] ?>" method="post">
                <?= csrf_field() ?>
                <div class="card shadow-sm border-0 rounded-3">
                    <div class="card-body p-4">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <div>
                                <h5 class="fw-bold mb-1 text-dark">Alokasi Waktu Program Tahunan</h5>
                                <p class="text-muted small mb-0">Tentukan penempatan semester, alokasi minggu efektif, dan jam pelajaran (JP) untuk masing-masing Tujuan Pembelajaran.</p>
                                <button type="button" class="btn btn-sm text-white mt-2" id="btnProtaAi" style="background: linear-gradient(135deg, #0d9488 0%, #0f766e 100%); border: none; border-radius: 20px; padding: 6px 16px; font-weight: 600; font-size: 0.8rem; box-shadow: 0 4px 12px rgba(13, 148, 136, 0.2);">
                                    <i class="bi bi-stars me-1"></i> Rekomendasi AI Prota
                                </button>
                            </div>
                            <div class="d-flex flex-column align-items-end gap-1">
                                <div class="bg-teal bg-opacity-10 text-teal px-3 py-2 rounded font-semibold small" id="rpe-summary-badge" data-s1-rpe="<?= $s1EffectiveWeeks ?>" data-s2-rpe="<?= $s2EffectiveWeeks ?>" data-total-rpe="<?= $totalEffectiveWeeks ?>">
                                    Kaldik RPE: <strong class="text-teal"><?= $totalEffectiveWeeks ?> Pekan</strong> (S1: <?= $s1EffectiveWeeks ?> Mgg, S2: <?= $s2EffectiveWeeks ?> Mgg)
                                </div>
                                <div class="badge rounded bg-secondary px-3 py-2 text-wrap" id="prota-allocation-badge" style="font-size: 0.8rem;">
                                    Alokasi Prota: <span id="prota-alloc-total">0</span> Pekan (S1: <span id="prota-alloc-s1">0</span> Mgg, S2: <span id="prota-alloc-s2">0</span> Mgg)
                                </div>
                            </div>
                        </div>

                        <div class="table-responsive">
                            <table class="table table-hover align-middle table-sm border">
                                <thead class="table-light">
                                    <tr>
                                        <th width="60" class="text-center">No</th>
                                        <th width="100" class="text-center">Kode</th>
                                        <th>Tujuan Pembelajaran (TP)</th>
                                        <th width="180">Semester <span class="text-danger">*</span></th>
                                        <th width="140">Alokasi Minggu <span class="text-danger">*</span></th>
                                        <th width="140">Alokasi JP <span class="text-danger">*</span></th>
                                        <th>Keterangan</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (!empty($tps)): ?>
                                        <?php foreach ($tps as $index => $tp): 
                                            $tpId = $tp['id'];
                                            $pSemester = $protaMap[$tpId]['semester'] ?? (($index < ceil(count($tps)/2)) ? 1 : 2);
                                            $pWeeks = $protaMap[$tpId]['allocated_weeks'] ?? ceil($tp['allocated_hours'] / 4);
                                            $pHours = $protaMap[$tpId]['allocated_hours'] ?? $tp['allocated_hours'];
                                            $pNotes = $protaMap[$tpId]['notes'] ?? '';
                                        ?>
                                        <tr class="prota-row" data-tp-id="<?= $tpId ?>">
                                            <td class="text-center"><?= $index + 1 ?></td>
                                            <td class="text-center"><span class="badge bg-secondary-subtle text-secondary px-2 py-1 fw-bold"><?= esc($tp['code']) ?></span></td>
                                            <td><small class="text-dark fw-medium"><?= esc($tp['description']) ?></small></td>
                                            <td>
                                                <select name="prota[<?= $tpId ?>][semester]" class="form-select form-select-sm select-semester" style="border-radius: 6px;">
                                                    <option value="1" <?= $pSemester == 1 ? 'selected' : '' ?>>Semester 1 (Ganjil)</option>
                                                    <option value="2" <?= $pSemester == 2 ? 'selected' : '' ?>>Semester 2 (Genap)</option>
                                                </select>
                                            </td>
                                            <td>
                                                <div class="input-group input-group-sm">
                                                    <input type="number" name="prota[<?= $tpId ?>][allocated_weeks]" class="form-control text-center input-allocated-weeks" value="<?= $pWeeks ?>" min="0" max="20" style="border-radius: 6px 0 0 6px;">
                                                    <span class="input-group-text small">Mgg</span>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="input-group input-group-sm">
                                                    <input type="number" name="prota[<?= $tpId ?>][allocated_hours]" class="form-control text-center input-allocated-jp" value="<?= $pHours ?>" min="1" max="100" style="border-radius: 6px 0 0 6px;">
                                                    <span class="input-group-text small">JP</span>
                                                </div>
                                            </td>
                                            <td>
                                                 <input type="text" name="prota[<?= $tpId ?>][notes]" class="form-control form-control-sm input-notes" value="<?= esc($pNotes) ?>" placeholder="Keterangan..." style="border-radius: 6px;">
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="7" class="text-center text-muted py-4">Belum ada Tujuan Pembelajaran (TP) yang dirumuskan. Silakan buat TP terlebih dahulu.</td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </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-teal px-4 py-2 fw-semibold" id="btnSubmitProta" style="border-radius: 8px;">
                                <i class="bi bi-save me-1"></i> Simpan Program Tahunan
                            </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() {
    const s1Limit = parseInt($('#rpe-summary-badge').data('s1-rpe')) || 18;
    const s2Limit = parseInt($('#rpe-summary-badge').data('s2-rpe')) || 18;
    const totalLimit = parseInt($('#rpe-summary-badge').data('total-rpe')) || 36;

    function calculateProtaAllocation() {
        let s1Alloc = 0;
        let s2Alloc = 0;

        $('.input-allocated-weeks').each(function() {
            const input = $(this);
            const tr = input.closest('tr');
            const sem = tr.find('.select-semester').val();
            const weeks = parseInt(input.val()) || 0;

            if (sem == 1) {
                s1Alloc += weeks;
            } else if (sem == 2) {
                s2Alloc += weeks;
            }
        });

        const totalAlloc = s1Alloc + s2Alloc;

        $('#prota-alloc-total').text(totalAlloc);
        $('#prota-alloc-s1').text(s1Alloc);
        $('#prota-alloc-s2').text(s2Alloc);

        // Visual validation formatting
        const badge = $('#prota-allocation-badge');
        if (s1Alloc > s1Limit || s2Alloc > s2Limit) {
            badge.removeClass('bg-secondary bg-success').addClass('bg-danger');
            badge.html(`<i class="bi bi-exclamation-triangle-fill me-1"></i> Alokasi Prota: ${totalAlloc} Pekan (S1: ${s1Alloc}/${s1Limit} Mgg, S2: ${s2Alloc}/${s2Limit} Mgg) - MELEBIHI BATAS RPE!`);
        } else if (totalAlloc === totalLimit && s1Alloc === s1Limit && s2Alloc === s2Limit) {
            badge.removeClass('bg-secondary bg-danger').addClass('bg-success');
            badge.html(`<i class="bi bi-check-circle-fill me-1"></i> Alokasi Prota Sesuai RPE: ${totalAlloc} Pekan (S1: ${s1Alloc} Mgg, S2: ${s2Alloc} Mgg)`);
        } else {
            badge.removeClass('bg-danger bg-success').addClass('bg-secondary');
            badge.html(`Alokasi Prota: ${totalAlloc} Pekan (S1: ${s1Alloc}/${s1Limit} Mgg, S2: ${s2Alloc}/${s2Limit} Mgg)`);
        }
    }

    $(document).on('change', '.select-semester', function() {
        calculateProtaAllocation();
    });

    $(document).on('input', '.input-allocated-weeks', function() {
        calculateProtaAllocation();
    });

    // Run initial calculation
    calculateProtaAllocation();

    $('#protaForm').on('submit', function(e) {
        e.preventDefault();
        const form = $(this);
        const submitBtn = $('#btnSubmitProta');
        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 Tahunan 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 Tahunan');
                }
            },
            error: function() {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Terjadi kesalahan sistem saat menyimpan Prota.',
                    confirmButtonText: 'Tutup'
                });
                submitBtn.prop('disabled', false).html('<i class="bi bi-save me-1"></i> Simpan Program Tahunan');
            }
        });
    });
    // AI Autocomplete click handler
    $('#btnProtaAi').on('click', function() {
        const btn = $(this);
        const originalHtml = btn.html();
        
        Swal.fire({
            title: 'Gunakan Rekomendasi AI?',
            text: 'AI akan menganalisis Tujuan Pembelajaran dan Kalender Akademik untuk membagi alokasi semester, minggu, dan JP secara otomatis.',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#0d9488',
            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> Menganalisis dengan AI...');
                
                $.ajax({
                    url: '/guru/learning-devices/prota/generate-ai/<?= $device['id'] ?>',
                    type: 'GET',
                    dataType: 'json',
                    success: function(res) {
                        if (res.status === 'success' && Array.isArray(res.data)) {
                            res.data.forEach(function(item) {
                                const row = $(`.prota-row[data-tp-id="${item.tp_id}"]`);
                                if (row.length) {
                                    row.find('.select-semester').val(item.semester);
                                    row.find('.input-allocated-weeks').val(item.allocated_weeks);
                                    row.find('.input-allocated-jp').val(item.allocated_hours);
                                    row.find('.input-notes').val(item.notes);
                                }
                            });
                            
                            calculateProtaAllocation();
                            
                            Swal.fire({
                                toast: true,
                                position: 'top-end',
                                icon: 'success',
                                title: 'Rekomendasi Prota AI berhasil diterapkan!',
                                showConfirmButton: false,
                                timer: 3000
                            });
                        } else {
                            Swal.fire('Gagal', res.message || 'Gagal merumuskan Prota.', 'error');
                        }
                    },
                    error: function() {
                        Swal.fire('Error', 'Terjadi kesalahan sistem saat menghubungi AI.', 'error');
                    },
                    complete: function() {
                        btn.prop('disabled', false).html(originalHtml);
                    }
                });
            }
        });
    });
});
</script>
<?= $this->endSection() ?>
