@extends('layouts.app')

@section('title', 'RFID Pulang - MagangTime')
@section('page-title', 'RFID Presensi Pulang')

@section('content')
<div class="row">
    <!-- RFID Scanner Card - Responsive Version -->
    <div class="col-12 mb-3">
        <div class="card border-warning shadow-sm">
            <div class="card-header bg-warning text-dark py-2">
                <div class="row align-items-center">
                    <div class="col-12">
                        <h6 class="mb-0"><i class="fas fa-id-card me-2"></i>Scanner RFID Pulang</h6>
                    </div>
                </div>
            </div>
            <div class="card-body py-3">
                <form id="rfidForm" class="mb-2">
                    @csrf
                    <div class="row g-2 align-items-end">
                        <div class="col-12 col-md-8">
                            <label class="form-label mb-1 small">Scan Kartu RFID</label>
                            <input type="text" id="rfidInput" name="rfid_number" class="form-control" 
                                   placeholder="Tempelkan kartu RFID pada reader..." autocomplete="off">
                        </div>
                        <div class="col-12 col-md-4">
                            <button type="submit" class="btn btn-warning w-100 text-dark">
                                <i class="fas fa-sign-out-alt me-1"></i>Presensi Pulang
                            </button>
                        </div>
                    </div>
                </form>
                
                <!-- Recent Scan Display -->
                <div id="recentScan" class="d-none">
                    <div class="alert alert-warning py-2 mb-0 mt-2">
                        <div class="text-center">
                            <small class="text-dark fw-bold">Presensi Berhasil!</small>
                            <div><strong id="scanName">-</strong> | <span id="scanTime">-</span></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Today's Checkout Data -->
    <div class="col-12">
        <div class="card">
            <div class="card-header bg-white">
                <div class="row align-items-center">
                    <div class="col-12">
                        <h5 class="mb-0"><i class="fas fa-list me-2"></i>Presensi Pulang Hari Ini</h5>
                    </div>
                </div>
            </div>
            <div class="card-body">
                {{-- Desktop Table --}}
                <div class="table-responsive d-none d-md-block">
                    <table class="table table-striped table-hover">
                        <thead class="table-dark">
                            <tr>
                                <th width="5%" class="text-center">No</th>
                                <th>Nama Siswa</th>
                                <th>Sekolah</th>
                                <th width="15%" class="text-center">Jam Masuk</th>
                                <th width="15%" class="text-center">Jam Pulang</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($todayAttendance as $i => $att)
                            <tr>
                                <td class="text-center">{{ $todayAttendance->firstItem() + $i }}</td>
                                <td>
                                    <div class="fw-bold">{{ $att->user->siswa->nama_siswa ?? '-' }}</div>
                                    <small class="text-muted">{{ $att->user->username ?? '-' }}</small>
                                </td>
                                <td>{{ $att->user->siswa->sekolah->nama_sekolah ?? '-' }}</td>
                                <td class="text-center">
                                    <span class="badge bg-success">
                                        {{ $att->formatted_check_in_time ?? '-' }}
                                    </span>
                                </td>
                                <td class="text-center">
                                    <span class="badge bg-warning text-dark">
                                        {{ $att->formatted_check_out_time ?? '-' }}
                                    </span>
                                </td>
                            </tr>
                            @empty
                            <tr>
                                <td colspan="5" class="text-center text-muted py-4">
                                    <i class="fas fa-clock fa-3x mb-3"></i>
                                    <p>Belum ada presensi pulang hari ini</p>
                                </td>
                            </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>

                {{-- Mobile Cards --}}
                <div class="d-block d-md-none">
                    @forelse($todayAttendance as $i => $att)
                    <div class="card mb-3 border-start border-warning border-4">
                        <div class="card-body py-3">
                            <div class="d-flex justify-content-between align-items-start mb-2">
                                <h6 class="fw-bold mb-1">{{ $att->user->siswa->nama_siswa ?? '-' }}</h6>
                                <small class="text-muted">#{{ $todayAttendance->firstItem() + $i }}</small>
                            </div>
                            
                            <div class="mb-2">
                                <small class="text-muted">Username:</small><br>
                                <small>{{ $att->user->username ?? '-' }}</small>
                            </div>
                            
                            <div class="mb-2">
                                <small class="text-muted">Sekolah:</small><br>
                                <small>{{ $att->user->siswa->sekolah->nama_sekolah ?? '-' }}</small>
                            </div>
                            
                            <div class="row">
                                <div class="col-6">
                                    <small class="text-muted">Jam Masuk:</small><br>
                                    <span class="badge bg-success">
                                        {{ $att->formatted_check_in_time ?? '-' }}
                                    </span>
                                </div>
                                <div class="col-6">
                                    <small class="text-muted">Jam Pulang:</small><br>
                                    <span class="badge bg-warning text-dark">
                                        {{ $att->formatted_check_out_time ?? '-' }}
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                    @empty
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-clock fa-3x mb-3"></i>
                        <p>Belum ada presensi pulang hari ini</p>
                    </div>
                    @endforelse
                </div>
                
                @if($todayAttendance->hasPages())
                    {{ $todayAttendance->appends(request()->query())->links('pagination::bootstrap-4') }}
                @endif
            </div>
        </div>
    </div>
</div>

<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const rfidForm = document.getElementById('rfidForm');
    const rfidInput = document.getElementById('rfidInput');
    const recentScan = document.getElementById('recentScan');
    const submitBtn = rfidForm.querySelector('button[type="submit"]');
    const originalButtonText = submitBtn.innerHTML;
    
    let isProcessing = false; // Flag untuk mencegah multiple submit
    
    // Focus on RFID input
    rfidInput.focus();
    
    // Auto-submit when RFID is scanned (assuming RFID reader sends data + enter)
    rfidInput.addEventListener('input', function() {
        if (this.value.length >= 8 && !isProcessing) { // Minimum RFID length
            setTimeout(() => rfidForm.requestSubmit(), 100);
        }
    });
    
    rfidForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        // Cegah multiple submit
        if (isProcessing) {
            return;
        }
        
        if (!rfidInput.value.trim()) {
            showSweetAlert('error', 'Silakan scan kartu RFID terlebih dahulu!');
            return;
        }
        
        // Set flag processing
        isProcessing = true;
        
        const formData = new FormData(this);
        
        // Ubah tombol ke loading state
        setButtonLoading(true);
        
        fetch('{{ route("admin.rfid.process.pulang") }}', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showRecentScan(data.data);
                // Tampilkan Swal success, lalu reload setelah Swal tertutup
                Swal.fire({
                    icon: 'success',
                    title: 'Berhasil',
                    text: data.message,
                    timer: 1800,
                    showConfirmButton: false,
                    timerProgressBar: true
                }).then(() => {
                    location.reload();
                });
            } else {
                showSweetAlert('error', data.message);
                resetForm();
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showSweetAlert('error', 'Terjadi kesalahan sistem!');
            resetForm();
        });
    });
    
    function setButtonLoading(loading) {
        if (loading) {
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Memproses...';
        } else {
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalButtonText;
        }
    }
    
    function resetForm() {
        // Reset semua state
        isProcessing = false;
        setButtonLoading(false);
        rfidInput.value = '';
        rfidInput.focus();
    }
    
    function showSweetAlert(type, message) {
        // Semua alert error, warning, dan info sekarang menggunakan timer
        if (type === 'success') {
            Swal.fire({ 
                icon: 'success', 
                title: 'Sukses', 
                text: message, 
                timer: 1800, 
                showConfirmButton: false, 
                timerProgressBar: true 
            });
        } else if (type === 'error') {
            Swal.fire({ 
                icon: 'error', 
                title: 'Gagal', 
                text: message, 
                timer: 1800, 
                showConfirmButton: false, 
                timerProgressBar: true 
            });
        } else if (type === 'warning') {
            Swal.fire({ 
                icon: 'warning', 
                title: 'Peringatan', 
                text: message, 
                timer: 1800, 
                showConfirmButton: false, 
                timerProgressBar: true 
            });
        } else if (type === 'info') {
            Swal.fire({ 
                icon: 'info', 
                title: 'Info', 
                text: message, 
                timer: 1800, 
                showConfirmButton: false, 
                timerProgressBar: true 
            });
        }
    }
    
    function showRecentScan(data) {
        document.getElementById('scanName').textContent = data.nama;
        document.getElementById('scanTime').textContent = data.waktu;
        recentScan.classList.remove('d-none');
        
        setTimeout(() => {
            recentScan.classList.add('d-none');
        }, 5000);
    }
});
</script>
@endsection