@extends('layouts.app')

@section('content')

<style>
    /* --- 1. Global Dark Mode & Modern Overrides --- */
    .modern-card {
        background-color: var(--bg-card, #1e293b);
        border: 1px solid var(--border-color, #334155);
        border-radius: 20px;
    }
    
    [data-theme="dark"] .card,
    [data-theme="dark"] .modal-content {
        background-color: var(--bg-card);
        border: 1px solid var(--border-color);
        color: var(--text-main);
        border-radius: 24px;
    }
    
    [data-theme="dark"] .card-header,
    [data-theme="dark"] .modal-header,
    [data-theme="dark"] .modal-footer { border-color: var(--border-color); }
    [data-theme="dark"] .modal-header { border-top-left-radius: 24px; border-top-right-radius: 24px; }

    /* 2. Form Input & Select */
    [data-theme="dark"] .form-control,
    [data-theme="dark"] .form-select {
        background-color: var(--hover-bg);
        border-color: var(--border-color);
        color: var(--text-main);
        border-radius: 12px;
        line-height: 1.4;
    }

    [data-theme="dark"] .form-control:focus,
    [data-theme="dark"] .form-select:focus {
        background-color: rgba(255,255,255,0.08);
        color: var(--text-main);
        border-color: var(--primary-color);
        box-shadow: 0 0 0 0.25rem rgba(67, 97, 238, 0.25);
    }
    
    [data-theme="dark"] .form-control::placeholder { color: var(--text-muted); opacity: 0.7; }
    [data-theme="dark"] .text-muted { color: #cbd5e1 !important; }

    /* 3. Typography & Labels */
    [data-theme="dark"] h2, 
    [data-theme="dark"] h5, 
    [data-theme="dark"] strong,
    [data-theme="dark"] .form-label { color: var(--text-main); }

    /* 4. Tabel Dark Mode */
    [data-theme="dark"] .table { color: var(--text-main); border-color: var(--border-color); }
    [data-theme="dark"] .table-light th {
        background-color: rgba(255,255,255,0.03) !important;
        color: var(--text-main);
        border-color: var(--border-color) !important;
    }
    [data-theme="dark"] .table-hover tbody tr:hover { background-color: rgba(255, 255, 255, 0.03); color: var(--text-main); }

    /* 5. Tombol Close Modal */
    [data-theme="dark"] .btn-close { filter: invert(1) grayscale(100%) brightness(200%); }

    /* 6. Komponen Kustom: Checkbox List */
    .checkbox-list-container {
        max-height: 250px; 
        overflow-y: auto;
        border: 1px solid var(--border-color, #dee2e6);
        border-radius: 16px;
        padding: 15px 20px;
        background-color: rgba(0,0,0,0.01); 
        color: var(--text-main, #212529); 
    }
    
    /* Custom Scrollbar untuk Checkbox List */
    .checkbox-list-container::-webkit-scrollbar { width: 6px; }
    .checkbox-list-container::-webkit-scrollbar-thumb { background: var(--border-color, #cbd5e1); border-radius: 10px; }

    [data-theme="dark"] .checkbox-list-container {
        background-color: rgba(0,0,0,0.15);
        border-color: var(--border-color);
        color: var(--text-main);
    }
    [data-theme="dark"] .form-check-label { color: var(--text-main) !important; }
    
    .form-check-label {
        margin-left: 8px;
        cursor: pointer;
        user-select: none;
        font-size: 0.95rem;
    }
    .form-check-input { cursor: pointer; width: 1.2rem; height: 1.2rem; margin-top: 0.2rem; }

    /* Tombol Rounded */
    .btn-pill { border-radius: 50rem !important; }
</style>

<div class="container py-4">
    {{-- HEADER HALAMAN --}}
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="fw-bold text-white">Manajemen Pengguna</h2>
            <p class="text-muted mb-0">Atur hak akses Super Admin, Admin Mapel, dan Guru.</p>
        </div>
        <button class="btn btn-primary btn-pill px-4 fw-bold shadow-sm" onclick="openModalTambah()">
            <i class="bi bi-person-plus-fill me-1"></i> Tambah Pengguna
        </button>
    </div>

    {{-- ALERT NOTIFIKASI --}}
    @if(session('success'))
        <div class="alert alert-success alert-dismissible fade show rounded-4 bg-success bg-opacity-25 border-0 border-start border-success border-4 text-white shadow-sm">
            <i class="bi bi-check-circle-fill me-2"></i> {{ session('success') }}
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="alert"></button>
        </div>
    @endif

    @if($errors->any())
        <div class="alert alert-danger alert-dismissible fade show rounded-4 bg-danger bg-opacity-25 border-0 border-start border-danger border-4 text-white shadow-sm">
            <ul class="mb-0">
                @foreach($errors->all() as $err) 
                    <li><i class="bi bi-exclamation-triangle me-1"></i> {{ $err }}</li> 
                @endforeach
            </ul>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="alert" style="position: absolute; top: 50%; right: 1rem; transform: translateY(-50%);"></button>
        </div>
    @endif

    {{-- TABEL PENGGUNA --}}
    <div class="card modern-card shadow-sm border-secondary overflow-hidden">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0 text-white">
                    <thead class="table-light">
                        <tr>
                            <th class="py-3 px-4" width="5%">No</th>
                            <th class="py-3" width="20%">Nama Pengguna</th>
                            <th class="py-3" width="15%">NIP</th>
                            <th class="py-3" width="15%">Username</th> 
                            <th class="py-3" width="15%">Role / Peran</th>
                            <th class="py-3" width="20%">Mapel Diampu</th>
                            <th class="py-3 text-center px-4" width="10%">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($users as $user)
                        <tr>
                            <td class="px-4 border-secondary text-muted">{{ $loop->iteration }}</td>
                            <td class="fw-bold border-secondary text-white">{{ $user->name }}</td>
                            <td class="border-secondary text-light">{{ $user->nip ?? '-' }}</td> 
                            <td class="border-secondary text-light">{{ $user->username }}</td> 
                            <td class="border-secondary">
                                @if($user->role == 'super_admin')
                                    <span class="badge bg-danger bg-opacity-25 text-danger border border-danger rounded-pill px-3 py-2">Super Admin</span>
                                @elseif($user->role == 'admin_mapel')
                                    <span class="badge bg-warning bg-opacity-25 text-warning border border-warning rounded-pill px-3 py-2">Admin Mapel</span>
                                @else
                                    <span class="badge bg-success bg-opacity-25 text-success border border-success rounded-pill px-3 py-2">Guru Mapel</span>
                                @endif
                            </td>
                            <td class="border-secondary">
                                @if($user->subjects && $user->subjects->count() > 0)
                                    <div class="d-flex flex-wrap gap-1">
                                        @foreach($user->subjects as $sub)
                                            <span class="badge bg-info bg-opacity-25 text-info border border-info rounded-pill px-2 py-1 mb-1">
                                                {{ $sub->name ?? $sub->nama_mapel ?? 'Tanpa Nama' }}
                                            </span>
                                        @endforeach
                                    </div>
                                @else
                                    <span class="text-muted small fst-italic">-</span>
                                @endif
                            </td>
                            <td class="text-center px-4 border-secondary text-nowrap">
                                <div class="d-flex justify-content-center gap-2">
                                    <button class="btn btn-sm btn-outline-warning rounded-circle" style="width:35px; height:35px;" onclick='openModalEdit(@json($user))' title="Edit Pengguna">
                                        <i class="bi bi-pencil-square"></i>
                                    </button>
                                    
                                    @if($user->role !== 'super_admin')
                                        <form action="{{ route('pengguna.destroy', $user->id) }}" method="POST" class="d-inline" onsubmit="return confirm('Apakah Anda yakin ingin menghapus user ini?')">
                                            @csrf @method('DELETE')
                                            <button class="btn btn-sm btn-outline-danger rounded-circle" style="width:35px; height:35px;" title="Hapus Pengguna">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </form>
                                    @else
                                        <button class="btn btn-sm btn-secondary rounded-circle opacity-25" style="width:35px; height:35px;" disabled title="Super Admin tidak bisa dihapus">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    @endif
                                </div>
                            </td>
                        </tr>
                        @empty
                        <tr>
                            <td colspan="7" class="text-center py-5 border-0">
                                <div class="text-muted opacity-50 mb-3"><i class="bi bi-people" style="font-size: 4rem;"></i></div>
                                <h5 class="text-white fw-bold">Belum ada data pengguna.</h5>
                                <p class="text-muted">Klik tombol "Tambah Pengguna" untuk menambahkan guru atau admin baru.</p>
                            </td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

{{-- MODAL TAMBAH & EDIT PENGGUNA --}}
<div class="modal fade" id="modalUser" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content border-secondary shadow-lg rounded-4">
            <div id="modalHeader" class="modal-header bg-primary border-0 rounded-top-4 py-3">
                <h5 class="modal-title fw-bold text-white" id="modalTitle"><i class="bi bi-person-plus me-2"></i> Tambah Pengguna</h5>
                <button type="button" class="btn-close btn-close-white" id="modalCloseBtn" data-bs-dismiss="modal"></button>
            </div>
            
            <form id="formUser" method="POST">
                @csrf
                <div id="methodPut"></div>
                
                <div class="modal-body p-4">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold small text-muted text-uppercase">Nama Lengkap <span class="text-danger">*</span></label>
                            <input type="text" name="name" id="inputName" class="form-control rounded-4 py-2" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold small text-muted text-uppercase">Username <span class="text-danger">*</span></label>
                            <input type="text" name="username" id="inputUsername" class="form-control rounded-4 py-2" placeholder="Contoh: guru_mtk" required>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold small text-muted text-uppercase">NIP (Opsional)</label>
                            <input type="number" name="nip" id="inputNip" class="form-control rounded-4 py-2" placeholder="Nomor Induk Pegawai">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold small text-muted text-uppercase">Role (Hak Akses) <span class="text-danger">*</span></label>
                            <select name="role" id="selectRole" class="form-select rounded-4 py-2" onchange="toggleSubject()">
                                <option value="guru_mapel">Guru Mapel</option>
                                <option value="admin_mapel">Admin Mapel (Ketua Jurusan)</option>
                                <option value="super_admin">Super Administrator</option>
                            </select>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-bold small text-muted text-uppercase">Password <span id="passHint" class="text-danger">*</span></label>
                        <input type="password" name="password" class="form-control rounded-4 py-2" placeholder="Masukkan password">
                        <small class="text-info mt-1 d-block" id="passNote"><i class="bi bi-info-circle me-1"></i> Minimal 6 karakter.</small>
                    </div>

                    {{-- AREA MAPEL (Dinamis: Muncul untuk Guru & Admin Mapel) --}}
                    <div class="mb-2" id="wrapperSubject">
                        <label class="form-label fw-bold small text-muted text-uppercase">Mata Pelajaran yang Diampu</label>
                        <div class="checkbox-list-container">
                            <div class="row">
                                @foreach($allSubjects as $subject)
                                    <div class="col-md-6 mb-2">
                                        <div class="form-check d-flex align-items-center">
                                            <input class="form-check-input subject-checkbox mt-0 me-2" type="checkbox" name="subjects[]" value="{{ $subject->id }}" id="chk_{{ $subject->id }}">
                                            <label class="form-check-label text-light w-100" for="chk_{{ $subject->id }}">
                                                {{ $subject->name ?? $subject->nama_mapel ?? 'Tanpa Nama' }}
                                            </label>
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                        </div>
                        <small class="text-warning d-block mt-2"><i class="bi bi-lightbulb me-1"></i> Centang mata pelajaran yang diajarkan (Bisa lebih dari satu).</small>
                    </div>

                </div>
                <div class="modal-footer border-0 py-3" style="background-color: rgba(255,255,255,0.02);">
                    <button type="button" class="btn btn-outline-light btn-pill px-4" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary btn-pill px-5 fw-bold shadow-sm" id="btnSubmitModal">
                        <i class="bi bi-save me-1"></i> Simpan
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    function getModal() {
        var el = document.getElementById('modalUser');
        if (typeof bootstrap !== 'undefined') {
            var instance = bootstrap.Modal.getInstance(el);
            if (instance) return instance;
            return new bootstrap.Modal(el);
        }
        return null;
    }

    function toggleSubject() {
        var role = document.getElementById('selectRole').value;
        var wrapperSubject = document.getElementById('wrapperSubject');
        var checkboxes = document.querySelectorAll('.subject-checkbox'); 
        
        if (role === 'guru_mapel' || role === 'admin_mapel') {
            wrapperSubject.style.display = 'block';
            checkboxes.forEach(chk => chk.disabled = false);
        } else {
            wrapperSubject.style.display = 'none';
            checkboxes.forEach(chk => chk.disabled = true);
        }
    }

    function openModalTambah() {
        document.getElementById('formUser').action = "{{ route('pengguna.store') }}";
        
        // Atur UI Modal untuk Mode Tambah
        document.getElementById('modalHeader').className = 'modal-header bg-primary border-0 rounded-top-4 py-3';
        document.getElementById('modalTitle').innerHTML = '<i class="bi bi-person-plus me-2"></i> Tambah Pengguna Baru';
        document.getElementById('modalTitle').className = 'modal-title fw-bold text-white';
        document.getElementById('modalCloseBtn').className = 'btn-close btn-close-white';
        document.getElementById('btnSubmitModal').className = 'btn btn-primary btn-pill px-5 fw-bold shadow-sm';
        
        document.getElementById('methodPut').innerHTML = ""; 
        document.getElementById('passHint').style.display = 'inline'; 
        document.getElementById('passNote').innerHTML = '<i class="bi bi-info-circle me-1"></i> Minimal 6 karakter.';
        document.getElementById('passNote').className = 'text-info mt-1 d-block';
        
        document.getElementById('inputName').value = "";
        document.getElementById('inputUsername').value = "";
        document.getElementById('inputNip').value = "";
        document.getElementById('selectRole').value = "guru_mapel";
        
        // Reset Checkbox
        var checkboxes = document.querySelectorAll('.subject-checkbox');
        checkboxes.forEach(chk => chk.checked = false);
        
        toggleSubject();
        
        var modal = getModal();
        if(modal) modal.show();
    }

    function openModalEdit(user) {
        var url = "{{ route('pengguna.update', ':id') }}";
        url = url.replace(':id', user.id);
        document.getElementById('formUser').action = url;
        
        // Atur UI Modal untuk Mode Edit
        document.getElementById('modalHeader').className = 'modal-header bg-warning border-0 rounded-top-4 py-3';
        document.getElementById('modalTitle').innerHTML = '<i class="bi bi-pencil-square me-2"></i> Edit Pengguna';
        document.getElementById('modalTitle').className = 'modal-title fw-bold text-dark';
        document.getElementById('modalCloseBtn').className = 'btn-close'; // hitam (tanpa btn-close-white)
        document.getElementById('btnSubmitModal').className = 'btn btn-warning btn-pill px-5 fw-bold text-dark shadow-sm';

        document.getElementById('methodPut').innerHTML = '<input type="hidden" name="_method" value="PUT">';
        document.getElementById('passHint').style.display = 'none';
        document.getElementById('passNote').innerHTML = '<i class="bi bi-shield-lock me-1"></i> Kosongkan jika tidak ingin mengganti password.';
        document.getElementById('passNote').className = 'text-warning mt-1 d-block';

        document.getElementById('inputName').value = user.name;
        document.getElementById('inputUsername').value = user.username; 
        document.getElementById('inputNip').value = user.nip; 
        document.getElementById('selectRole').value = user.role;

        // Populate Checkbox
        var checkboxes = document.querySelectorAll('.subject-checkbox');
        checkboxes.forEach(chk => chk.checked = false);

        if (user.subjects && user.subjects.length > 0) {
            var subjectIds = user.subjects.map(s => s.id);
            checkboxes.forEach(chk => {
                if (subjectIds.includes(parseInt(chk.value))) {
                    chk.checked = true;
                }
            });
        }

        toggleSubject(); 
        
        var modal = getModal();
        if(modal) modal.show();
    }

    document.addEventListener("DOMContentLoaded", function() {
        @if($errors->any())
            var modal = getModal();
            if(modal) modal.show();
        @endif
    });
</script>
@endsection