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

<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
        <div>
            <h1 class="h3 mb-1 text-gray-800 fw-bold">Alur Tujuan Pembelajaran (ATP)</h1>
            <p class="text-muted mb-0 small">Susun dan alokasikan Tujuan Pembelajaran (TP) ke dalam Semester 1 dan Semester 2.</p>
        </div>
        <div class="d-flex gap-2">

            <a href="/guru/learning-devices?device_id=<?= $device['id'] ?>" class="btn btn-sm btn-outline-secondary py-2 px-3" style="border-radius: 8px;">
                <i class="bi bi-arrow-left"></i> Kembali
            </a>
        </div>
    </div>

    <?php if (session()->getFlashdata('error')) : ?>
        <div class="alert alert-danger alert-dismissible fade show border-0 shadow-sm mb-4" role="alert" style="border-radius: 12px; background-color: #f8d7da; color: #842029;">
            <div class="d-flex align-items-center gap-2">
                <i class="bi bi-exclamation-triangle-fill fs-5"></i>
                <div><?= session()->getFlashdata('error') ?></div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <div class="row">
        <!-- Main Workspace -->
        <div class="col-lg-12 mb-4">
            <div class="card shadow-sm border-0 rounded-3">
                <div class="card-header bg-white border-0 pt-4 pb-3 d-flex justify-content-between align-items-center">
                    <div>
                        <h5 class="fw-bold text-dark d-flex align-items-center gap-2 mb-1">
                            <i class="bi bi-arrows-move text-primary fs-4"></i> Susun ATP
                        </h5>
                        <p class="text-muted small mb-0">Tarik dan letakkan (Drag & Drop) baris TP antar kolom semester atau untuk mengubah urutan.</p>
                    </div>
                    <button type="button" class="btn btn-primary px-4 fw-bold shadow-sm" id="btnSaveAtp" style="border-radius: 8px; background: linear-gradient(135deg, #4f46e5 0%, #3b82f6 100%); border: none;">
                        <i class="bi bi-save me-1"></i> Simpan ATP
                    </button>
                </div>
                <div class="card-body p-4 bg-light">
                    <div class="row g-4">
                        
                        <!-- Semester 1 Column -->
                        <div class="col-md-6">
                            <div class="card border-0 shadow-sm h-100" style="border-radius: 12px; border-top: 4px solid #f59e0b;">
                                <div class="card-header bg-white border-bottom-0 pt-3 pb-2 d-flex justify-content-between align-items-center">
                                    <h6 class="fw-bold text-dark mb-0">Semester 1</h6>
                                    <span class="badge bg-warning text-dark px-3 py-2" style="border-radius: 6px;">Total: <span id="totalJpSem1">0</span> JP</span>
                                </div>
                                <div class="card-body p-3 bg-light bg-opacity-50" style="min-height: 400px;">
                                    <div id="listSemester1" class="list-group list-group-flush sortable-list h-100" style="min-height: 50px;">
                                        <?php if (!empty($semester1)): ?>
                                            <?php foreach ($semester1 as $tp): ?>
                                                <div class="list-group-item d-flex align-items-start gap-3 p-3 mb-2 border rounded shadow-sm bg-white tp-item" data-id="<?= $tp['id'] ?>" data-jp="<?= $tp['allocated_hours'] ?>" style="cursor: grab; border-radius: 8px !important;">
                                                    <i class="bi bi-grip-vertical text-muted mt-1 fs-5 drag-handle"></i>
                                                    <div class="flex-grow-1">
                                                        <div class="d-flex justify-content-between align-items-start mb-1">
                                                            <span class="badge bg-primary bg-opacity-10 text-primary fw-bold"><?= esc($tp['code']) ?></span>
                                                            <span class="badge bg-secondary bg-opacity-10 text-secondary border border-secondary border-opacity-25"><?= esc($tp['allocated_hours']) ?> JP</span>
                                                        </div>
                                                        <p class="mb-0 text-dark small" style="line-height: 1.5;"><?= esc($tp['description']) ?></p>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Semester 2 Column -->
                        <div class="col-md-6">
                            <div class="card border-0 shadow-sm h-100" style="border-radius: 12px; border-top: 4px solid #10b981;">
                                <div class="card-header bg-white border-bottom-0 pt-3 pb-2 d-flex justify-content-between align-items-center">
                                    <h6 class="fw-bold text-dark mb-0">Semester 2</h6>
                                    <span class="badge bg-success px-3 py-2" style="border-radius: 6px;">Total: <span id="totalJpSem2">0</span> JP</span>
                                </div>
                                <div class="card-body p-3 bg-light bg-opacity-50" style="min-height: 400px;">
                                    <div id="listSemester2" class="list-group list-group-flush sortable-list h-100" style="min-height: 50px;">
                                        <?php if (!empty($semester2)): ?>
                                            <?php foreach ($semester2 as $tp): ?>
                                                <div class="list-group-item d-flex align-items-start gap-3 p-3 mb-2 border rounded shadow-sm bg-white tp-item" data-id="<?= $tp['id'] ?>" data-jp="<?= $tp['allocated_hours'] ?>" style="cursor: grab; border-radius: 8px !important;">
                                                    <i class="bi bi-grip-vertical text-muted mt-1 fs-5 drag-handle"></i>
                                                    <div class="flex-grow-1">
                                                        <div class="d-flex justify-content-between align-items-start mb-1">
                                                            <span class="badge bg-primary bg-opacity-10 text-primary fw-bold"><?= esc($tp['code']) ?></span>
                                                            <span class="badge bg-secondary bg-opacity-10 text-secondary border border-secondary border-opacity-25"><?= esc($tp['allocated_hours']) ?> JP</span>
                                                        </div>
                                                        <p class="mb-0 text-dark small" style="line-height: 1.5;"><?= esc($tp['description']) ?></p>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?= $this->section('scripts') ?>
<!-- SortableJS -->
<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>

<script>
$(document).ready(function() {

    function calculateJp() {
        let total1 = 0;
        $('#listSemester1 .tp-item').each(function() {
            total1 += parseInt($(this).data('jp')) || 0;
        });
        $('#totalJpSem1').text(total1);

        let total2 = 0;
        $('#listSemester2 .tp-item').each(function() {
            total2 += parseInt($(this).data('jp')) || 0;
        });
        $('#totalJpSem2').text(total2);
    }

    // Initialize Sortable for Semester 1
    new Sortable(document.getElementById('listSemester1'), {
        group: 'shared', // set both lists to same group
        animation: 150,
        handle: '.tp-item',
        ghostClass: 'bg-light',
        onEnd: function (evt) {
            calculateJp();
        }
    });

    // Initialize Sortable for Semester 2
    new Sortable(document.getElementById('listSemester2'), {
        group: 'shared',
        animation: 150,
        handle: '.tp-item',
        ghostClass: 'bg-light',
        onEnd: function (evt) {
            calculateJp();
        }
    });

    // Initial Calculation
    calculateJp();

    // Save Action via AJAX
    $('#btnSaveAtp').on('click', function() {
        const semester1Ids = [];
        $('#listSemester1 .tp-item').each(function() {
            semester1Ids.push($(this).data('id'));
        });

        const semester2Ids = [];
        $('#listSemester2 .tp-item').each(function() {
            semester2Ids.push($(this).data('id'));
        });

        const btn = $(this);
        const originalHtml = btn.html();
        btn.html('<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Menyimpan...').prop('disabled', true);

        $.ajax({
            url: '/guru/learning-devices/atp/save/<?= $device['id'] ?>',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                semester1: semester1Ids,
                semester2: semester2Ids,
                <?= csrf_token() ?>: '<?= csrf_hash() ?>'
            }),
            success: function(res) {
                btn.html(originalHtml).prop('disabled', false);
                if (res.status === 'success') {
                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil',
                        text: res.message,
                        timer: 2000,
                        showConfirmButton: false
                    }).then(() => {
                        window.location.href = '/guru/learning-devices?device_id=<?= $device['id'] ?>';
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Gagal',
                        text: res.message
                    });
                }
            },
            error: function() {
                btn.html(originalHtml).prop('disabled', false);
                Swal.fire({
                    icon: 'error',
                    title: 'Kesalahan Sistem',
                    text: 'Terjadi kesalahan saat menyimpan data.'
                });
            }
        });
    });

});
</script>
<style>
.tp-item.sortable-ghost {
    opacity: 0.5;
    background-color: #f8f9fa !important;
    border: 2px dashed #4f46e5 !important;
}
.tp-item.sortable-drag {
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}
</style>
<?= $this->endSection() ?>

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