@extends('layouts.master')

@section('title', 'Monthly Attendance – VIP Dashboard')

@section('content')
    <div class="az-content-breadcrumb mb-3">
        <span>Attendance</span>
    </div>

    {{-- Month Filter --}}
    <div class="mb-4">
        <form method="GET" class="d-flex gap-2 align-items-center">
            <label class="fw-semibold">Select Month:</label>
            <input type="month" name="month_year" value="{{ $monthYear }}" class="form-control w-auto">
            <button class="btn btn-primary">View</button>
        </form>
    </div>

    @foreach ($departmentsWithEmployees as $departmentName => $employees)
        <div class="card shadow-lg border-0 mb-5 department-card">
            <div class="card-header bg-gradient-primary py-3 d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="fas fa-building me-2"></i>{{ $departmentName }}</h5>
                <span>{{ \Carbon\Carbon::parse($monthYear)->format('F Y') }}</span>
            </div>

            <div class="card-body">
                @if ($employees->isEmpty())
                    <p class="text-muted text-center">No employees in this department.</p>
                @else
                    <div class="row g-4">
                        @foreach ($employees as $employee)
                            @php
                                $present = $employee->attendances->where('status', 'present')->count();
                                $absent = $employee->attendances->where('status', 'absent')->count();
                                $late = $employee->attendances->where('status', 'late')->count();
                                $halfday = $employee->attendances->where('status', 'half-day')->count();
                                $recentAttendances = $employee->attendances->sortByDesc('date')->take(10);
                                $total = max($present + $absent + $late + $halfday, 1);
                            @endphp

                            <div class="col-md-3 col-lg-3">
                                <div class="employee-card shadow-sm border rounded-4 d-flex flex-column h-100 p-3">

                                    {{-- Employee Header --}}
                                    <div class="d-flex align-items-center mb-3">
                                        <div class="employee-photo-wrapper me-3">
                                            <img src="{{ asset('uploads/employees/' . ($employee->photo ?? 'default_user.png')) }}"
                                                alt="Profile" style="width: 60px;height: 60px"
                                                class="employee-photo rounded-circle">
                                        </div>
                                        <div>
                                            <h6 class="fw-bold mb-1">{{ $employee->first_name }} {{ $employee->last_name }}
                                            </h6>
                                            <small class="text-muted">{{ $employee->employee_no }} |
                                                {{ $employee->designation->title ?? 'N/A' }}</small>
                                            <br>
                                            <small class="text-muted">{{ $departmentName }}</small>
                                        </div>
                                    </div>

                                    {{-- Mini Stats Badges --}}
                                    <div class="d-flex gap-2 flex-wrap mb-3">
                                        <div class="badge bg-success text-white flex-fill p-2 text-center">Present:
                                            {{ $present }}</div>
                                        <div class="badge bg-danger text-white flex-fill p-2 text-center">Absent:
                                            {{ $absent }}</div>
                                        <div class="badge bg-warning text-dark flex-fill p-2 text-center">Late:
                                            {{ $late }}</div>
                                        <div class="badge bg-info text-dark flex-fill p-2 text-center">Half-day:
                                            {{ $halfday }}</div>
                                    </div>

                                    {{-- Donut Chart --}}
                                    <div class="my-2" style="height:160px;">
                                        <canvas id="chart-{{ $employee->id }}"></canvas>
                                    </div>

                                    {{-- Recent Attendance List --}}
                                    <div class="attendance-list mt-auto">
                                        <h6 class="fw-semibold mb-2">Recent Attendance</h6>
                                        <div class="list-group mb-2">
                                            @foreach ($recentAttendances as $att)
                                                <div
                                                    class="list-group-item d-flex justify-content-between align-items-center">
                                                    <div>
                                                        <strong>{{ \Carbon\Carbon::parse($att->date)->format('d M, Y') }}</strong><br>
                                                        <small class="text-muted">
                                                            IN: {{ $att->check_in?->format('h:i A') ?? '—' }} |
                                                            OUT: {{ $att->check_out?->format('h:i A') ?? '—' }}
                                                        </small>
                                                    </div>
                                                    <span
                                                        class="badge
                                                        @if ($att->status == 'present') bg-success
                                                        @elseif($att->status == 'late') bg-warning text-dark
                                                        @elseif($att->status == 'half-day') bg-info text-dark
                                                        @elseif($att->status == 'absent') bg-danger
                                                        @else bg-secondary @endif">
                                                        {{ ucfirst($att->status ?? '-') }}
                                                    </span>
                                                </div>
                                            @endforeach
                                        </div>
                                        <a href="{{ url('/attendance/details/' . Crypt::encrypt($employee->id)) }}"
                                            class="btn btn-sm btn-primary w-100">
                                            View All
                                        </a>
                                    </div>

                                </div>
                            </div>
                        @endforeach
                    </div>
                @endif
            </div>
        </div>
    @endforeach

    {{-- Modal --}}
    <div class="modal fade" id="attendanceModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header bg-gradient-primary text-white">
                    <h5 class="modal-title">Attendance Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="attendanceModalBody">
                    <p class="text-center text-muted">Select an employee to view attendance.</p>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('styles')
    <style>
        .employee-card {
            border-radius: 15px;
            transition: .25s;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        .employee-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 30px rgba(0, 0, 0, .15);
        }

        .employee-photo-wrapper {
            width: 40px;
            height: 40px;
            flex-shrink: 0;
            overflow: hidden;
            border-radius: 50%;
            background: #f0f0f0;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .employee-photo-wrapper img.employee-photo {
            width: 100%;
            height: 100%;
            object-fit: cover;
            display: block;
        }

        .attendance-list {
            max-height: 200px;
            overflow-y: auto;
        }

        .list-group-item {
            border-left: 4px solid #e9ecef;
            margin-bottom: 5px;
            border-radius: 6px;
            padding: 0.5rem 0.75rem;
        }

        .badge {
            font-size: 12px;
            padding: 5px;
        }

        .bg-gradient-primary {
            background: linear-gradient(45deg, #007bff, #6610f2);
        }
    </style>
@endpush

@push('scripts')
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        let attendanceModal = new bootstrap.Modal(document.getElementById('attendanceModal'));

        function viewAllAttendance(empId) {
            window.location.href = `/attendance/details/${empId}`;
        }
        // Render donut charts for each employee
        @foreach ($departmentsWithEmployees as $dept => $employees)
            @foreach ($employees as $emp)
                const ctx{{ $emp->id }} = document.getElementById('chart-{{ $emp->id }}').getContext('2d');
                new Chart(ctx{{ $emp->id }}, {
                    type: 'doughnut',
                    data: {
                        labels: ['Present', 'Absent', 'Late', 'Half-day'],
                        datasets: [{
                            data: [
                                {{ $emp->attendances->where('status', 'present')->count() }},
                                {{ $emp->attendances->where('status', 'absent')->count() }},
                                {{ $emp->attendances->where('status', 'late')->count() }},
                                {{ $emp->attendances->where('status', 'half-day')->count() }}
                            ],
                            backgroundColor: ['#28a745', '#dc3545', '#ffc107', '#17a2b8'],
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        cutout: '60%',
                        plugins: {
                            legend: {
                                position: 'bottom',
                                labels: {
                                    boxWidth: 12
                                }
                            }
                        }
                    }
                });
            @endforeach
        @endforeach
    </script>
@endpush
