@extends('layouts.admin')

@section('title', 'Absensi Guru')
@section('subtitle', 'Rekap dan input kehadiran guru')

@section('extra-style')
<style>
.foto-thumb { width:52px !important; height:52px !important; min-width:52px; min-height:52px;
              border-radius:10px; object-fit:cover; cursor:pointer;
              border:2px solid var(--border); transition:transform .15s; display:block; }
.foto-thumb:hover { transform:scale(1.08); }
.no-foto { width:52px !important; height:52px !important; min-width:52px; border-radius:10px;
           background:var(--surface-2); border:2px dashed var(--border);
           display:flex; align-items:center; justify-content:center;
           color:var(--text-muted); font-size:.75rem; }
/* Pastikan kolom foto tidak melebar */
td:has(.foto-thumb), td:has(.no-foto) { width:64px; padding:8px !important; }
.loc-text { font-size:.72rem; color:var(--text-muted); max-width:200px;
            white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }

/* Modal foto */
.foto-modal-bg  { display:none; position:fixed; inset:0; background:rgba(0,0,0,.85);
                  z-index:9999; align-items:center; justify-content:center; }
.foto-modal-bg.show { display:flex; }
.foto-modal-img { max-width:90vw; max-height:90vh; border-radius:16px; }
.foto-modal-close { position:fixed; top:16px; right:20px; background:rgba(255,255,255,.15);
                    color:#fff; border:none; border-radius:50%; width:38px; height:38px;
                    font-size:1.1rem; cursor:pointer; display:flex; align-items:center; justify-content:center; }
</style>
@endsection

@section('content')

{{-- Rekap stat cards --}}
<div class="row g-3 mb-4">
    @php
        $rekapItems = [
            ['label'=>'Hadir',     'key'=>'hadir',      'color'=>'#155724','bg'=>'#d4edda','icon'=>'circle-check'],
            ['label'=>'Sakit',     'key'=>'sakit',      'color'=>'#856404','bg'=>'#fff3cd','icon'=>'face-dizzy'],
            ['label'=>'Izin',      'key'=>'izin',       'color'=>'#0c5460','bg'=>'#d1ecf1','icon'=>'envelope'],
            ['label'=>'Dinas Luar','key'=>'dinas_luar', 'color'=>'#003580','bg'=>'#cce5ff','icon'=>'briefcase'],
            ['label'=>'Alfa',      'key'=>'alfa',       'color'=>'#721c24','bg'=>'#f8d7da','icon'=>'ban'],
            ['label'=>'Blm Input', 'key'=>'belum',      'color'=>'#383d41','bg'=>'#e2e3e5','icon'=>'clock'],
        ];
    @endphp
    @foreach($rekapItems as $item)
        <div class="col-6 col-lg">
            <div class="stat-card">
                <div>
                    <div class="label">{{ $item['label'] }}</div>
                    <div class="value">{{ $rekap[$item['key']] ?? 0 }}</div>
                    <div class="delta text-muted">guru</div>
                </div>
                <div class="stat-icon" style="background:{{ $item['bg'] }};color:{{ $item['color'] }};">
                    <i class="fa-solid fa-{{ $item['icon'] }}"></i>
                </div>
            </div>
        </div>
    @endforeach
</div>

{{-- Tabel rekap dengan foto+lokasi --}}
<div class="panel mb-3">
    <div class="panel-head">
        <h3>Rekap Kehadiran + Foto</h3>
        <form method="GET" class="d-flex gap-2 align-items-center">
            <input type="date" name="tanggal" class="form-control form-control-sm"
                value="{{ $tanggal }}" max="{{ today()->format('Y-m-d') }}" onchange="this.form.submit()">
        </form>
    </div>
    <div class="table-responsive">
        <table class="table-modern">
            <thead>
                <tr>
                    <th>Foto</th>
                    <th>Nama Guru</th>
                    <th>Status</th>
                    <th>Check-in</th>
                    <th>Lokasi</th>
                    <th>Keterangan</th>
                </tr>
            </thead>
            <tbody>
                @forelse($teachers as $t)
                    <tr>
                        <td style="width:56px;padding:8px;">
                            @if($t->absen?->photo_path)
                                <img src="{{ asset('storage/' . $t->absen->photo_path) }}"
                                     style="width:48px;height:48px;min-width:48px;border-radius:10px;object-fit:cover;cursor:pointer;border:2px solid var(--border);display:block;"
                                     onclick="showFoto(
                                        '{{ asset('storage/' . $t->absen->photo_path) }}',
                                        '{{ addslashes($t->name) }}',
                                        '{{ $t->absen->latitude }}',
                                        '{{ $t->absen->longitude }}',
                                        '{{ addslashes($t->absen->location_address ?? '') }}',
                                        '{{ $t->absen->check_in_time ?? '' }}'
                                     )"
                                     title="Klik untuk perbesar">
                            @else
                                <div style="width:48px;height:48px;border-radius:10px;background:var(--surface-2);border:2px dashed var(--border);display:flex;align-items:center;justify-content:center;color:var(--text-muted);font-size:.75rem;">
                                    <i class="fa-solid fa-camera-slash"></i>
                                </div>
                            @endif
                        </td>
                        <td>
                            <div class="fw-semibold">{{ $t->name }}</div>
                            <div class="text-muted" style="font-size:.72rem;">{{ $t->nip }}</div>
                        </td>
                        <td>
                            @if($t->absen)
                                <span class="badge badge-{{ $t->absen->status === 'dinas_luar' ? 'hadir' : $t->absen->status }}">
                                    {{ \App\Models\TeacherAttendance::statusLabel($t->absen->status) }}
                                </span>
                            @else
                                <span class="badge badge-belum">Belum</span>
                            @endif
                        </td>
                        <td>
                            @if($t->absen?->check_in_time)
                                <span class="fw-semibold">{{ substr($t->absen->check_in_time, 0, 5) }}</span>
                                <div class="text-muted" style="font-size:.7rem;">WIB</div>
                            @else
                                <span class="text-muted">—</span>
                            @endif
                        </td>
                        <td>
                            @if($t->absen?->latitude)
                                <div class="loc-text" title="{{ $t->absen->location_address }}">
                                    <i class="fa-solid fa-location-dot me-1" style="color:var(--brand);"></i>
                                    {{ $t->absen->location_address
                                        ? implode(', ', array_slice(explode(', ', $t->absen->location_address), 0, 3))
                                        : $t->absen->latitude . ', ' . $t->absen->longitude }}
                                </div>
                                <a href="https://maps.google.com/?q={{ $t->absen->latitude }},{{ $t->absen->longitude }}"
                                   target="_blank" style="font-size:.68rem;color:var(--brand);">
                                    Lihat Maps →
                                </a>
                            @else
                                <span class="text-muted" style="font-size:.75rem;">
                                    {{ $t->absen ? 'Tidak ada GPS' : '—' }}
                                </span>
                            @endif
                        </td>
                        <td class="text-muted" style="font-size:.8rem;">
                            {{ $t->absen?->notes ?? '—' }}
                        </td>
                    </tr>
                @empty
                    <tr><td colspan="6" class="text-center text-muted py-4">Belum ada data guru.</td></tr>
                @endforelse
            </tbody>
        </table>
    </div>
</div>

{{-- Form input manual oleh admin --}}
<div class="panel">
    <div class="panel-head">
        <h3>Input Manual oleh Admin</h3>
        <span class="text-muted" style="font-size:.75rem;">Untuk guru yang belum absen mandiri</span>
    </div>
    <form action="{{ route('admin.absen.guru.store') }}" method="POST">
        @csrf
        <input type="hidden" name="tanggal" value="{{ $tanggal }}">
        <div class="table-responsive">
            <table class="table-modern">
                <thead>
                    <tr>
                        <th>Nama Guru</th>
                        <th>Status Saat Ini</th>
                        <th>Ubah Status</th>
                        <th>Keterangan</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($teachers as $t)
                        <tr>
                            <td class="fw-semibold">{{ $t->name }}</td>
                            <td>
                                @if($t->absen)
                                    <span class="badge badge-{{ $t->absen->status === 'dinas_luar' ? 'hadir' : $t->absen->status }}">
                                        {{ \App\Models\TeacherAttendance::statusLabel($t->absen->status) }}
                                    </span>
                                    @if($t->absen->photo_path)
                                        <span class="badge text-bg-success" style="font-size:.65rem;">
                                            <i class="fa-solid fa-camera"></i> Mandiri
                                        </span>
                                    @endif
                                @else
                                    <span class="badge badge-belum">Belum</span>
                                @endif
                            </td>
                            <td>
                                <div class="d-flex gap-2 flex-wrap">
                                    @foreach(['hadir'=>['success','circle-check'],'sakit'=>['warning','face-dizzy'],'izin'=>['info','envelope'],'dinas_luar'=>['primary','briefcase'],'alfa'=>['danger','ban']] as $val=>[$color,$icon])
                                        <label class="d-flex align-items-center gap-1" style="cursor:pointer;font-size:.8rem;">
                                            <input type="radio" name="absen[{{ $t->id }}][status]"
                                                value="{{ $val }}"
                                                {{ ($t->absen?->status ?? '') === $val ? 'checked' : '' }}
                                                style="accent-color:var(--brand);">
                                            <span class="badge badge-{{ $val==='dinas_luar'?'hadir':$val }}">
                                                <i class="fa-solid fa-{{ $icon }} me-1"></i>
                                                {{ $val==='dinas_luar'?'Dinas':ucfirst($val) }}
                                            </span>
                                        </label>
                                    @endforeach
                                </div>
                            </td>
                            <td>
                                <input type="text" name="absen[{{ $t->id }}][notes]"
                                    class="form-control form-control-sm"
                                    value="{{ $t->absen?->notes }}"
                                    placeholder="Keterangan">
                            </td>
                        </tr>
                    @empty
                        <tr><td colspan="4" class="text-center text-muted py-4">Belum ada data guru.</td></tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        @if($teachers->count())
            <div class="p-3 d-flex justify-content-end" style="border-top:1px solid var(--border);">
                <button type="submit" class="btn btn-brand">
                    <i class="fa-solid fa-floppy-disk me-1"></i> Simpan Perubahan
                </button>
            </div>
        @endif
    </form>
</div>

{{-- Modal foto besar --}}
<div class="foto-modal-bg" id="fotoModal" onclick="closeFoto()">
    <button class="foto-modal-close" onclick="closeFoto()"><i class="fa-solid fa-xmark"></i></button>
    <div style="display:flex;flex-direction:column;align-items:center;gap:12px;max-width:92vw;" onclick="event.stopPropagation()">

        {{-- Foto --}}
        <div style="position:relative;">
            <img src="" id="fotoModalImg"
                 style="max-width:88vw;max-height:72vh;border-radius:16px;display:block;object-fit:contain;">

            {{-- Overlay koordinat di pojok kiri bawah foto --}}
            <div id="fotoCoordOverlay"
                 style="display:none;position:absolute;bottom:0;left:0;right:0;
                        background:linear-gradient(transparent,rgba(0,0,0,.75));
                        border-radius:0 0 16px 16px;padding:20px 14px 10px;
                        color:#fff;font-size:.75rem;">
                <div id="fotoCoordText" style="font-weight:600;letter-spacing:.01em;"></div>
                <div id="fotoAddrText" style="opacity:.85;font-size:.68rem;margin-top:2px;"></div>
            </div>
        </div>

        {{-- Info bawah foto --}}
        <div id="fotoInfoBar"
             style="background:rgba(255,255,255,.1);backdrop-filter:blur(10px);
                    border-radius:12px;padding:10px 18px;display:flex;
                    align-items:center;gap:16px;flex-wrap:wrap;justify-content:center;">
            <div style="color:#fff;text-align:center;">
                <div id="fotoNama" style="font-weight:700;font-size:.9rem;"></div>
                <div id="fotoJam"  style="font-size:.75rem;opacity:.75;"></div>
            </div>
            <a id="fotoMapsLink" href="#" target="_blank"
               style="display:none;background:rgba(255,255,255,.2);color:#fff;
                      border-radius:8px;padding:6px 14px;font-size:.75rem;
                      font-weight:600;text-decoration:none;white-space:nowrap;">
                <i class="fa-solid fa-map-location-dot me-1"></i> Buka Google Maps
            </a>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script>
function showFoto(url, nama, lat, lng, addr, jam) {
    document.getElementById('fotoModalImg').src = url;
    document.getElementById('fotoNama').textContent = nama;
    document.getElementById('fotoJam').textContent  = jam ? 'Check-in ' + jam + ' WIB' : '';

    const overlay = document.getElementById('fotoCoordOverlay');
    const coordTxt = document.getElementById('fotoCoordText');
    const addrTxt  = document.getElementById('fotoAddrText');
    const mapsLink = document.getElementById('fotoMapsLink');

    if (lat && lng && lat !== '' && lng !== '') {
        const latF = parseFloat(lat).toFixed(6);
        const lngF = parseFloat(lng).toFixed(6);
        coordTxt.textContent = '📍 ' + latF + ', ' + lngF;
        addrTxt.textContent  = addr || '';
        overlay.style.display = 'block';
        mapsLink.href = 'https://maps.google.com/?q=' + lat + ',' + lng;
        mapsLink.style.display = 'inline-flex';
    } else {
        overlay.style.display  = 'none';
        mapsLink.style.display = 'none';
    }

    document.getElementById('fotoModal').classList.add('show');
}
function closeFoto() {
    document.getElementById('fotoModal').classList.remove('show');
    document.getElementById('fotoModalImg').src = '';
}
document.addEventListener('keydown', e => { if(e.key==='Escape') closeFoto(); });
</script>
@endsection
