@extends('layouts.dashboard.superadminapp')

@section('title', 'Employee Attendance Calendar')

@section('styles')
<link href="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.8/index.global.min.css" rel="stylesheet">
<style>
    /* Calendar Container */
    #calendar {
        min-height: 500px;
        width: 100%;
        background: #fff;
    }

    /* Header styling - Day names */
    .fc .fc-col-header-cell {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%) !important;
        padding: 10px 0 !important;
    }
    .fc .fc-col-header-cell-cushion {
        color: #fff !important;
        font-weight: 600 !important;
        font-size: 0.9rem !important;
        text-decoration: none !important;
    }
    /* Sunday header - ensure visibility */
    .fc .fc-col-header-cell.fc-day-sun {
        background: linear-gradient(135deg, #dc3545 0%, #b21f2d 100%) !important;
    }
    .fc .fc-col-header-cell.fc-day-sun .fc-col-header-cell-cushion,
    .fc .fc-col-header-cell.fc-day-sun a {
        color: #fff !important;
        font-weight: 700 !important;
    }

    /* Title styling */
    .fc .fc-toolbar-title {
        font-size: 1.25rem !important;
        font-weight: 700 !important;
        color: #333 !important;
    }

    /* Day number styling */
    .fc .fc-daygrid-day-number {
        font-weight: 700 !important;
        font-size: 1rem !important;
        color: #333 !important;
        padding: 8px !important;
    }

    /* Day cell styling */
    .fc .fc-daygrid-day {
        min-height: 80px !important;
    }
    .fc .fc-daygrid-day-frame {
        min-height: 80px !important;
    }

    /* Status backgrounds */
    .fc .fc-daygrid-day.present {
        background: #d4edda !important;
    }
    .fc .fc-daygrid-day.present .fc-daygrid-day-number {
        color: #155724 !important;
    }

    .fc .fc-daygrid-day.absent {
        background: #f8d7da !important;
    }
    .fc .fc-daygrid-day.absent .fc-daygrid-day-number {
        color: #721c24 !important;
    }

    .fc .fc-daygrid-day.leave {
        background: #fff3cd !important;
    }
    .fc .fc-daygrid-day.leave .fc-daygrid-day-number {
        color: #856404 !important;
    }

    .fc .fc-daygrid-day.lop {
        background: #ffe4c4 !important;
    }
    .fc .fc-daygrid-day.lop .fc-daygrid-day-number {
        color: #c45c00 !important;
    }

    /* Today highlight */
    .fc .fc-day-today {
        background: #e3f2fd !important;
    }
    .fc .fc-day-today .fc-daygrid-day-number {
        background: #4e73df;
        color: #fff !important;
        border-radius: 50%;
        width: 28px;
        height: 28px;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    /* Sunday styling */
    .fc .fc-day-sun {
        background: #fafafa !important;
    }
    .fc .fc-day-sun .fc-daygrid-day-number {
        color: #dc3545 !important;
    }

    /* Event/Status text inside cells */
    .fc .fc-event {
        font-size: 0.75rem !important;
        font-weight: 600 !important;
        padding: 2px 6px !important;
        border-radius: 4px !important;
        margin: 2px !important;
    }

    /* Grid borders */
    .fc .fc-scrollgrid {
        border: 1px solid #dee2e6 !important;
    }
    .fc .fc-scrollgrid td, .fc .fc-scrollgrid th {
        border: 1px solid #dee2e6 !important;
    }

    /* Other month days */
    .fc .fc-day-other .fc-daygrid-day-number {
        color: #adb5bd !important;
    }

    .fc .fc-daygrid-body, .fc .fc-daygrid-body-natural {
        min-height: 400px !important;
    }

    /* Legend badge */
    .legend-badge {
        font-size: 0.85rem;
        font-weight: 500;
        border-radius: 12px;
        margin-right: 10px;
        padding: 5px 12px;
        display: inline-block;
    }

    /* Summary section */
    .summary-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 10px 0;
        border-bottom: 1px dashed #dee2e6;
    }
    .summary-item:last-child {
        border-bottom: none;
    }
    .summary-label {
        font-weight: 500;
        color: #495057;
    }
    .summary-count {
        font-weight: 700;
        font-size: 1.1rem;
    }

    /* Status label inside day cell */
    .status-label {
        font-size: 0.75rem;
        font-weight: 600;
        text-align: center;
        padding: 2px 0;
    }
</style>
@endsection

@section('content')

<!-- Page Heading -->
<div class="bg-white p-2 d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h5 mb-0 text-gray-800">UEPL | Employee Attendance Calendar</h1>
    <div class="display-date">
        <span id="day">day</span>,
        <span id="daynum">00</span>
        <span id="month">month</span>
        <span id="year">0000</span>
    </div>
    <div class="display-time"></div>
</div>

<!-- Alerts -->
@if(session('success'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle mr-2"></i>{{ session('success') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif
@if(session('error'))
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle mr-2"></i>{{ session('error') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif

<div class="row">
    <!-- Calendar Section -->
    <div class="col-lg-8 col-md-12 mb-4">
        <!-- Filter Card -->
        <div class="card shadow mb-4">
            <div class="card-header py-3" style="background: linear-gradient(135deg, #6c757d 0%, #495057 100%);">
                <h6 class="m-0 font-weight-bold text-white">
                    <i class="fas fa-filter mr-2"></i> Filter Options
                </h6>
            </div>
            <div class="card-body">
                <form method="GET" class="row">
                    <div class="col-md-6 mb-3">
                        <label class="small font-weight-bold">Select Employee <span class="text-danger">*</span></label>
                        <select name="employee_id" class="form-control" onchange="this.form.submit()">
                            <option value="">-- Select Employee --</option>
                            @foreach($employees as $emp)
                                <option value="{{ $emp->employee_id }}" @if(request('employee_id') == $emp->employee_id) selected @endif>
                                    {{ $emp->employee_id }} - {{ $emp->name }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="small font-weight-bold">Select Month <span class="text-danger">*</span></label>
                        <input type="month" name="month" class="form-control" value="{{ $month }}" onchange="this.form.submit()">
                    </div>
                </form>
            </div>
        </div>

        <!-- Calendar Card -->
        <div class="card shadow mb-4">
            <div class="card-header py-3 d-flex justify-content-between align-items-center" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
                <h6 class="m-0 font-weight-bold text-white">
                    <i class="fas fa-calendar-alt mr-2"></i> Attendance Calendar
                </h6>
                <div>
                    <a href="{{ route('superadmin.attendance.matrix') }}" class="btn btn-light btn-sm">
                        <i class="fas fa-th-large mr-1"></i> Matrix View
                    </a>
                    <a href="{{ route('superadmin.employee.employeedailyreport') }}" class="btn btn-light btn-sm ml-2">
                        <i class="fas fa-list mr-1"></i> Daily Reports
                    </a>
                </div>
            </div>
            <div class="card-body">
                <!-- Legend -->
                <div class="mb-3">
                    <span class="legend-badge badge badge-success">Present</span>
                    <span class="legend-badge badge badge-warning text-dark">CL/SL/PL</span>
                    <span class="legend-badge badge" style="background:#fd7e14;color:#fff;">LOP</span>
                    <span class="legend-badge badge badge-danger">Absent</span>
                </div>
                <div id="calendar"></div>
            </div>
        </div>
    </div>

    <!-- Summary Section -->
    <div class="col-lg-4 col-md-12 mb-4">
        <div class="card shadow mb-4">
            <div class="card-header py-3" style="background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);">
                <h6 class="m-0 font-weight-bold text-white">
                    <i class="fas fa-chart-bar mr-2"></i> Monthly Summary
                </h6>
            </div>
            <div class="card-body">
                @php
                    $totalDays = 0;
                    $present = 0; $absent = 0; $lop = 0; $cl = 0; $sl = 0; $pl = 0;
                    $totalOt = 0; $totalShortage = 0;

                    foreach($attendanceMap as $day => $status) {
                        $totalDays++;
                        if($status === 'Present') $present++;
                        elseif($status === 'Absent') $absent++;
                        elseif(strtoupper($status) === 'LOP') $lop++;
                        elseif(strtoupper($status) === 'CL') $cl++;
                        elseif(strtoupper($status) === 'SL') $sl++;
                        elseif(strtoupper($status) === 'PL') $pl++;
                    }

                    // Calculate OT and Shortage hours from $attendanceData if available
                    if(isset($attendanceData)) {
                        foreach($attendanceData as $row) {
                            $checkIn = $row->check_in ? \Carbon\Carbon::parse($row->check_in) : null;
                            $breakOut = $row->break_out ? \Carbon\Carbon::parse($row->break_out) : null;
                            $breakIn = $row->break_in ? \Carbon\Carbon::parse($row->break_in) : null;
                            $checkOut = $row->check_out ? \Carbon\Carbon::parse($row->check_out) : null;

                            $workMinutes = 0;
                            if ($checkIn && $checkOut) {
                                $total = $checkIn->diffInMinutes($checkOut);
                                $break = ($breakIn && $breakOut) ? $breakOut->diffInMinutes($breakIn) : 0;
                                $workMinutes = max(0, $total - $break);
                            }
                            $workHours = round($workMinutes / 60, 2);
                            $requiredHours = 9;

                            $ot = $workHours > $requiredHours ? $workHours - $requiredHours : 0;
                            $shortage = $workHours < $requiredHours ? $requiredHours - $workHours : 0;

                            $totalOt += $ot;
                            $totalShortage += $shortage;
                        }
                    }

                    $attendanceRate = $totalDays > 0 ? round(($present / $totalDays) * 100, 1) : 0;
                @endphp

                @if(request('employee_id'))
                    <!-- Attendance Rate -->
                    <div class="text-center mb-4">
                        <h2 class="font-weight-bold {{ $attendanceRate >= 90 ? 'text-success' : ($attendanceRate >= 75 ? 'text-warning' : 'text-danger') }}">
                            {{ $attendanceRate }}%
                        </h2>
                        <small class="text-muted">Attendance Rate</small>
                    </div>

                    <div class="summary-item">
                        <span class="summary-label"><i class="fas fa-check-circle text-success mr-2"></i>Present</span>
                        <span class="summary-count text-success">{{ $present }}</span>
                    </div>
                    <div class="summary-item">
                        <span class="summary-label"><i class="fas fa-umbrella-beach text-info mr-2"></i>CL (Casual Leave)</span>
                        <span class="summary-count text-info">{{ $cl }}</span>
                    </div>
                    <div class="summary-item">
                        <span class="summary-label"><i class="fas fa-medkit text-warning mr-2"></i>SL (Sick Leave)</span>
                        <span class="summary-count text-warning">{{ $sl }}</span>
                    </div>
                    <div class="summary-item">
                        <span class="summary-label"><i class="fas fa-gift text-primary mr-2"></i>PL (Privilege Leave)</span>
                        <span class="summary-count text-primary">{{ $pl }}</span>
                    </div>
                    <div class="summary-item">
                        <span class="summary-label"><i class="fas fa-exclamation-triangle mr-2" style="color:#fd7e14;"></i>LOP</span>
                        <span class="summary-count" style="color:#fd7e14;">{{ $lop }}</span>
                    </div>
                    <div class="summary-item">
                        <span class="summary-label"><i class="fas fa-times-circle text-danger mr-2"></i>Absent</span>
                        <span class="summary-count text-danger">{{ $absent }}</span>
                    </div>

                    <hr class="my-3">

                    <div class="summary-item">
                        <span class="summary-label"><i class="fas fa-clock text-success mr-2"></i>OT Hours</span>
                        <span class="summary-count text-success">{{ number_format($totalOt, 2) }}</span>
                    </div>
                    <div class="summary-item">
                        <span class="summary-label"><i class="fas fa-hourglass-half text-danger mr-2"></i>Shortage Hours</span>
                        <span class="summary-count text-danger">{{ number_format($totalShortage, 2) }}</span>
                    </div>

                    <hr class="my-3">

                    <div class="summary-item">
                        <span class="summary-label"><i class="fas fa-calendar-day text-secondary mr-2"></i>Total Days</span>
                        <span class="summary-count text-secondary">{{ $totalDays }}</span>
                    </div>
                @else
                    <div class="text-center text-muted py-4">
                        <i class="fas fa-user-clock fa-3x mb-3"></i>
                        <p>Select an employee to view their monthly summary</p>
                    </div>
                @endif
            </div>
        </div>

        <!-- Quick Stats Card -->
        @if(request('employee_id'))
        <div class="card shadow">
            <div class="card-header py-3" style="background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%);">
                <h6 class="m-0 font-weight-bold text-white">
                    <i class="fas fa-info-circle mr-2"></i> Quick Stats
                </h6>
            </div>
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-6 mb-3">
                        <div class="p-2 rounded" style="background:#d4edda;">
                            <h4 class="font-weight-bold text-success mb-0">{{ $present + $cl + $sl + $pl }}</h4>
                            <small class="text-muted">Total Present + Leaves</small>
                        </div>
                    </div>
                    <div class="col-6 mb-3">
                        <div class="p-2 rounded" style="background:#ffeaea;">
                            <h4 class="font-weight-bold text-danger mb-0">{{ $absent + $lop }}</h4>
                            <small class="text-muted">Absent + LOP</small>
                        </div>
                    </div>
                </div>
                @php
                    $netHours = $totalOt - $totalShortage;
                @endphp
                <div class="text-center mt-2">
                    <span class="small font-weight-bold">Net Hours Balance:</span>
                    <h5 class="font-weight-bold {{ $netHours >= 0 ? 'text-success' : 'text-danger' }}">
                        {{ $netHours >= 0 ? '+' : '' }}{{ number_format($netHours, 2) }} hrs
                    </h5>
                </div>
            </div>
        </div>
        @endif
    </div>
</div>

@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.8/index.global.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    let attendanceMap = @json($attendanceMap ?? []);
    let month = "{{ $month }}";
    let firstDay = new Date(month + '-01');
    let lastDay = new Date(firstDay.getFullYear(), firstDay.getMonth() + 1, 0);

    let events = [];
    for (let d = new Date(firstDay); d <= lastDay; d.setDate(d.getDate() + 1)) {
        let ymd = d.toISOString().slice(0,10);
        let status = attendanceMap[ymd] ?? '';
        // Add events for leaves and LOP with colored backgrounds
        if (['CL','SL','PL'].includes(status)) {
            events.push({
                title: status,
                start: ymd,
                display: 'block',
                backgroundColor: '#ffc107',
                borderColor: '#d39e00',
                textColor: '#212529'
            });
        } else if (status === 'LOP') {
            events.push({
                title: 'LOP',
                start: ymd,
                display: 'block',
                backgroundColor: '#fd7e14',
                borderColor: '#e56b00',
                textColor: '#fff'
            });
        }
    }

    let calendarEl = document.getElementById('calendar');
    if (calendarEl) {
        let calendar = new FullCalendar.Calendar(calendarEl, {
            initialView: 'dayGridMonth',
            initialDate: firstDay,
            firstDay: 0,
            height: "auto",
            fixedWeekCount: false,
            contentHeight: "auto",
            expandRows: true,
            headerToolbar: {
                left: 'title',
                center: '',
                right: ''
            },
            events: events,
            dayCellClassNames: function(arg) {
                let ymd = arg.date.toISOString().slice(0,10);
                let status = attendanceMap[ymd] ?? '';
                // Sunday and nothing: keep default
                if (arg.date.getDay() === 0 && (!status || status === '')) return [];
                if (status === 'Present') return ['present'];
                if (['CL','SL','PL'].includes(status)) return ['leave'];
                if (status === 'LOP') return ['lop'];
                if (status === 'Absent') return ['absent'];
                return [];
            },
            dayCellDidMount: function(info) {
                let ymd = info.date.toISOString().slice(0,10);
                let status = attendanceMap[ymd] ?? '';

                // Create status label
                let label = document.createElement('div');
                label.style.fontSize = '0.7rem';
                label.style.fontWeight = '700';
                label.style.textAlign = 'center';
                label.style.padding = '3px 6px';
                label.style.borderRadius = '4px';
                label.style.margin = '4px';
                label.style.textTransform = 'uppercase';
                label.style.letterSpacing = '0.5px';

                if (status === 'Absent') {
                    label.textContent = "Absent";
                    label.style.backgroundColor = '#dc3545';
                    label.style.color = '#fff';
                    info.el.querySelector('.fc-daygrid-day-events')?.appendChild(label);
                } else if (status === 'Present') {
                    label.textContent = "Present";
                    label.style.backgroundColor = '#28a745';
                    label.style.color = '#fff';
                    info.el.querySelector('.fc-daygrid-day-events')?.appendChild(label);
                }
            }
        });
        calendar.render();
    }
});
</script>
@endsection
