@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: 150px !important;
    }
    .fc .fc-daygrid-day-frame {
        min-height: 150px !important;
        position: relative !important;
    }
    .fc .fc-daygrid-day-events {
        margin-top: 0 !important;
        padding: 0 2px !important;
    }
    .fc .fc-daygrid-day-top {
        flex-direction: row-reverse !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;
    }

    /* Holiday styling */
    .fc .fc-daygrid-day.holiday {
        background: linear-gradient(135deg, #e0f7fa 0%, #b2ebf2 100%) !important;
    }
    .fc .fc-daygrid-day.holiday .fc-daygrid-day-number {
        color: #00695c !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 - Weekly Off */
    .fc .fc-day-sun {
        background: #fce4e4 !important;
    }
    .fc .fc-day-sun .fc-daygrid-day-number {
        color: #8b0000 !important;
        font-weight: 700 !important;
    }

    /* Sunday with weekly off status */
    .fc .fc-daygrid-day.sunday-off {
        background: linear-gradient(135deg, #fce4e4 0%, #f5c6c6 100%) !important;
    }
    .fc .fc-daygrid-day.sunday-off .fc-daygrid-day-number {
        color: #8b0000 !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 -->
<x-layout.page-header title="UEPL | Employee Attendance Calendar" icon="user-tie" iconColor="primary" />

<!-- 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">P - Present</span>
                    <span class="legend-badge badge badge-danger">A - Absent</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" style="background:#00695c;color:#fff;">Holiday</span>
                    <span class="legend-badge badge" style="background:#8b0000;color:#fff;">W/OFF - Sunday</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;
                    $workingDays = 0;
                    $sundays = 0;
                    $holidays = 0;
                    $present = 0; $absent = 0; $lop = 0; $cl = 0; $sl = 0; $pl = 0;

                    foreach($attendanceMap as $day => $status) {
                        $totalDays++;
                        if($status === 'Sunday') {
                            $sundays++;
                        } elseif($status === 'Holiday') {
                            $holidays++;
                        } else {
                            $workingDays++;
                            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++;
                        }
                    }

                    // Use pre-calculated OT and Shortage hours from database (passed from controller)
                    // $otHours and $shortageHours are already calculated in the controller
                    $totalOt = $otHours ?? 0;
                    $totalShortage = $shortageHours ?? 0;

                    // Calculate attendance rate based on working days (excluding Sundays and Holidays)
                    $attendanceRate = $workingDays > 0 ? round(($present / $workingDays) * 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>
                    <div class="summary-item">
                        <span class="summary-label"><i class="fas fa-calendar-week mr-2" style="color:#8b0000;"></i>Sundays (W/OFF)</span>
                        <span class="summary-count" style="color:#8b0000;">{{ $sundays }}</span>
                    </div>
                    <div class="summary-item">
                        <span class="summary-label"><i class="fas fa-star mr-2" style="color:#00695c;"></i>Holidays</span>
                        <span class="summary-count" style="color:#00695c;">{{ $holidays }}</span>
                    </div>
                    <div class="summary-item">
                        <span class="summary-label"><i class="fas fa-briefcase text-primary mr-2"></i>Working Days</span>
                        <span class="summary-count text-primary">{{ $workingDays }}</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 attendanceDetails = @json($attendanceDetails ?? []);
    let holidayMap = @json($holidayMap ?? []);
    let month = "{{ $month }}";
    let firstDay = new Date(month + '-01');
    let lastDay = new Date(firstDay.getFullYear(), firstDay.getMonth() + 1, 0);

    // Helper function to format date as YYYY-MM-DD using local timezone
    function formatLocalDate(date) {
        return date.getFullYear() + '-' + String(date.getMonth() + 1).padStart(2, '0') + '-' + String(date.getDate()).padStart(2, '0');
    }

    let events = [];
    for (let d = new Date(firstDay); d <= lastDay; d.setDate(d.getDate() + 1)) {
        let ymd = formatLocalDate(d);
        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'
            });
        } else if (status === 'Holiday') {
            let holidayName = holidayMap[ymd] ?? 'Holiday';
            events.push({
                title: holidayName,
                start: ymd,
                display: 'block',
                backgroundColor: '#00695c',
                borderColor: '#004d40',
                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) {
                // Use local date to avoid timezone issues
                let d = arg.date;
                let ymd = d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
                let status = attendanceMap[ymd] ?? '';
                let isSunday = d.getDay() === 0;

                // Present takes highest priority
                if (status === 'Present') return ['present'];
                // Holiday
                if (status === 'Holiday') return ['holiday'];
                // Sunday with no work (weekly off)
                if (status === 'Sunday') return ['sunday-off'];
                // Leaves
                if (['CL','SL','PL'].includes(status)) return ['leave'];
                if (status === 'LOP') return ['lop'];
                // Absent
                if (status === 'Absent') return ['absent'];
                return [];
            },
            dayCellDidMount: function(info) {
                // Use local date to avoid timezone issues
                let d = info.date;
                let ymd = d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
                let status = attendanceMap[ymd] ?? '';
                let details = attendanceDetails[ymd] ?? null;
                let isSunday = d.getDay() === 0;

                let dayFrame = info.el.querySelector('.fc-daygrid-day-frame');
                let container = info.el.querySelector('.fc-daygrid-day-events');
                if (!dayFrame) return;

                // Create status label - positioned top left
                let label = document.createElement('div');
                label.style.position = 'absolute';
                label.style.top = '2px';
                label.style.left = '2px';
                label.style.fontSize = '0.7rem';
                label.style.fontWeight = '700';
                label.style.padding = '1px 6px';
                label.style.borderRadius = '3px';
                label.style.zIndex = '10';

                if (status === 'Sunday') {
                    label.textContent = "W/OFF";
                    label.style.backgroundColor = '#8b0000';
                    label.style.color = '#fff';
                    dayFrame.style.position = 'relative';
                    dayFrame.appendChild(label);
                } else if (status === 'Absent') {
                    label.textContent = "A";
                    label.style.backgroundColor = '#dc3545';
                    label.style.color = '#fff';
                    dayFrame.style.position = 'relative';
                    dayFrame.appendChild(label);
                } else if (status === 'Present') {
                    label.textContent = "P";
                    label.style.backgroundColor = '#28a745';
                    label.style.color = '#fff';
                    dayFrame.style.position = 'relative';
                    dayFrame.appendChild(label);

                    // Show attendance details if present
                    if (details && container) {
                        let checkIn = details.check_in ? details.check_in : '-';
                        let checkOut = details.check_out ? details.check_out : '-';
                        let workHrs = details.working_hours ? parseFloat(details.working_hours).toFixed(1) : '0';
                        let otHrs = details.ot_hours ? parseFloat(details.ot_hours).toFixed(1) : '0';
                        let shift = details.shift ? details.shift : '-';
                        let firstHalf = details.first_half ? details.first_half : '-';
                        let secondHalf = details.second_half ? details.second_half : '-';
                        let lateIn = details.late_in ? details.late_in : '-';
                        let earlyOut = details.early_out ? details.early_out : '-';

                        let detailsDiv = document.createElement('div');
                        detailsDiv.style.fontSize = '0.68rem';
                        detailsDiv.style.textAlign = 'left';
                        detailsDiv.style.marginTop = '16px';
                        detailsDiv.style.padding = '0 3px';
                        detailsDiv.style.color = '#333';
                        detailsDiv.style.lineHeight = '1.2';
                        detailsDiv.innerHTML = `
                            <div><b>Shift:</b> ${shift}</div>
                            <div><b>1st:</b> ${firstHalf} | <b>2nd:</b> ${secondHalf}</div>
                            <div><b>In:</b> ${checkIn}</div>
                            <div><b>Out:</b> ${checkOut}</div>
                            <div><b>Work Hrs:</b> ${workHrs}</div>
                            <div><b style="color:#28a745;">OT:</b> <span style="color:#28a745;">${otHrs}</span></div>
                            <div><b style="color:#dc3545;">Late-In:</b> <span style="color:#dc3545;">${lateIn}</span></div>
                            <div><b style="color:#fd7e14;">Early-Out:</b> <span style="color:#fd7e14;">${earlyOut}</span></div>
                        `;
                        container.appendChild(detailsDiv);
                    }
                } else if (['CL','SL','PL'].includes(status)) {
                    label.textContent = status;
                    label.style.backgroundColor = '#ffc107';
                    label.style.color = '#212529';
                    dayFrame.style.position = 'relative';
                    dayFrame.appendChild(label);

                    // Show leave type description
                    let leaveDesc = document.createElement('div');
                    leaveDesc.style.fontSize = '0.7rem';
                    leaveDesc.style.textAlign = 'center';
                    leaveDesc.style.marginTop = '18px';
                    leaveDesc.style.padding = '5px';
                    leaveDesc.style.color = '#856404';
                    leaveDesc.style.fontWeight = '600';
                    let leaveText = status === 'CL' ? 'Casual Leave' : (status === 'SL' ? 'Sick Leave' : 'Privilege Leave');
                    leaveDesc.textContent = leaveText;
                    if (container) container.appendChild(leaveDesc);
                } else if (status === 'LOP') {
                    label.textContent = "LOP";
                    label.style.backgroundColor = '#fd7e14';
                    label.style.color = '#fff';
                    dayFrame.style.position = 'relative';
                    dayFrame.appendChild(label);

                    // Show LOP description
                    let lopDesc = document.createElement('div');
                    lopDesc.style.fontSize = '0.7rem';
                    lopDesc.style.textAlign = 'center';
                    lopDesc.style.marginTop = '18px';
                    lopDesc.style.padding = '5px';
                    lopDesc.style.color = '#fd7e14';
                    lopDesc.style.fontWeight = '600';
                    lopDesc.textContent = 'Loss of Pay';
                    if (container) container.appendChild(lopDesc);
                } else if (status === 'Holiday') {
                    label.textContent = "H";
                    label.style.backgroundColor = '#00695c';
                    label.style.color = '#fff';
                    dayFrame.style.position = 'relative';
                    dayFrame.appendChild(label);

                    // Show Holiday name
                    let holidayName = holidayMap[ymd] ?? 'Public Holiday';
                    let holidayDesc = document.createElement('div');
                    holidayDesc.style.fontSize = '0.7rem';
                    holidayDesc.style.textAlign = 'center';
                    holidayDesc.style.marginTop = '18px';
                    holidayDesc.style.padding = '5px';
                    holidayDesc.style.color = '#00695c';
                    holidayDesc.style.fontWeight = '600';
                    holidayDesc.textContent = holidayName;
                    if (container) container.appendChild(holidayDesc);
                }
            }
        });
        calendar.render();
    }
});
</script>
@endsection
