@extends('admin.layout')

@section('title', '')

@section('content')
    <div class="card">
        <div class="card-header bg-success text-white">
            <h5 class="mb-0"><i class="bi bi-calendar-check me-1"></i> Periode Aktif</h5>
            <p class="mb-0 small text-white-50">Halaman pengaturan periode aktif masa pembelajaran</p>
        </div>
        <div class="card-body">
                <div class="d-flex justify-content-between mb-3">
                    <div>
                        <p class="mb-0">Daftar Periode Tahun Pelajaran Aktif dan Tidak Aktif</p>
                    </div>
                    <div>
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#tambahPeriodeModal">Tambah Periode Pembelajaran</button>
                    </div>
                </div>

                @if(session('success'))
                    <div class="alert alert-success">{{ session('success') }}</div>
                @endif
                @if($errors->any())
                    <div class="alert alert-danger">
                        <ul class="mb-0">
                            @foreach($errors->all() as $err)
                                <li>{{ $err }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif

                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>NO</th>
                                <th>Tahun Pelajaran</th>
                                <th>Semester</th>
                                <th>Status</th>
                                <th>Dibuat</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($periodes as $p)
                                <tr>
                                    <td>{{ $loop->iteration }}</td>
                                    <td>{{ $p->tahun_pelajaran }}</td>
                                    <td>{{ $p->semester }}</td>
                                    <td>{{ ucfirst($p->status) }}</td>
                                    <td>{{ $p->created_at->format('Y-m-d') }}</td>
                                    <td>
                                        <button class="btn btn-sm btn-primary btn-edit" 
                                            data-id="{{ $p->id }}" 
                                            data-tahun="{{ $p->tahun_pelajaran }}" 
                                            data-semester="{{ $p->semester }}" 
                                            data-status="{{ $p->status }}"
                                            data-bs-toggle="modal" data-bs-target="#editPeriodeModal" title="Edit">
                                            <i class="bi bi-pencil" aria-hidden="true"></i>
                                        </button>

                                        <form action="{{ url('admin/data-umum/periode/' . $p->id) }}" method="POST" class="d-inline" onsubmit="return confirm('Yakin ingin menghapus periode ini?');">
                                            @csrf
                                            @method('DELETE')
                                            <button class="btn btn-sm btn-danger" title="Hapus">
                                                <i class="bi bi-trash" aria-hidden="true"></i>
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="6" class="text-center">Belum ada data periode.</td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>

                @include('admin.data-umum.periode.create')
                @include('admin.data-umum.periode.edit')

                <script>
                    document.addEventListener('DOMContentLoaded', function () {
                        var editButtons = document.querySelectorAll('.btn-edit');
                        editButtons.forEach(function (btn) {
                            btn.addEventListener('click', function () {
                                var id = this.dataset.id;
                                var tahun = this.dataset.tahun;
                                var semester = this.dataset.semester;
                                var status = this.dataset.status;

                                var form = document.getElementById('editPeriodeForm');
                                form.action = '/admin/data-umum/periode/' + id;
                                document.getElementById('edit_tahun_pelajaran').value = tahun;
                                document.getElementById('edit_semester').value = semester;
                                document.getElementById('edit_status').value = status;
                            });
                        });

                        // Helper to show bootstrap alert at top of card
                        function showAlert(message, type = 'success') {
                            var container = document.querySelector('.card-body');
                            var alert = document.createElement('div');
                            alert.className = 'alert alert-' + type;
                            alert.textContent = message;
                            container.insertBefore(alert, container.firstChild);
                            setTimeout(function () { alert.remove(); }, 3000);
                        }

                        // Submit create form via AJAX
                        var createForm = document.getElementById('createPeriodeForm');
                        if (createForm) {
                            createForm.addEventListener('submit', function (e) {
                                e.preventDefault();
                                var fd = new FormData(createForm);
                                fetch(createForm.action, {
                                    method: 'POST',
                                    body: fd,
                                    headers: { 'X-Requested-With': 'XMLHttpRequest' }
                                }).then(function (res) {
                                    if (!res.ok) throw res;
                                    return res.json();
                                }).then(function (data) {
                                    showAlert(data.message || 'Berhasil disimpan', 'success');
                                    setTimeout(function () { location.reload(); }, 800);
                                }).catch(function (err) {
                                    err.json().then(function (e) {
                                        var msg = e.message || 'Terjadi kesalahan';
                                        showAlert(msg, 'danger');
                                    }).catch(function () { showAlert('Terjadi kesalahan', 'danger'); });
                                });
                            });
                        }

                        // Submit edit form via AJAX
                        var editForm = document.getElementById('editPeriodeForm');
                        if (editForm) {
                            editForm.addEventListener('submit', function (e) {
                                e.preventDefault();
                                var fd = new FormData(editForm);
                                var action = editForm.action;
                                fetch(action, {
                                    method: 'POST',
                                    body: fd,
                                    headers: { 'X-Requested-With': 'XMLHttpRequest' }
                                }).then(function (res) {
                                    if (!res.ok) throw res;
                                    return res.json();
                                }).then(function (data) {
                                    showAlert(data.message || 'Berhasil diperbarui', 'success');
                                    setTimeout(function () { location.reload(); }, 800);
                                }).catch(function (err) {
                                    err.json().then(function (e) {
                                        var msg = e.message || 'Terjadi kesalahan';
                                        showAlert(msg, 'danger');
                                    }).catch(function () { showAlert('Terjadi kesalahan', 'danger'); });
                                });
                            });
                        }

                        // Intercept delete forms and call via fetch
                        var deleteForms = document.querySelectorAll('form[method="POST"]');
                        deleteForms.forEach(function (f) {
                            if (f.querySelector('input[name="_method"][value="DELETE"]')) {
                                f.addEventListener('submit', function (e) {
                                    e.preventDefault();
                                    if (!confirm('Yakin ingin menghapus periode ini?')) return;
                                    var token = f.querySelector('input[name="_token"]').value;
                                    fetch(f.action, {
                                        method: 'DELETE',
                                        headers: {
                                            'X-CSRF-TOKEN': token,
                                            'X-Requested-With': 'XMLHttpRequest'
                                        }
                                    }).then(function (res) {
                                        if (!res.ok) throw res;
                                        return res.json();
                                    }).then(function (data) {
                                        showAlert(data.message || 'Berhasil dihapus', 'success');
                                        setTimeout(function () { location.reload(); }, 700);
                                    }).catch(function () {
                                        showAlert('Gagal menghapus', 'danger');
                                    });
                                });
                            }
                        });
                    });
                </script>
        </div>
    </div>
@endsection
