@extends('layouts.guru')

@section('title', 'Kelola Nilai - SIPENA Guru')
@section('page_title', 'Kelola Nilai')

@push('styles')
<style>
    .badge-lulus {
        background-color: #dcfce7;
        color: #16a34a;
    }
    .badge-tidak-lulus {
        background-color: #fee2e2;
        color: #dc2626;
    }
    .grade-badge {
        display: inline-block;
        padding: 4px 10px;
        border-radius: 6px;
        font-weight: bold;
    }
    .grade-a { background-color: #eff6ff; color: #1d4ed8; }
    .grade-b { background-color: #f0fdf4; color: #15803d; }
    .grade-c { background-color: #fffbeb; color: #b45309; }
    .grade-d { background-color: #fef2f2; color: #b91c1c; }

    /* Modal styling matching SIPENA guidelines */
    .modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(15, 23, 42, 0.6);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 2000;
        opacity: 0;
        pointer-events: none;
        transition: all 0.3s ease;
    }
    .modal-overlay.show {
        opacity: 1;
        pointer-events: auto;
    }
    .modal-content {
        background-color: white;
        border-radius: 12px;
        width: 90%;
        max-width: 500px;
        box-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1);
        overflow: hidden;
    }
    .modal-header {
        padding: 16px 24px;
        border-bottom: 1px solid #e2e8f0;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .modal-header h3 {
        font-size: 1.1rem;
        font-weight: 600;
        color: #1e293b;
        margin: 0;
    }
    .modal-header .close-btn {
        background: none;
        border: none;
        font-size: 1.25rem;
        color: #64748b;
        cursor: pointer;
    }
    .modal-footer {
        padding: 16px 24px;
        background-color: #f8fafc;
        border-top: 1px solid #e2e8f0;
        display: flex;
        justify-content: flex-end;
        gap: 12px;
    }

    @media print {
        .sidebar, .topbar, .stats-grid, .card:not(.table-card), .page-header, .filter-card, .btn, .action-buttons, form {
            display: none !important;
        }
        .app-container, .main-content {
            margin: 0 !important;
            padding: 0 !important;
            width: 100% !important;
        }
        .table-card {
            border: none !important;
            box-shadow: none !important;
        }
        .modern-table {
            width: 100% !important;
            border-collapse: collapse !important;
        }
        .modern-table th, .modern-table td {
            border: 1px solid #ddd !important;
            padding: 8px !important;
        }
        .print-header {
            display: block !important;
            text-align: center;
            margin-bottom: 20px;
        }
        .print-header h2 {
            margin: 5px 0;
        }
    }
</style>
@endpush

@section('content')
<!-- Page Header -->
<div class="page-header">
    <h1>Kelola Nilai Siswa</h1>
    <p>Pilih kelas dan mata pelajaran untuk melihat daftar siswa, kemudian input atau edit nilai akademik siswa.</p>
</div>

<!-- Filter Card (Right under Title) -->
<div class="card mb-4 filter-card" style="margin-bottom: 24px;">
    <div class="card-body">
        <form action="{{ route('guru.nilai.index') }}" method="GET" style="display: flex; flex-wrap: wrap; gap: 16px; align-items: flex-end;">
            <div style="flex: 1; min-width: 200px;">
                <label for="kelas_id" style="font-size: 0.9rem; margin-bottom: 6px; display: block; font-weight: 600; color: #475569;">Pilih Kelas</label>
                <select name="kelas_id" id="kelas_id" class="form-control" style="width: 100%; border: 1px solid #cbd5e1; border-radius: 6px; padding: 8px 12px; height: 40px; box-sizing: border-box;">
                    <option value="">-- Pilih Kelas --</option>
                    @foreach($kelas as $k)
                        <option value="{{ $k->id }}" {{ request('kelas_id') == $k->id ? 'selected' : '' }}>Kelas {{ $k->nama_kelas }}</option>
                    @endforeach
                </select>
            </div>

            <div style="flex: 1; min-width: 200px;">
                <label for="mata_pelajaran_id" style="font-size: 0.9rem; margin-bottom: 6px; display: block; font-weight: 600; color: #475569;">Mata Pelajaran</label>
                <select name="mata_pelajaran_id" id="mata_pelajaran_id" class="form-control" style="width: 100%; border: 1px solid #cbd5e1; border-radius: 6px; padding: 8px 12px; height: 40px; box-sizing: border-box;">
                    <option value="">-- Pilih Mata Pelajaran --</option>
                    @foreach($mataPelajaran as $mapel)
                        <option value="{{ $mapel->id }}" {{ request('mata_pelajaran_id') == $mapel->id ? 'selected' : '' }}>{{ $mapel->nama_mapel }}</option>
                    @endforeach
                </select>
            </div>

            <div>
                <button type="submit" class="btn btn-primary" style="height: 40px; display: inline-flex; align-items: center; gap: 8px; border-radius: 6px; border: none; cursor: pointer; background-color: #2563eb; color: #fff; padding: 0 20px; font-weight: 600;"><i class="fa-solid fa-filter"></i> Filter</button>
            </div>
        </form>
    </div>
</div>

@if(request('kelas_id') && request('mata_pelajaran_id'))
    <!-- Stats Grid (Visual insights) -->
    <div class="stats-grid" style="margin-bottom: 24px;">
        <div class="stat-card">
            <div class="stat-icon bg-blue">
                <i class="fa-solid fa-users"></i>
            </div>
            <div class="stat-details">
                <h3>Total Siswa</h3>
                <p class="stat-value">{{ $siswaList->count() }}</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon bg-green">
                <i class="fa-solid fa-circle-check"></i>
            </div>
            <div class="stat-details">
                <h3>Rata-rata Kelas</h3>
                <p class="stat-value">
                    {{ number_format($averageNilai, 1) }}
                </p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon bg-purple">
                <i class="fa-solid fa-user-graduate"></i>
            </div>
            <div class="stat-details">
                <h3>Siswa Lulus (>=70)</h3>
                <p class="stat-value">
                    {{ $existingNilais->filter(fn($nilai) => $nilai->nilai_akhir >= 70)->count() }}
                </p>
            </div>
        </div>
    </div>

    <!-- print-header only visible when printing browser layout -->
    <div class="print-header" style="display: none;">
        <h2>LAPORAN HASIL EVALUASI AKADEMIK SISWA</h2>
        <h3>SIPENA E-LEARNING SD</h3>
        <p>Kelas: {{ $kelas->find(request('kelas_id'))?->nama_kelas }} | Mata Pelajaran: {{ $mataPelajaran->find(request('mata_pelajaran_id'))?->nama_mapel }}</p>
        <hr style="border: 1px solid #333; margin-top: 10px; margin-bottom: 20px;">
    </div>

    <!-- Table Card -->
    <div class="card table-card">
        <div class="card-header" style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 12px;">
            <h3>
                <i class="fa-solid fa-graduation-cap text-primary"></i> 
                Rekap Nilai: Kelas {{ $kelas->find(request('kelas_id'))?->nama_kelas }} - {{ $mataPelajaran->find(request('mata_pelajaran_id'))?->nama_mapel }}
            </h3>
            <div style="display: flex; gap: 10px;">
                <button type="button" class="btn btn-outline" onclick="window.print()" style="height: 36px; padding: 0 16px; font-size: 0.85rem; font-weight: 600; border-radius: 6px; display: inline-flex; align-items: center; gap: 6px; cursor: pointer; border: 1px solid #cbd5e1; background-color: transparent;"><i class="fa-solid fa-print"></i> Cetak PDF / Print</button>
                <button type="button" class="btn btn-outline" onclick="exportToCSV()" style="height: 36px; padding: 0 16px; font-size: 0.85rem; font-weight: 600; border-radius: 6px; display: inline-flex; align-items: center; gap: 6px; cursor: pointer; border: 1px solid #cbd5e1; background-color: transparent;"><i class="fa-solid fa-file-csv"></i> Export CSV</button>
            </div>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="modern-table">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Nama Siswa</th>
                            <th style="text-align: center;">Tugas (30%)</th>
                            <th style="text-align: center;">UTS (30%)</th>
                            <th style="text-align: center;">UAS (40%)</th>
                            <th style="text-align: center;">Nilai Akhir</th>
                            <th style="text-align: center;">Grade</th>
                            <th>Status Kelulusan</th>
                            <th>Catatan Guru</th>
                            <th class="action-buttons">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($siswaList as $index => $siswa)
                            @php
                                $nilai = $existingNilais->get($siswa->id);
                            @endphp
                            <tr>
                                <td>{{ $index + 1 }}</td>
                                <td style="font-weight: 500;">{{ $siswa->name }}</td>
                                <td style="text-align: center;">{{ $nilai?->tugas ?? '-' }}</td>
                                <td style="text-align: center;">{{ $nilai?->uts ?? '-' }}</td>
                                <td style="text-align: center;">{{ $nilai?->uas ?? '-' }}</td>
                                <td style="text-align: center; font-weight: bold; font-size: 1.05rem; color: var(--primary-color);">
                                    {{ $nilai?->nilai_akhir !== null ? number_format($nilai->nilai_akhir, 1) : '-' }}
                                </td>
                                <td style="text-align: center;">
                                    @if($nilai?->grade)
                                        <span class="grade-badge grade-{{ strtolower($nilai->grade) }}">{{ $nilai->grade }}</span>
                                    @else
                                        -
                                    @endif
                                </td>
                                <td>
                                    @if($nilai)
                                        @if($nilai->nilai_akhir >= 70)
                                            <span class="badge badge-lulus"><i class="fa-solid fa-circle-check"></i> Lulus</span>
                                        @else
                                            <span class="badge badge-tidak-lulus"><i class="fa-solid fa-circle-xmark"></i> Remedial</span>
                                        @endif
                                    @else
                                        <span class="badge bg-light text-dark">Belum Diinput</span>
                                    @endif
                                </td>
                                <td style="max-width: 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="{{ $nilai?->catatan }}">
                                    {{ $nilai?->catatan ?? '-' }}
                                </td>
                                <td class="action-buttons">
                                    @if($nilai)
                                        <button type="button" class="btn-icon btn-icon-edit" title="Edit Nilai" 
                                            onclick="openEditModal('{{ $nilai->id }}', '{{ $siswa->id }}', '{{ addslashes($siswa->name) }}', '{{ request('kelas_id') }}', '{{ request('mata_pelajaran_id') }}', '{{ $nilai->tugas }}', '{{ $nilai->uts }}', '{{ $nilai->uas }}', '{{ addslashes($nilai->catatan) }}')">
                                            <i class="fa-solid fa-user-pen"></i>
                                        </button>
                                    @else
                                        <button type="button" class="btn-icon btn-icon-view" title="Input Nilai" 
                                            onclick="openInputModal('{{ $siswa->id }}', '{{ addslashes($siswa->name) }}', '{{ request('kelas_id') }}', '{{ request('mata_pelajaran_id') }}')">
                                            <i class="fa-solid fa-plus-circle"></i>
                                        </button>
                                    @endif
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="10" style="text-align: center; color: #64748b; padding: 20px;">Tidak ada data siswa untuk kelas ini.</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
            
            <!-- print-footer signatures -->
            <div class="print-header" style="display: none; margin-top: 50px;">
                <div style="display: flex; justify-content: space-between; padding: 0 50px;">
                    <div>
                        <p>Mengetahui,</p>
                        <p style="margin-bottom: 60px;">Kepala Sekolah SD SIPENA</p>
                        <p>__________________________</p>
                    </div>
                    <div>
                        <p>Jakarta, {{ now()->translatedFormat('d F Y') }}</p>
                        <p style="margin-bottom: 60px;">Guru Mata Pelajaran</p>
                        <p><strong>{{ auth()->user()->name }}</strong></p>
                    </div>
                </div>
                <div style="margin-top: 30px; font-size: 0.8rem; color: #64748b; text-align: center;">
                    <p>Dicetak oleh: {{ auth()->user()->name }} | Tanggal Cetak: {{ now()->translatedFormat('d F Y') }}</p>
                </div>
            </div>

        </div>
    </div>
@else
    <div class="card" style="text-align: center; padding: 40px; border: 1px dashed #cbd5e1; background: #f8fafc;">
        <i class="fa-solid fa-graduation-cap" style="font-size: 3.5rem; color: #94a3b8; margin-bottom: 16px;"></i>
        <h3 style="color: #475569;">Pilih Filter Kelas & Mata Pelajaran Terlebih Dahulu</h3>
        <p style="color: #64748b; max-width: 400px; margin: 8px auto 0 auto;">Gunakan form filter di atas untuk memuat daftar nama siswa dan rekap nilai akademik mereka.</p>
    </div>
@endif

<!-- Modal Input & Edit Nilai -->
<div class="modal-overlay" id="nilaiModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modal-title">Input Nilai Siswa</h3>
            <button type="button" class="close-btn" onclick="closeModal()">&times;</button>
        </div>
        <form id="nilaiForm" action="" method="POST">
            @csrf
            <input type="hidden" name="_method" id="form-method" value="POST">
            
            <!-- Hidden inputs structure -->
            <input type="hidden" name="siswa_id" id="modal-siswa-id">
            <input type="hidden" name="kelas_id" id="modal-kelas-id">
            <input type="hidden" name="mata_pelajaran_id" id="modal-mapel-id">

            <div class="card-body" style="padding: 24px; display: flex; flex-direction: column; gap: 16px;">
                <div class="form-row" style="display: flex; gap: 12px;">
                    <div class="form-group" style="flex: 1;">
                        <label for="modal-tugas" style="font-weight: 500;">Nilai Tugas (30%) <span class="text-danger">*</span></label>
                        <input type="number" name="tugas" id="modal-tugas" class="form-control" min="0" max="100" placeholder="0-100" required style="width: 100%; border: 1px solid #cbd5e1; border-radius: 6px; padding: 8px 12px; height: 40px; box-sizing: border-box;">
                    </div>
                    <div class="form-group" style="flex: 1;">
                        <label for="modal-uts" style="font-weight: 500;">Nilai UTS (30%) <span class="text-danger">*</span></label>
                        <input type="number" name="uts" id="modal-uts" class="form-control" min="0" max="100" placeholder="0-100" required style="width: 100%; border: 1px solid #cbd5e1; border-radius: 6px; padding: 8px 12px; height: 40px; box-sizing: border-box;">
                    </div>
                    <div class="form-group" style="flex: 1;">
                        <label for="modal-uas" style="font-weight: 500;">Nilai UAS (40%) <span class="text-danger">*</span></label>
                        <input type="number" name="uas" id="modal-uas" class="form-control" min="0" max="100" placeholder="0-100" required style="width: 100%; border: 1px solid #cbd5e1; border-radius: 6px; padding: 8px 12px; height: 40px; box-sizing: border-box;">
                    </div>
                </div>

                <div class="form-group">
                    <label for="modal-catatan" style="font-weight: 500;">Catatan / Feedback Guru</label>
                    <textarea name="catatan" id="modal-catatan" class="form-control" rows="3" placeholder="Contoh: Sangat baik di tugas, tingkatkan fokus saat ujian..." style="width: 100%; border: 1px solid #cbd5e1; border-radius: 6px; padding: 8px 12px; box-sizing: border-box; resize: vertical; min-height: 80px;"></textarea>
                </div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-outline" onclick="closeModal()">Batal</button>
                <button type="submit" class="btn btn-primary" id="submit-btn"><i class="fa-solid fa-save"></i> Simpan Nilai</button>
            </div>
        </form>
    </div>
</div>
@endsection

@push('scripts')
<script>
    function openInputModal(siswaId, siswaName, kelasId, mapelId) {
        document.getElementById('modal-title').innerText = 'Input Nilai - ' + siswaName;
        document.getElementById('nilaiForm').action = "{{ route('guru.nilai.store') }}";
        document.getElementById('form-method').value = 'POST';
        
        document.getElementById('modal-siswa-id').value = siswaId;
        document.getElementById('modal-kelas-id').value = kelasId;
        document.getElementById('modal-mapel-id').value = mapelId;
        
        document.getElementById('modal-tugas').value = '';
        document.getElementById('modal-uts').value = '';
        document.getElementById('modal-uas').value = '';
        document.getElementById('modal-catatan').value = '';
        
        document.getElementById('submit-btn').innerHTML = '<i class="fa-solid fa-save"></i> Simpan Nilai';
        document.getElementById('nilaiModal').classList.add('show');
    }

    function openEditModal(nilaiId, siswaId, siswaName, kelasId, mapelId, tugas, uts, uas, catatan) {
        document.getElementById('modal-title').innerText = 'Edit Nilai - ' + siswaName;
        
        let actionUrl = "{{ route('guru.nilai.update', ':id') }}";
        actionUrl = actionUrl.replace(':id', nilaiId);
        document.getElementById('nilaiForm').action = actionUrl;
        
        document.getElementById('form-method').value = 'PUT';
        
        document.getElementById('modal-siswa-id').value = siswaId;
        document.getElementById('modal-kelas-id').value = kelasId;
        document.getElementById('modal-mapel-id').value = mapelId;
        
        document.getElementById('modal-tugas').value = tugas;
        document.getElementById('modal-uts').value = uts;
        document.getElementById('modal-uas').value = uas;
        document.getElementById('modal-catatan').value = catatan ? catatan : '';
        
        document.getElementById('submit-btn').innerHTML = '<i class="fa-solid fa-save"></i> Perbarui Nilai';
        document.getElementById('nilaiModal').classList.add('show');
    }

    function closeModal() {
        document.getElementById('nilaiModal').classList.remove('show');
    }

    function exportToCSV() {
        let csv = [];
        let rows = document.querySelectorAll("table.modern-table tr");
        for (let i = 0; i < rows.length; i++) {
            let row = [], cols = rows[i].querySelectorAll("td, th");
            for (let j = 0; j < cols.length - 1; j++) { // exclude Aksi
                let data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, "").replace(/(\s\s)/gm, " ").trim();
                data = data.replace(/"/g, '""');
                row.push('"' + data + '"');
            }
            csv.push(row.join(","));
        }
        let csvString = csv.join("\n");
        let filename = 'Rekap_Nilai_Siswa_' + new Date().toLocaleDateString() + '.csv';
        let link = document.createElement("a");
        link.setAttribute("href", "data:text/csv;charset=utf-8,\uFEFF" + encodeURIComponent(csvString));
        link.setAttribute("download", filename);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
</script>
@endpush
