@extends('adminlte::page')

@section('title', 'Pengesahan Permohonan')

@section('content_header')
    <div class="d-flex justify-content-between align-items-center">
        <h1><i class="fas fa-check-double mr-2"></i>Pengesahan Permohonan</h1>
    </div>
@stop

@section('content')
    @if (session('success'))
        <div class="alert alert-success alert-dismissible">
            <button type="button" class="close" data-dismiss="alert">&times;</button>
            <i class="fas fa-check-circle mr-2"></i>{{ session('success') }}
        </div>
    @endif
    @if (session('error'))
        <div class="alert alert-danger alert-dismissible">
            <button type="button" class="close" data-dismiss="alert">&times;</button>
            <i class="fas fa-times-circle mr-2"></i>{{ session('error') }}
        </div>
    @endif

    {{-- Pilihan Tahun --}}
    <div class="d-flex align-items-center mb-3">
        <label class="mr-2 mb-0 font-weight-bold"><i class="fas fa-calendar-alt mr-1"></i>Tahun:</label>
        <form method="GET" action="{{ route('pemohon.pengesahan.index') }}" class="d-flex" id="formTahun">
            <select name="tahun" class="form-control form-control-sm mr-2" style="width:auto" id="selectTahun">
                @for ($y = 2026; $y <= 2040; $y++)
                    <option value="{{ $y }}" {{ $tahun == $y ? 'selected' : '' }}>{{ $y }}</option>
                @endfor
            </select>
        </form>
    </div>

    {{-- Kad Ringkasan Per Jenis Sekolah --}}
    @foreach ($dataPerJenis as $jenisData)
        @php
            $jenisSekolah = $jenisData['jenis_sekolah'];
            $data = $jenisData['data'];
            $totalDarjah = $jenisData['totalDarjah'];
            $selesaiCount = $jenisData['selesaiCount'];
            $progressPct = $jenisData['progressPct'];
            $semua_selesai = $jenisData['semua_selesai'];
            $pengesahan = $jenisData['pengesahan'];
        @endphp

        <div class="card card-outline card-primary mb-4">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-school mr-1"></i>
                    <strong>{{ $jenisSekolah }}</strong>
                    <span
                        class="badge badge-{{ $semua_selesai ? 'success' : ($selesaiCount > 0 ? 'warning' : 'secondary') }} ml-2">
                        {{ $selesaiCount }} / {{ $totalDarjah }} Darjah
                    </span>
                    @if ($pengesahan)
                        <span class="badge badge-success ml-1"><i class="fas fa-check mr-1"></i>Telah Dihantar</span>
                    @endif
                </h3>
            </div>
            <div class="card-body">
                {{-- Progress Bar --}}
                <div class="d-flex justify-content-between mb-1">
                    <small class="font-weight-bold">Status Pengisian {{ $jenisSekolah }}</small>
                    <small class="font-weight-bold">{{ $progressPct }}%</small>
                </div>
                <div class="progress mb-3" style="height:12px">
                    <div class="progress-bar progress-bar-striped progress-bar-animated
                        {{ $progressPct == 100 ? 'bg-success' : 'bg-primary' }}"
                        style="width:{{ $progressPct }}%" role="progressbar">
                        {{ $progressPct }}%
                    </div>
                </div>

                {{-- Senarai Darjah --}}
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="mb-0 text-uppercase font-weight-bold text-muted" style="letter-spacing:.05em">
                        <i class="fas fa-layer-group mr-1"></i> Senarai Darjah
                    </h6>
                </div>

                @foreach ($data as $item)
                    @php $collapseId = 'collapse-' . Str::slug($jenisSekolah) . '-' . Str::slug($item['darjah']); @endphp
                    <div class="card card-outline card-{{ $item['selesai'] ? 'success' : 'secondary' }} mb-2">
                        <div class="card-header py-2" style="cursor:pointer" data-toggle="collapse"
                            data-target="#{{ $collapseId }}">
                            <h3 class="card-title" style="font-size:.9rem">
                                <i
                                    class="fas fa-{{ $item['selesai'] ? 'check-circle text-success' : 'circle text-secondary' }} mr-2"></i>
                                <strong>{{ $item['darjah'] }}</strong>
                                @if ($item['selesai'])
                                    <span class="badge badge-success ml-2">Selesai</span>
                                @else
                                    <span class="badge badge-secondary ml-2">Belum Daftar</span>
                                @endif
                            </h3>
                            <div class="card-tools">
                                @if (!$item['selesai'])
                                    <a href="{{ route('pemohon.jumlah-buku.index', ['darjah' => $item['darjah'], 'tahun' => $tahun, 'jenis_sekolah' => $jenisSekolah]) }}"
                                        class="btn btn-sm btn-primary" onclick="event.stopPropagation()">
                                        <i class="fas fa-edit mr-1"></i> Daftar
                                    </a>
                                @endif
                                <button type="button" class="btn btn-tool" onclick="event.stopPropagation()">
                                    <i class="fas fa-plus collapse-icon"></i>
                                </button>
                            </div>
                        </div>
                        <div class="collapse" id="{{ $collapseId }}">
                            <div class="card-body p-0">
                                @if ($item['maklumat']->isNotEmpty())
                                    <table class="table table-sm table-bordered mb-0">
                                        <thead class="thead-light">
                                            <tr>
                                                <th>Kod Buku</th>
                                                <th>Judul</th>
                                                <th class="text-center">Buku di
                                                    Tangan<br><small>{{ $tahun }}</small></th>
                                                <th class="text-center">Unjuran<br><small>{{ $tahun + 1 }}</small></th>
                                                <th class="text-center">Baki BOSS<br><small>{{ $tahun }}</small>
                                                </th>
                                                <th class="text-center">Elok BOSS<br><small>{{ $tahun }}</small>
                                                </th>
                                                <th class="text-center">Angg. Elok<br><small>{{ $tahun }}</small>
                                                </th>
                                                <th class="text-center" style="background:#f0fff4">Stok
                                                    Akhir<br><small>{{ $tahun }}</small></th>
                                                <th class="text-center" style="background:#f0fff4">Elok
                                                    Akhir<br><small>{{ $tahun }}</small></th>
                                                <th class="text-center" style="background:#f0fff4">
                                                    Pesanan<br><small>{{ $tahun + 1 }}</small></th>
                                                <th class="text-center" style="background:#f0fff4">
                                                    Lebih<br><small>{{ $tahun + 1 }}</small></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach ($item['maklumat'] as $m)
                                                <tr>
                                                    <td><span class="badge badge-primary">{{ $m->kod_buku }}</span></td>
                                                    <td>{{ $m->judul }}</td>
                                                    <td class="text-center font-weight-bold">
                                                        {{ number_format($m->buku_di_tangan_murid) }}</td>
                                                    <td class="text-center font-weight-bold text-info">
                                                        {{ number_format($m->unjuran_enrolmen) }}</td>
                                                    <td class="text-center">{{ number_format($m->baki_buku_boss) }}</td>
                                                    <td class="text-center">{{ number_format($m->buku_elok_boss) }}</td>
                                                    <td class="text-center">
                                                        {{ number_format($m->anggaran_buku_elok_tangan) }}</td>
                                                    <td class="text-center font-weight-bold" style="background:#f0fff4">
                                                        {{ number_format($m->stok_hingga_akhir) }}</td>
                                                    <td class="text-center font-weight-bold" style="background:#f0fff4">
                                                        {{ number_format($m->elok_hingga_akhir) }}</td>
                                                    <td class="text-center font-weight-bold text-danger"
                                                        style="background:#f0fff4">{{ number_format($m->pesanan_buku) }}
                                                    </td>
                                                    <td class="text-center font-weight-bold text-success"
                                                        style="background:#f0fff4">{{ number_format($m->lebihan_buku) }}
                                                    </td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                @else
                                    <p class="text-muted mb-0 p-3"><small>Belum didaftarkan.</small></p>
                                @endif
                            </div>
                        </div>
                    </div>
                @endforeach

                {{-- Bahagian Hantar Pengesahan untuk jenis sekolah ini --}}
                @if ($pengesahan)
                    <div class="alert alert-success mt-3 mb-0 text-center">
                        <i class="fas fa-check-circle fa-2x mb-2"></i><br>
                        <strong>Pengesahan {{ $jenisSekolah }} Telah Dihantar</strong><br>
                        <small>Dihantar pada:
                            {{ \Carbon\Carbon::parse($pengesahan->dihantar_pada)->format('d/m/Y H:i') }}</small>
                    </div>
                @elseif ($semua_selesai)
                    <div class="border rounded p-3 mt-3 bg-light">
                        <h6 class="font-weight-bold text-dark mb-2"><i class="fas fa-file-signature mr-1"></i> Perakuan
                            Pemohon ({{ $jenisSekolah }})</h6>
                        <p class="mb-2 text-justify" style="line-height:1.8;font-size:.9rem">
                            Saya <strong>({{ Auth::user()->name }})</strong> mengesahkan bahawa segala maklumat bagi
                            <strong>{{ $jenisSekolah }}</strong> tahun <strong>{{ $tahun }}</strong> adalah benar,
                            tepat, dan lengkap.
                        </p>
                        <form method="POST" action="{{ route('pemohon.pengesahan.hantar') }}">
                            @csrf
                            <input type="hidden" name="tahun" value="{{ $tahun }}">
                            <input type="hidden" name="jenis_sekolah" value="{{ $jenisSekolah }}">
                            <div class="form-check mb-2">
                                <input class="form-check-input chk-disclaimer" type="checkbox" name="disclaimer"
                                    id="chkDisclaimer_{{ Str::slug($jenisSekolah) }}" value="1">
                                <label class="form-check-label font-weight-bold"
                                    for="chkDisclaimer_{{ Str::slug($jenisSekolah) }}">
                                    Saya bersetuju dan mengesahkan maklumat {{ $jenisSekolah }} adalah benar.
                                </label>
                            </div>
                            <button type="submit" class="btn btn-primary btn-hantar" disabled>
                                <i class="fas fa-paper-plane mr-1"></i> Hantar Pengesahan {{ $jenisSekolah }}
                            </button>
                        </form>
                    </div>
                @else
                    <div class="alert alert-warning mt-3 mb-0 text-center">
                        <i class="fas fa-exclamation-triangle mr-1"></i>
                        Masih terdapat <strong>{{ $totalDarjah - $selesaiCount }} darjah</strong> belum selesai untuk
                        {{ $jenisSekolah }}.
                    </div>
                @endif
            </div>
        </div>
    @endforeach

@stop

@push('js')
    <script>
        // Tahun dropdown — hanya boleh pilih tahun semasa
        (function() {
            var sel = document.getElementById('selectTahun');
            var tahunSemasa = {{ (int) date('Y') }};
            if (sel) {
                sel.addEventListener('change', function() {
                    if (parseInt(this.value) !== tahunSemasa) {
                        this.value = tahunSemasa;
                        if (typeof toastr !== 'undefined') {
                            toastr.warning('Anda hanya boleh melihat data untuk tahun semasa (' + tahunSemasa +
                                ').', 'Tidak Dibenarkan');
                        } else {
                            alert('Anda hanya boleh melihat data untuk tahun semasa (' + tahunSemasa + ').');
                        }
                        return;
                    }
                    document.getElementById('formTahun').submit();
                });
            }
        })();

        // Enable submit button when disclaimer is checked (per jenis sekolah)
        document.querySelectorAll('.chk-disclaimer').forEach(function(chk) {
            chk.addEventListener('change', function() {
                var btn = this.closest('form').querySelector('.btn-hantar');
                if (btn) btn.disabled = !this.checked;
            });
        });

        // Update collapse icon when panel is toggled
        document.querySelectorAll('[data-toggle="collapse"]').forEach(function(header) {
            var targetId = header.getAttribute('data-target');
            var target = document.querySelector(targetId);
            if (!target) return;
            var icon = header.querySelector('.collapse-icon');

            target.addEventListener('show.bs.collapse', function() {
                if (icon) {
                    icon.classList.remove('fa-plus');
                    icon.classList.add('fa-minus');
                }
            });
            target.addEventListener('hide.bs.collapse', function() {
                if (icon) {
                    icon.classList.remove('fa-minus');
                    icon.classList.add('fa-plus');
                }
            });
        });
    </script>
@endpush
