@extends('layouts.app')

@section('title', 'Data Kehadiran')
@section('page-title', 'Data Kehadiran Karyawan')
@section('page-subtitle', 'Monitoring rekap absensi harian, keterlambatan, selfie, dan lokasi geofencing GPS.')

@section('page-actions')
<div class="d-flex justify-content-md-end gap-2 mt-2 mt-md-0">
    <a href="{{ route('admin.attendance.export', request()->query()) }}" class="btn btn-outline-success">
        <i class="bi bi-file-earmark-excel me-1"></i> Export Data
    </a>
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalManualAttendance">
        <i class="bi bi-plus-circle me-1"></i> Input Manual
    </button>
</div>
@endsection

@push('styles')
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<style>
    .map-preview-container {
        height: 250px;
        width: 100%;
        border-radius: 0.5rem;
    }
</style>
@endpush

@section('content')
{{-- Stats Row --}}
<div class="row g-3 mb-4">
    <div class="col-12 col-sm-6 col-xl-3">
        <div class="material-stat-card">
            <div class="stat-icon-glow stat-icon-green">
                <i class="bi bi-check2-circle"></i>
            </div>
            <div class="stat-info-box">
                <div class="stat-info-label">Total Hadir</div>
                <h3 class="stat-info-val text-success">{{ $totalPresent }}</h3>
                <small class="text-muted text-xs font-semibold">Karyawan Masuk</small>
            </div>
        </div>
    </div>
    <div class="col-12 col-sm-6 col-xl-3">
        <div class="material-stat-card">
            <div class="stat-icon-glow stat-icon-orange">
                <i class="bi bi-clock-history"></i>
            </div>
            <div class="stat-info-box">
                <div class="stat-info-label">Terlambat</div>
                <h3 class="stat-info-val text-warning">{{ $totalLate }}</h3>
                <small class="text-muted text-xs font-semibold">Tercatat Keterlambatan</small>
            </div>
        </div>
    </div>
    <div class="col-12 col-sm-6 col-xl-3">
        <div class="material-stat-card">
            <div class="stat-icon-glow stat-icon-purple">
                <i class="bi bi-calendar2-check"></i>
            </div>
            <div class="stat-info-box">
                <div class="stat-info-label">Izin / Sakit / Cuti</div>
                <h3 class="stat-info-val text-primary">{{ $totalPermit }}</h3>
                <small class="text-muted text-xs font-semibold">Disetujui HR</small>
            </div>
        </div>
    </div>
    <div class="col-12 col-sm-6 col-xl-3">
        <div class="material-stat-card">
            <div class="stat-icon-glow stat-icon-rose">
                <i class="bi bi-person-x"></i>
            </div>
            <div class="stat-info-box">
                <div class="stat-info-label">Tanpa Keterangan</div>
                <h3 class="stat-info-val text-danger">{{ $totalAlpha }}</h3>
                <small class="text-muted text-xs font-semibold">Alpha / Belum Absen</small>
            </div>
        </div>
    </div>
</div>

{{-- Filter Card --}}
<div class="card shadow-sm border-0 mb-4">
    <div class="card-body p-3">
        <form method="GET" action="{{ route('admin.attendance.index') }}" class="row g-2 align-items-center">
            <div class="col-12 col-md-3">
                <label class="form-label text-xs text-muted mb-1">Tanggal Spesifik</label>
                <input type="date" name="date" class="form-control bg-light border-0" value="{{ request('date', $selectedDate) }}">
            </div>
            <div class="col-6 col-md-3">
                <label class="form-label text-xs text-muted mb-1">Departemen</label>
                <select name="department_id" class="form-select bg-light border-0">
                    <option value="">Semua Departemen</option>
                    @foreach($departments as $dept)
                        <option value="{{ $dept->id }}" {{ request('department_id') == $dept->id ? 'selected' : '' }}>{{ $dept->name }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-6 col-md-2">
                <label class="form-label text-xs text-muted mb-1">Karyawan</label>
                <select name="employee_id" class="form-select bg-light border-0">
                    <option value="">Semua Karyawan</option>
                    @foreach($employeesList as $emp)
                        <option value="{{ $emp->id }}" {{ request('employee_id') == $emp->id ? 'selected' : '' }}>{{ $emp->name }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-6 col-md-2">
                <label class="form-label text-xs text-muted mb-1">Status</label>
                <select name="status" class="form-select bg-light border-0">
                    <option value="">Semua Status</option>
                    <option value="present" {{ request('status') == 'present' ? 'selected' : '' }}>Hadir</option>
                    <option value="late" {{ request('status') == 'late' ? 'selected' : '' }}>Terlambat</option>
                    <option value="permit" {{ request('status') == 'permit' ? 'selected' : '' }}>Izin</option>
                    <option value="sick" {{ request('status') == 'sick' ? 'selected' : '' }}>Sakit</option>
                    <option value="leave" {{ request('status') == 'leave' ? 'selected' : '' }}>Cuti</option>
                    <option value="alpha" {{ request('status') == 'alpha' ? 'selected' : '' }}>Alpha</option>
                </select>
            </div>
            <div class="col-6 col-md-2 d-flex align-items-end gap-1">
                <button type="submit" class="btn btn-primary w-100 mt-md-4"><i class="bi bi-funnel me-1"></i> Terapkan</button>
                @if(request()->hasAny(['date', 'start_date', 'department_id', 'employee_id', 'status']))
                    <a href="{{ route('admin.attendance.index') }}" class="btn btn-light mt-md-4" title="Reset"><i class="bi bi-arrow-counterclockwise"></i></a>
                @endif
            </div>
        </form>
    </div>
</div>

{{-- Attendance Table Card --}}
<div class="card shadow-sm border-0">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="bg-light">
                    <tr>
                        <th class="ps-4">Karyawan</th>
                        <th>Tanggal</th>
                        <th>Jam Masuk</th>
                        <th>Jam Pulang</th>
                        <th>Status</th>
                        <th>Keterlambatan</th>
                        <th>Lokasi & Radius</th>
                        <th class="text-end pe-4">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($attendances as $att)
                        <tr>
                            <td class="ps-4">
                                <div class="d-flex align-items-center">
                                    <div class="avatar avatar-md bg-light-primary text-primary me-3 flex-shrink-0">
                                        @if($att->photo_in)
                                            <img src="{{ asset($att->photo_in) }}" alt="Foto Masuk" style="object-fit: cover; width: 45px; height: 45px; border-radius: 50%;">
                                        @elseif($att->employee?->photo)
                                            <img src="{{ asset($att->employee->photo) }}" alt="Avatar" style="object-fit: cover; width: 45px; height: 45px; border-radius: 50%;">
                                        @else
                                            <span class="avatar-content fw-bold">{{ strtoupper(substr($att->employee?->name ?? 'K', 0, 2)) }}</span>
                                        @endif
                                    </div>
                                    <div>
                                        <h6 class="mb-0 fw-bold text-dark">{{ $att->employee?->name ?? 'Karyawan Dihapus' }}</h6>
                                        <small class="text-muted">{{ $att->employee?->department?->name ?? '-' }} • <span class="badge bg-light text-secondary">{{ $att->employee?->nik }}</span></small>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <strong>{{ \Carbon\Carbon::parse($att->attendance_date)->translatedFormat('d M Y') }}</strong>
                                <br><small class="text-muted">{{ $att->shift?->name ?? 'Shift Reguler' }}</small>
                            </td>
                            <td>
                                @if($att->check_in)
                                    <span class="fw-bold text-success"><i class="bi bi-box-arrow-in-right me-1"></i> {{ \Carbon\Carbon::parse($att->check_in)->format('H:i') }}</span>
                                @else
                                    <span class="text-muted">-</span>
                                @endif
                            </td>
                            <td>
                                @if($att->check_out)
                                    <span class="fw-bold text-danger"><i class="bi bi-box-arrow-right me-1"></i> {{ \Carbon\Carbon::parse($att->check_out)->format('H:i') }}</span>
                                @else
                                    <span class="text-muted">-</span>
                                @endif
                            </td>
                            <td>
                                <span class="badge {{ $att->status_badge }}">{{ $att->status_label }}</span>
                            </td>
                            <td>
                                @if($att->late_minutes > 0)
                                    <span class="text-danger fw-bold">+{{ $att->late_minutes }} Menit</span>
                                @else
                                    <span class="text-success"><i class="bi bi-check2 me-1"></i> Tepat Waktu</span>
                                @endif
                            </td>
                            <td>
                                @if($att->distance_in !== null)
                                    <span class="badge bg-light-primary text-primary"><i class="bi bi-geo-alt me-1"></i> {{ round($att->distance_in) }} Meter</span>
                                @else
                                    <span class="text-muted">-</span>
                                @endif
                            </td>
                            <td class="text-end pe-4">
                                <div class="btn-group">
                                    <button type="button" class="btn btn-sm btn-outline-info" data-bs-toggle="modal" data-bs-target="#modalDetailAtt{{ $att->id }}" title="Lihat Selfie & GPS">
                                        <i class="bi bi-eye"></i>
                                    </button>
                                    <button type="button" class="btn btn-sm btn-outline-warning" data-bs-toggle="modal" data-bs-target="#modalEditAtt{{ $att->id }}" title="Edit Manual">
                                        <i class="bi bi-pencil-square"></i>
                                    </button>
                                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="confirmDeleteAtt('{{ $att->id }}')" title="Hapus">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </div>
                                <form id="delete-att-form-{{ $att->id }}" action="{{ route('admin.attendance.destroy', $att->id) }}" method="POST" class="d-none">
                                    @csrf
                                    @method('DELETE')
                                </form>
                            </td>
                        </tr>

                        {{-- Modal Detail Selfie & GPS --}}
                        <div class="modal fade" id="modalDetailAtt{{ $att->id }}" tabindex="-1" aria-hidden="true">
                            <div class="modal-dialog modal-dialog-centered">
                                <div class="modal-content border-0 shadow">
                                    <div class="modal-header bg-light">
                                        <h5 class="modal-title"><i class="bi bi-geo-alt-fill text-primary me-2"></i> Detail Presensi & Verifikasi</h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                    </div>
                                    <div class="modal-body p-4">
                                        <div class="d-flex align-items-center mb-3">
                                            <div class="avatar avatar-lg bg-light-primary me-3">
                                                @if($att->photo_in)
                                                    <img src="{{ asset($att->photo_in) }}" alt="Selfie Masuk" style="width: 60px; height: 60px; object-fit: cover; border-radius: 50%;">
                                                @else
                                                    <span class="avatar-content">{{ strtoupper(substr($att->employee?->name ?? 'K', 0, 2)) }}</span>
                                                @endif
                                            </div>
                                            <div>
                                                <h5 class="mb-0 fw-bold">{{ $att->employee?->name }}</h5>
                                                <p class="text-muted mb-0">{{ $att->employee?->department?->name }} • {{ \Carbon\Carbon::parse($att->attendance_date)->translatedFormat('d F Y') }}</p>
                                            </div>
                                        </div>

                                        <div class="row g-2 mb-3 bg-light p-3 rounded-3">
                                            <div class="col-6"><small class="text-muted d-block">Jam Masuk:</small><strong>{{ $att->check_in ?? '-' }}</strong></div>
                                            <div class="col-6"><small class="text-muted d-block">Jam Pulang:</small><strong>{{ $att->check_out ?? '-' }}</strong></div>
                                            <div class="col-6"><small class="text-muted d-block">Status:</small><span class="badge {{ $att->status_badge }}">{{ $att->status_label }}</span></div>
                                            <div class="col-6"><small class="text-muted d-block">Keterlambatan:</small><strong>{{ $att->late_minutes }} Menit</strong></div>
                                            <div class="col-6"><small class="text-muted d-block">Jarak Masuk:</small><strong>{{ $att->distance_in ? round($att->distance_in).' Meter' : '-' }}</strong></div>
                                            <div class="col-6"><small class="text-muted d-block">Jarak Pulang:</small><strong>{{ $att->distance_out ? round($att->distance_out).' Meter' : '-' }}</strong></div>
                                            <div class="col-12"><small class="text-muted d-block">Catatan:</small><span>{{ $att->notes ?? 'Tidak ada catatan' }}</span></div>
                                        </div>

                                        @if($att->latitude_in && $att->longitude_in)
                                            <div class="text-center">
                                                <a href="https://www.google.com/maps?q={{ $att->latitude_in }},{{ $att->longitude_in }}" target="_blank" class="btn btn-sm btn-outline-primary w-100">
                                                    <i class="bi bi-map-fill me-1"></i> Buka Koordinat GPS di Google Maps
                                                </a>
                                            </div>
                                        @endif
                                    </div>
                                    <div class="modal-footer bg-light">
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        {{-- Modal Edit Attendance --}}
                        <div class="modal fade" id="modalEditAtt{{ $att->id }}" tabindex="-1" aria-hidden="true">
                            <div class="modal-dialog modal-dialog-centered">
                                <div class="modal-content border-0 shadow">
                                    <div class="modal-header bg-warning text-dark">
                                        <h5 class="modal-title"><i class="bi bi-pencil-square me-2"></i> Edit Absensi ({{ $att->employee?->name }})</h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                    </div>
                                    <form action="{{ route('admin.attendance.update', $att->id) }}" method="POST">
                                        @csrf
                                        @method('PUT')
                                        <div class="modal-body p-4">
                                            <div class="mb-3">
                                                <label class="form-label fw-bold">Jam Masuk</label>
                                                <input type="time" name="check_in" class="form-control" value="{{ $att->check_in ? \Carbon\Carbon::parse($att->check_in)->format('H:i') : '' }}">
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label fw-bold">Jam Pulang</label>
                                                <input type="time" name="check_out" class="form-control" value="{{ $att->check_out ? \Carbon\Carbon::parse($att->check_out)->format('H:i') : '' }}">
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label fw-bold">Status Kehadiran</label>
                                                <select name="status" class="form-select" required>
                                                    <option value="present" {{ $att->status == 'present' ? 'selected' : '' }}>Hadir</option>
                                                    <option value="late" {{ $att->status == 'late' ? 'selected' : '' }}>Terlambat</option>
                                                    <option value="permit" {{ $att->status == 'permit' ? 'selected' : '' }}>Izin</option>
                                                    <option value="sick" {{ $att->status == 'sick' ? 'selected' : '' }}>Sakit</option>
                                                    <option value="leave" {{ $att->status == 'leave' ? 'selected' : '' }}>Cuti</option>
                                                    <option value="alpha" {{ $att->status == 'alpha' ? 'selected' : '' }}>Alpha / Tidak Hadir</option>
                                                </select>
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label fw-bold">Keterlambatan (Menit)</label>
                                                <input type="number" name="late_minutes" class="form-control" min="0" value="{{ $att->late_minutes }}">
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label fw-bold">Catatan / Keterangan</label>
                                                <textarea name="notes" class="form-control" rows="2">{{ $att->notes }}</textarea>
                                            </div>
                                        </div>
                                        <div class="modal-footer bg-light">
                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                                            <button type="submit" class="btn btn-warning"><i class="bi bi-save me-1"></i> Simpan Perubahan</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    @empty
                        <tr>
                            <td colspan="8" class="text-center py-5 text-muted">
                                <i class="bi bi-calendar-x fs-1 d-block mb-2 text-muted"></i>
                                Tidak ada data absensi yang ditemukan untuk filter yang dipilih.
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        @if($attendances->hasPages())
            <div class="p-3 border-top d-flex justify-content-end">
                {{ $attendances->links('pagination::bootstrap-5') }}
            </div>
        @endif
    </div>
</div>

{{-- Modal Input Manual --}}
<div class="modal fade" id="modalManualAttendance" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title text-white"><i class="bi bi-plus-circle me-2"></i> Input Manual Presensi</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="{{ route('admin.attendance.store') }}" method="POST">
                @csrf
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label class="form-label fw-bold">Pilih Karyawan <span class="text-danger">*</span></label>
                        <select name="employee_id" class="form-select" required>
                            <option value="">-- Pilih Karyawan --</option>
                            @foreach($employeesList as $emp)
                                <option value="{{ $emp->id }}">{{ $emp->name }} ({{ $emp->nik }})</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Tanggal Absensi <span class="text-danger">*</span></label>
                        <input type="date" name="attendance_date" class="form-control" value="{{ date('Y-m-d') }}" required>
                    </div>
                    <div class="row g-2 mb-3">
                        <div class="col-6">
                            <label class="form-label fw-bold">Jam Masuk</label>
                            <input type="time" name="check_in" class="form-control" value="08:00">
                        </div>
                        <div class="col-6">
                            <label class="form-label fw-bold">Jam Pulang</label>
                            <input type="time" name="check_out" class="form-control" value="17:00">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Status Kehadiran <span class="text-danger">*</span></label>
                        <select name="status" class="form-select" required>
                            <option value="present">Hadir (Tepat Waktu)</option>
                            <option value="late">Terlambat</option>
                            <option value="permit">Izin</option>
                            <option value="sick">Sakit</option>
                            <option value="leave">Cuti</option>
                            <option value="alpha">Alpha / Tidak Hadir</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Keterlambatan (Menit)</label>
                        <input type="number" name="late_minutes" class="form-control" value="0" min="0">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Catatan / Alasan</label>
                        <textarea name="notes" class="form-control" rows="2" placeholder="Catatan manual dari administrator"></textarea>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-check2-circle me-1"></i> Simpan Data</button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
    function confirmDeleteAtt(id) {
        Swal.fire({
            title: 'Hapus Record Presensi?',
            text: 'Apakah Anda yakin ingin menghapus data presensi ini?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Ya, Hapus',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                document.getElementById(`delete-att-form-${id}`).submit();
            }
        });
    }
</script>
@endpush
