@extends('layouts.app')

@section('title', 'Absen Pulang')
@section('page-title', 'Absensi Pulang (Check-Out)')
@section('page-subtitle', 'Pastikan pekerjaan Anda hari ini telah selesai sebelum melakukan check-out.')

@section('content')
<div class="row justify-content-center">
    <div class="col-12 col-lg-7">
        @if(!$attendance || !$attendance->check_in)
            <div class="card shadow-sm border-0 mb-4 bg-light-warning text-center py-5">
                <div class="card-body">
                    <div class="avatar avatar-xl bg-warning text-dark mx-auto mb-3">
                        <i class="bi bi-exclamation-triangle-fill fs-1"></i>
                    </div>
                    <h4 class="text-warning fw-bold">Anda Belum Melakukan Absen Masuk Hari Ini</h4>
                    <p class="text-muted mb-4">Silakan lakukan absensi masuk (Check-In) terlebih dahulu.</p>
                    <a href="{{ route('employee.attendance.check-in') }}" class="btn btn-primary px-4">
                        <i class="bi bi-box-arrow-in-right me-1"></i> Menuju Halaman Absen Masuk
                    </a>
                </div>
            </div>
        @elseif($attendance->check_out)
            <div class="card shadow-sm border-0 mb-4 bg-light-info text-center py-5">
                <div class="card-body">
                    <div class="avatar avatar-xl bg-info text-white mx-auto mb-3">
                        <i class="bi bi-check2-all fs-1"></i>
                    </div>
                    <h3 class="text-info fw-bold">Anda Sudah Melakukan Absen Pulang!</h3>
                    <p class="text-muted mb-4">
                        Waktu Check-Out: <strong>{{ \Carbon\Carbon::parse($attendance->check_out)->format('H:i') }} WIB</strong>. Selamat beristirahat!
                    </p>
                    <a href="{{ route('employee.dashboard') }}" class="btn btn-primary px-4">
                        <i class="bi bi-arrow-left me-1"></i> Kembali ke Dashboard
                    </a>
                </div>
            </div>
        @else
            <div class="card shadow-sm border-0 mb-4">
                <div class="card-body p-4">
                    <div class="text-center mb-4">
                        <div class="avatar avatar-xl bg-light-danger text-danger mx-auto mb-3">
                            <i class="bi bi-box-arrow-right fs-1"></i>
                        </div>
                        <h4 class="fw-bold mb-1">Konfirmasi Absen Pulang</h4>
                        <p class="text-muted">Halo, <strong>{{ $employee->name }}</strong>. Anda check-in masuk hari ini pada pukul <strong>{{ \Carbon\Carbon::parse($attendance->check_in)->format('H:i') }} WIB</strong>.</p>
                    </div>

                    {{-- Live Clock Display --}}
                    <div class="bg-light p-4 rounded-3 text-center mb-4">
                        <small class="text-muted d-block mb-1">WAKTU SAAT INI</small>
                        <h1 class="display-5 fw-bold text-danger mb-0" id="checkout-live-clock">{{ now()->format('H:i:s') }}</h1>
                        <small class="text-muted">Waktu Indonesia Barat (WIB)</small>
                    </div>

                    {{-- GPS Indicator --}}
                    <div class="bg-light p-3 rounded-3 mb-4">
                        <div class="d-flex align-items-center justify-content-between">
                            <span class="text-xs text-muted"><i class="bi bi-geo-alt-fill text-danger me-1"></i> Lokasi GPS Terdeteksi:</span>
                            <span class="badge bg-success" id="checkout-gps-status">Mendeteksi...</span>
                        </div>
                    </div>

                    <form id="form-checkout">
                        @csrf
                        <input type="hidden" name="latitude" id="checkout-latitude">
                        <input type="hidden" name="longitude" id="checkout-longitude">

                        <button type="submit" id="btn-submit-checkout" class="btn btn-danger btn-lg w-100 py-3 shadow" disabled>
                            <i class="bi bi-box-arrow-right me-2 fs-5"></i>
                            <span class="fw-bold fs-5">KONFIRMASI ABSEN PULANG SEKARANG</span>
                        </button>
                    </form>
                </div>
            </div>
        @endif
    </div>
</div>
@endsection

@push('scripts')
<script>
    function updateCheckoutClock() {
        const now = new Date();
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        const clockEl = document.getElementById('checkout-live-clock');
        if (clockEl) {
            clockEl.innerText = `${hours}:${minutes}:${seconds}`;
        }
    }
    setInterval(updateCheckoutClock, 1000);

    document.addEventListener('DOMContentLoaded', function() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                (pos) => {
                    const lat = pos.coords.latitude;
                    const lng = pos.coords.longitude;
                    document.getElementById('checkout-latitude').value = lat;
                    document.getElementById('checkout-longitude').value = lng;
                    document.getElementById('checkout-gps-status').innerText = `${lat.toFixed(4)}, ${lng.toFixed(4)}`;
                    const btn = document.getElementById('btn-submit-checkout');
                    if (btn) btn.disabled = false;
                },
                (err) => {
                    document.getElementById('checkout-gps-status').className = 'badge bg-warning text-dark';
                    document.getElementById('checkout-gps-status').innerText = 'Izin Lokasi Belum Aktif';
                    const btn = document.getElementById('btn-submit-checkout');
                    if (btn) btn.disabled = false; // still allow or prompt
                }
            );
        }
    });

    const formCheckout = document.getElementById('form-checkout');
    if (formCheckout) {
        formCheckout.addEventListener('submit', function(e) {
            e.preventDefault();

            Swal.fire({
                title: 'Memproses Check-Out...',
                text: 'Mencatat jam pulang Anda...',
                allowOutsideClick: false,
                didOpen: () => Swal.showLoading()
            });

            const formData = {
                _token: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                latitude: document.getElementById('checkout-latitude').value || 0,
                longitude: document.getElementById('checkout-longitude').value || 0,
            };

            fetch("{{ route('employee.attendance.check-out.post') }}", {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': formData._token
                },
                body: JSON.stringify(formData)
            })
            .then(res => res.json().then(data => ({ status: res.status, body: data })))
            .then(res => {
                if (res.status === 200 && res.body.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Absen Pulang Berhasil!',
                        text: res.body.message,
                        confirmButtonText: 'Selesai'
                    }).then(() => {
                        window.location.href = "{{ route('employee.dashboard') }}";
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Check-Out Gagal',
                        text: res.body.message || 'Terjadi kesalahan.',
                    });
                }
            })
            .catch(err => {
                Swal.fire('Error', 'Terjadi kesalahan koneksi.', 'error');
            });
        });
    }
</script>
@endpush
