@extends('layouts.app')

@section('title', 'Penugasan Sekolah ke Pengawas - Admin KCD')

@section('content')
<style>
    .badge .btn-close-sm {
        padding: 0;
        margin-left: 4px;
        opacity: 0.6;
    }
    .badge .btn-close-sm:hover {
        opacity: 1;
    }
    .badge.bg-light {
        border: 1px solid #dee2e6;
    }
</style>
<div class="container-fluid">
    <!-- Page Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-0">Penugasan Sekolah ke Pengawas</h1>
            <p class="text-muted small mt-1">Kelola penugasan pengawas ke sekolah di wilayah KCD Anda</p>
        </div>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#assignModal">
            <i class="bi bi-plus-circle"></i> Penugasan Baru
        </button>
    </div>

    @if(session('success'))
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="bi bi-check-circle"></i> {{ session('success') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    @endif

    @if(session('error'))
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="bi bi-exclamation-triangle"></i> {{ session('error') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    @endif

    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="card stat-card">
                <div class="card-body">
                    <h6 class="card-title text-muted mb-2">Total Sekolah</h6>
                    <h3 class="mb-0">{{ $stats['total_schools'] }}</h3>
                    <small class="text-muted"><i class="bi bi-info-circle"></i> Di KCD ini</small>
                </div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="card stat-card success">
                <div class="card-body">
                    <h6 class="card-title text-muted mb-2">Sudah Tertugaskan</h6>
                    <h3 class="mb-0">{{ $stats['assigned_schools'] }}</h3>
                    <small class="text-success"><i class="bi bi-check-circle"></i> Memiliki pengawas</small>
                </div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="card stat-card warning">
                <div class="card-body">
                    <h6 class="card-title text-muted mb-2">Belum Tertugaskan</h6>
                    <h3 class="mb-0">{{ $stats['unassigned_schools'] }}</h3>
                    <small class="text-warning"><i class="bi bi-exclamation-circle"></i> Perlu pengawas</small>
                </div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="card stat-card info">
                <div class="card-body">
                    <h6 class="card-title text-muted mb-2">Pengawas Aktif</h6>
                    <h3 class="mb-0">{{ $stats['active_supervisors'] }}</h3>
                    <small class="text-info"><i class="bi bi-people"></i> Di KCD ini</small>
                </div>
            </div>
        </div>
    </div>

    <!-- Pengawas & Sekolah Binaan -->
    <div class="row">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Daftar Pengawas dan Sekolah Binaannya</h5>
                </div>
                <div class="card-body">
                    @if($supervisorGroups->isEmpty())
                        <div class="text-center py-5 text-muted">
                            <i class="bi bi-inbox" style="font-size: 3rem;"></i>
                            <p class="mt-3 mb-1"><strong>Belum ada pengawas yang ditugaskan</strong></p>
                            <p class="small">Klik tombol "Penugasan Baru" untuk menugaskan pengawas ke sekolah</p>
                        </div>
                    @else
                        @foreach($supervisorGroups as $supervisorData)
                            @php
                                $colors = ['primary', 'success', 'warning', 'info', 'danger'];
                                $colorIndex = $loop->index % count($colors);
                                $employee = $supervisorData['employee'];
                                $schools = $supervisorData['schools'];
                                $initials = collect(explode(' ', $employee->name))
                                    ->map(fn($word) => strtoupper(substr($word, 0, 1)))
                                    ->take(2)
                                    ->join('');
                            @endphp
                            <div class="mb-4 pb-4 {{ !$loop->last ? 'border-bottom' : '' }}">
                                <div class="d-flex align-items-center justify-content-between mb-3">
                                    <div class="d-flex align-items-center">
                                        <div class="avatar avatar-sm bg-{{ $colors[$colorIndex] }} text-white rounded-circle me-3 d-flex align-items-center justify-content-center" style="width: 45px; height: 45px;">
                                            <strong>{{ $initials }}</strong>
                                        </div>
                                        <div>
                                            <h6 class="mb-0">{{ $employee->name }}</h6>
                                            <small class="text-muted">
                                                @if($employee->nip)
                                                    NIP: {{ $employee->nip }} 
                                                @endif
                                                @if($employee->email)
                                                    | {{ $employee->email }}
                                                @endif
                                                @if($employee->phone)
                                                    | {{ $employee->phone }}
                                                @endif
                                            </small>
                                        </div>
                                    </div>
                                </div>
                                <div class="ms-5 ps-2">
                                    <small class="text-muted d-block mb-2">Sekolah Binaan ({{ $schools->count() }}):</small>
                                    <div class="d-flex flex-wrap gap-2">
                                        @foreach($schools as $school)
                                            <span class="badge bg-light text-dark d-flex align-items-center gap-1">
                                                {{ $school->name }}
                                                <button type="button" class="btn-close btn-close-sm" style="font-size: 0.6rem;" 
                                                        onclick="unassignSchool({{ $employee->id }}, {{ $school->id }}, '{{ addslashes($school->name) }}')"></button>
                                            </span>
                                        @endforeach
                                        <button class="badge bg-primary border-0" data-bs-toggle="modal" data-bs-target="#addSchoolModal" 
                                                onclick="setEmployeeForAddSchool({{ $employee->id }}, '{{ addslashes($employee->name) }}')">
                                            <i class="bi bi-plus"></i> Tambah Sekolah
                                        </button>
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    @endif
                </div>
            </div>
        </div>
    </div>

    <!-- Sekolah Belum Tertugaskan -->
    <div class="row mt-4">
        <div class="col-lg-12">
            <div class="card border-warning">
                <div class="card-header bg-warning bg-opacity-10 border-warning">
                    <h5 class="mb-0 text-warning"><i class="bi bi-exclamation-circle"></i> Sekolah Belum Tertugaskan</h5>
                </div>
                <div class="card-body">
                    @if($schoolsWithoutSupervisor->count() > 0)
                        <div class="table-responsive">
                            <table class="table table-sm table-hover">
                                <thead class="table-light">
                                    <tr>
                                        <th>Nama Sekolah</th>
                                        <th>Kepala Sekolah</th>
                                        <th>Kab/Kota</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($schoolsWithoutSupervisor as $school)
                                        <tr>
                                            <td>
                                                <div>
                                                    <strong>{{ $school->name }}</strong>
                                                    <br>
                                                    <small class="text-muted">NPSN: {{ $school->npsn }}</small>
                                                </div>
                                            </td>
                                            <td>{{ $school->principal_name ?? '-' }}</td>
                                            <td>{{ $school->kabKota->name ?? '-' }}</td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    @else
                        <div class="text-center py-4 text-success">
                            <i class="bi bi-check-circle" style="font-size: 3rem;"></i>
                            <p class="mt-2">Semua sekolah sudah memiliki pengawas!</p>
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Penugasan Baru Modal -->
<div class="modal fade" id="assignModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="{{ route('admin-kcd.mapping-sekolah.store') }}" method="POST">
                @csrf
                <div class="modal-header border-bottom">
                    <h5 class="modal-title">Penugasan Sekolah ke Pengawas</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Pengawas <span class="text-danger">*</span></label>
                        <select class="form-select" name="employee_id" required>
                            <option value="">-- Pilih Pengawas --</option>
                            @forelse($supervisors as $supervisor)
                                <option value="{{ $supervisor->id }}">{{ $supervisor->name }} @if($supervisor->nip)(NIP: {{ $supervisor->nip }})@endif</option>
                            @empty
                                <option value="" disabled>Tidak ada pengawas tersedia</option>
                            @endforelse
                        </select>
                        @if($supervisors->isEmpty())
                            <small class="text-warning">Belum ada pengawas di KCD ini. Hubungi Super Administrator untuk menambah pengawas.</small>
                        @endif
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Sekolah <span class="text-danger">*</span></label>
                        <select class="form-select" name="school_ids[]" multiple required size="8">
                            @forelse($allSchools as $school)
                                <option value="{{ $school->id }}">{{ $school->name }} (NPSN: {{ $school->npsn }})@if($school->kabKota) - {{ $school->kabKota->name }}@endif</option>
                            @empty
                                <option value="" disabled>Tidak ada sekolah tersedia</option>
                            @endforelse
                        </select>
                        <small class="text-muted">Tahan Ctrl (Windows) atau Cmd (Mac) untuk memilih lebih dari satu sekolah</small>
                        @if($allSchools->isEmpty())
                            <br><small class="text-warning">Belum ada sekolah di KCD ini.</small>
                        @endif
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Tanggal Mulai <span class="text-danger">*</span></label>
                        <input type="date" class="form-control" name="start_date" value="{{ date('Y-m-d') }}" required>
                    </div>
                </div>
                <div class="modal-footer border-top">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary">Simpan Penugasan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Add School to Existing Supervisor Modal -->
<div class="modal fade" id="addSchoolModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="{{ route('admin-kcd.mapping-sekolah.store') }}" method="POST">
                @csrf
                <input type="hidden" name="employee_id" id="add_employee_id">
                <div class="modal-header border-bottom">
                    <h5 class="modal-title">Tambah Sekolah ke <span id="supervisor_name"></span></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Pilih Sekolah <span class="text-danger">*</span></label>
                        <select class="form-select" name="school_ids[]" multiple required size="10">
                            @forelse($allSchools as $school)
                                <option value="{{ $school->id }}">{{ $school->name }} (NPSN: {{ $school->npsn }})@if($school->kabKota) - {{ $school->kabKota->name }}@endif</option>
                            @empty
                                <option value="" disabled>Tidak ada sekolah tersedia</option>
                            @endforelse
                        </select>
                        <small class="text-muted">Tahan Ctrl (Windows) atau Cmd (Mac) untuk memilih lebih dari satu sekolah</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Tanggal Mulai <span class="text-danger">*</span></label>
                        <input type="date" class="form-control" name="start_date" value="{{ date('Y-m-d') }}" required>
                    </div>
                </div>
                <div class="modal-footer border-top">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary">Tambah Sekolah</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function setEmployeeForAddSchool(employeeId, employeeName) {
    document.getElementById('add_employee_id').value = employeeId;
    document.getElementById('supervisor_name').textContent = employeeName;
}

function unassignSchool(employeeId, schoolId, schoolName) {
    if (confirm(`Apakah Anda yakin ingin menghapus penugasan "${schoolName}" dari pengawas ini?`)) {
        fetch('{{ route('admin-kcd.mapping-sekolah.unassign') }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify({
                employee_id: employeeId,
                school_id: schoolId
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                location.reload();
            } else {
                alert('Error: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Terjadi kesalahan saat menghapus penugasan');
        });
    }
}
</script>
@endsection
