@extends('layouts.dashboard.superadminapp')

@section('title', 'Daily Attendance & Productivity Report')

@section('styles')
<style>
    div.dt-buttons {
        float: left;
        display: flex !important;
    }
    .dataTable {
        overflow-x: auto !important;
        display: table !important;
    }
    .dt-buttons .btn {
        margin-right: 0.5rem !important;
        padding: 0.25rem 0.75rem !important;
        font-size: 0.95rem !important;
    }
    .stat-card {
        border-radius: 10px;
        padding: 15px;
        text-align: center;
        color: #fff;
        transition: transform 0.2s;
    }
    .stat-card:hover {
        transform: translateY(-3px);
    }
    .stat-card .stat-value {
        font-size: 2rem;
        font-weight: bold;
    }
    .stat-card .stat-label {
        font-size: 0.85rem;
        opacity: 0.9;
    }
    .bg-present { background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%); }
    .bg-absent { background: linear-gradient(135deg, #dc3545 0%, #b21f2d 100%); }
    .bg-leave { background: linear-gradient(135deg, #ffc107 0%, #d39e00 100%); color: #212529 !important; }
    .bg-total { background: linear-gradient(135deg, #4e73df 0%, #224abe 100%); }
    .bg-ot { background: linear-gradient(135deg, #17a2b8 0%, #117a8b 100%); }
    .bg-shortage { background: linear-gradient(135deg, #6c757d 0%, #495057 100%); }
    .row-leave { background-color: #fffbe7 !important; }
    .row-absent { background-color: #ffe6e6 !important; }
    .row-present { background-color: #e6ffe6 !important; }
</style>
@endsection

@section('content')

<!-- Page Heading -->
<x-layout.page-header title="UEPL | Daily Attendance & Productivity Report" 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

<!-- Filter Section -->
<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-3 mb-2">
                <label class="small font-weight-bold">Date</label>
                <input type="date" name="date" class="form-control" value="{{ request('date', date('Y-m-d')) }}">
            </div>
            <div class="col-md-3 mb-2">
                <label class="small font-weight-bold">Department</label>
                <select name="department" class="form-control">
                    <option value="">All Departments</option>
                    @foreach($departments as $dept)
                        <option value="{{ $dept }}" @if(request('department') == $dept) selected @endif>{{ $dept }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-3 mb-2">
                <label class="small font-weight-bold">Employee</label>
                <select name="employee_id" class="form-control">
                    <option value="">All Employees</option>
                    @foreach($employees as $emp)
                        <option value="{{ $emp->id }}" @if(request('employee_id') == $emp->id) selected @endif>
                            {{ $emp->employee_id }} - {{ $emp->name }}
                        </option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-3 mb-2">
                <label class="small font-weight-bold">&nbsp;</label>
                <button class="btn btn-primary btn-block">
                    <i class="fas fa-search mr-1"></i> Apply Filter
                </button>
            </div>
        </form>
    </div>
</div>

@php
    // Calculate summary statistics
    $totalEmployees = $employees->count();
    $presentCount = 0;
    $absentCount = 0;
    $onLeaveCount = 0;
    $totalOtMinutes = 0;
    $totalShortageMinutes = 0;
    $totalWorkMinutes = 0;
    $standardWorkHours = 9;

    foreach($employees as $emp) {
        $attendance = $attendanceData->where('employee_id', $emp->employee_id)->first();
        $leave = $leaveData->where('employee_id', $emp->id)->first();

        if($attendance) {
            $presentCount++;
            // Calculate working hours
            if($attendance->check_in && $attendance->check_out) {
                $checkIn = \Carbon\Carbon::parse($attendance->check_in);
                $checkOut = \Carbon\Carbon::parse($attendance->check_out);
                $breakOut = $attendance->break_out ? \Carbon\Carbon::parse($attendance->break_out) : null;
                $breakIn = $attendance->break_in ? \Carbon\Carbon::parse($attendance->break_in) : null;

                $totalMins = $checkIn->diffInMinutes($checkOut);
                $breakMins = ($breakOut && $breakIn) ? $breakOut->diffInMinutes($breakIn) : 0;
                $workMins = max(0, $totalMins - $breakMins);
                $totalWorkMinutes += $workMins;

                $workHours = $workMins / 60;
                if($workHours > $standardWorkHours) {
                    $totalOtMinutes += ($workHours - $standardWorkHours) * 60;
                } else {
                    $totalShortageMinutes += ($standardWorkHours - $workHours) * 60;
                }
            }
        } elseif($leave) {
            $onLeaveCount++;
        } else {
            $absentCount++;
        }
    }

    $avgWorkHours = $presentCount > 0 ? round($totalWorkMinutes / $presentCount / 60, 2) : 0;
    $productivityRate = $totalEmployees > 0 ? round(($presentCount / $totalEmployees) * 100, 1) : 0;
@endphp

<!-- Summary Statistics -->
<div class="row mb-4">
    <div class="col-xl-2 col-md-4 mb-3">
        <div class="stat-card bg-total">
            <div class="stat-value">{{ $totalEmployees }}</div>
            <div class="stat-label"><i class="fas fa-users mr-1"></i> Total Employees</div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 mb-3">
        <div class="stat-card bg-present">
            <div class="stat-value">{{ $presentCount }}</div>
            <div class="stat-label"><i class="fas fa-check-circle mr-1"></i> Present</div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 mb-3">
        <div class="stat-card bg-leave">
            <div class="stat-value">{{ $onLeaveCount }}</div>
            <div class="stat-label"><i class="fas fa-calendar-minus mr-1"></i> On Leave</div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 mb-3">
        <div class="stat-card bg-absent">
            <div class="stat-value">{{ $absentCount }}</div>
            <div class="stat-label"><i class="fas fa-times-circle mr-1"></i> Absent</div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 mb-3">
        <div class="stat-card bg-ot">
            <div class="stat-value">{{ sprintf('%02d:%02d', intdiv($totalOtMinutes, 60), $totalOtMinutes % 60) }}</div>
            <div class="stat-label"><i class="fas fa-clock mr-1"></i> Total OT</div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 mb-3">
        <div class="stat-card bg-shortage">
            <div class="stat-value">{{ $productivityRate }}%</div>
            <div class="stat-label"><i class="fas fa-chart-line mr-1"></i> Attendance Rate</div>
        </div>
    </div>
</div>

<!-- Daily Report 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-clipboard-list mr-2"></i> Daily Report for {{ \Carbon\Carbon::parse(request('date', date('Y-m-d')))->format('d M Y') }}
        </h6>
        <div>
            <span class="badge badge-light mr-2">Avg Work: {{ $avgWorkHours }} hrs</span>
        </div>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table id="dailyReportTable" class="table table-bordered table-striped table-sm" width="100%" cellspacing="0">
                <thead class="thead-light">
                    <tr class="text-center">
                        <th>Employee ID</th>
                        <th>Name</th>
                        <th>Department</th>
                        <th>Status</th>
                        <th>Check In</th>
                        <th>Break Out</th>
                        <th>Break In</th>
                        <th>Check Out</th>
                        <th>Work Hours</th>
                        <th>OT</th>
                        <th>Shortage</th>
                        <th>Leave Type</th>
                        <th>Leave Status</th>
                        <th>Productivity</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($employees as $emp)
                        @php
                            $attendance = $attendanceData->where('employee_id', $emp->employee_id)->first();
                            $leave = $leaveData->where('employee_id', $emp->id)->first();

                            $workDuration = null;
                            $workHours = 0;
                            $ot = 0;
                            $shortage = 0;
                            $productivityScore = 0;

                            if($attendance && $attendance->check_in && $attendance->check_out) {
                                $checkIn = \Carbon\Carbon::parse($attendance->check_in);
                                $checkOut = \Carbon\Carbon::parse($attendance->check_out);
                                $breakOut = $attendance->break_out ? \Carbon\Carbon::parse($attendance->break_out) : null;
                                $breakIn = $attendance->break_in ? \Carbon\Carbon::parse($attendance->break_in) : null;

                                $totalMins = $checkIn->diffInMinutes($checkOut);
                                $breakMins = ($breakOut && $breakIn) ? $breakOut->diffInMinutes($breakIn) : 0;
                                $workMins = max(0, $totalMins - $breakMins);
                                $workHours = round($workMins / 60, 2);
                                $workDuration = sprintf('%02d:%02d', intdiv($workMins, 60), $workMins % 60);

                                $ot = $workHours > $standardWorkHours ? round($workHours - $standardWorkHours, 2) : 0;
                                $shortage = $workHours < $standardWorkHours ? round($standardWorkHours - $workHours, 2) : 0;

                                // Productivity score: 100% for 9 hrs, +10% per OT hour, -10% per shortage hour
                                $productivityScore = min(150, max(0, 100 + ($ot * 10) - ($shortage * 10)));
                            }

                            $rowClass = '';
                            if($attendance) {
                                $rowClass = 'row-present';
                            } elseif($leave) {
                                $rowClass = 'row-leave';
                            } else {
                                $rowClass = 'row-absent';
                            }
                        @endphp
                        <tr class="text-center {{ $rowClass }}">
                            <td>{{ $emp->employee_id }}</td>
                            <td class="text-left">{{ $emp->name }}</td>
                            <td>{{ $emp->department ?? '-' }}</td>
                            <td>
                                @if($attendance)
                                    <span class="badge badge-success">Present</span>
                                @elseif($leave)
                                    <span class="badge badge-warning">On Leave</span>
                                @else
                                    <span class="badge badge-danger">Absent</span>
                                @endif
                            </td>
                            <td>{{ $attendance->check_in ?? '-' }}</td>
                            <td>{{ $attendance->break_out ?? '-' }}</td>
                            <td>{{ $attendance->break_in ?? '-' }}</td>
                            <td>{{ $attendance->check_out ?? '-' }}</td>
                            <td>
                                @if($workDuration)
                                    <strong>{{ $workDuration }}</strong>
                                @else
                                    -
                                @endif
                            </td>
                            <td>
                                @if($ot > 0)
                                    <span class="badge badge-success">+{{ sprintf('%02d:%02d', floor($ot), ($ot - floor($ot)) * 60) }}</span>
                                @else
                                    <span class="text-muted">-</span>
                                @endif
                            </td>
                            <td>
                                @if($shortage > 0)
                                    <span class="badge badge-danger">-{{ sprintf('%02d:%02d', floor($shortage), ($shortage - floor($shortage)) * 60) }}</span>
                                @else
                                    <span class="text-muted">-</span>
                                @endif
                            </td>
                            <td>
                                @if($leave)
                                    @switch($leave->leave_type)
                                        @case('CL')
                                            <span class="badge badge-info">CL</span>
                                            @break
                                        @case('SL')
                                            <span class="badge badge-warning">SL</span>
                                            @break
                                        @case('PL')
                                            <span class="badge badge-primary">PL</span>
                                            @break
                                        @case('LOP')
                                            <span class="badge badge-danger">LOP</span>
                                            @break
                                        @default
                                            <span class="badge badge-secondary">{{ $leave->leave_type }}</span>
                                    @endswitch
                                @else
                                    -
                                @endif
                            </td>
                            <td>
                                @if($leave)
                                    @if(strtolower($leave->status) == 'approved')
                                        <span class="badge badge-success">Approved</span>
                                    @elseif(strtolower($leave->status) == 'pending')
                                        <span class="badge badge-warning">Pending</span>
                                    @else
                                        <span class="badge badge-secondary">{{ $leave->status }}</span>
                                    @endif
                                @else
                                    -
                                @endif
                            </td>
                            <td>
                                @if($attendance)
                                    @if($productivityScore >= 100)
                                        <span class="badge badge-success">{{ $productivityScore }}%</span>
                                    @elseif($productivityScore >= 80)
                                        <span class="badge badge-warning">{{ $productivityScore }}%</span>
                                    @else
                                        <span class="badge badge-danger">{{ $productivityScore }}%</span>
                                    @endif
                                @elseif($leave)
                                    <span class="badge badge-info">On Leave</span>
                                @else
                                    <span class="badge badge-secondary">N/A</span>
                                @endif
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Productivity Summary Card -->
<div class="row">
    <div class="col-md-6">
        <div class="card shadow mb-4">
            <div class="card-header py-3" style="background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%);">
                <h6 class="m-0 font-weight-bold text-white">
                    <i class="fas fa-award mr-2"></i> Top Performers (OT Hours)
                </h6>
            </div>
            <div class="card-body p-0">
                <table class="table table-sm mb-0">
                    <thead class="thead-light">
                        <tr>
                            <th>Employee</th>
                            <th>Department</th>
                            <th class="text-center">OT Hours</th>
                        </tr>
                    </thead>
                    <tbody>
                        @php
                            $topPerformers = collect();
                            foreach($employees as $emp) {
                                $attendance = $attendanceData->where('employee_id', $emp->employee_id)->first();
                                if($attendance && $attendance->check_in && $attendance->check_out) {
                                    $checkIn = \Carbon\Carbon::parse($attendance->check_in);
                                    $checkOut = \Carbon\Carbon::parse($attendance->check_out);
                                    $breakOut = $attendance->break_out ? \Carbon\Carbon::parse($attendance->break_out) : null;
                                    $breakIn = $attendance->break_in ? \Carbon\Carbon::parse($attendance->break_in) : null;
                                    $totalMins = $checkIn->diffInMinutes($checkOut);
                                    $breakMins = ($breakOut && $breakIn) ? $breakOut->diffInMinutes($breakIn) : 0;
                                    $workMins = max(0, $totalMins - $breakMins);
                                    $workHours = $workMins / 60;
                                    if($workHours > $standardWorkHours) {
                                        $topPerformers->push([
                                            'name' => $emp->name,
                                            'department' => $emp->department,
                                            'ot' => round($workHours - $standardWorkHours, 2)
                                        ]);
                                    }
                                }
                            }
                            $topPerformers = $topPerformers->sortByDesc('ot')->take(5);
                        @endphp
                        @forelse($topPerformers as $performer)
                            <tr>
                                <td>{{ $performer['name'] }}</td>
                                <td>{{ $performer['department'] ?? '-' }}</td>
                                <td class="text-center">
                                    <span class="badge badge-success">+{{ sprintf('%02d:%02d', floor($performer['ot']), ($performer['ot'] - floor($performer['ot'])) * 60) }}</span>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="3" class="text-center text-muted">No OT recorded today</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card shadow mb-4">
            <div class="card-header py-3" style="background: linear-gradient(135deg, #dc3545 0%, #b21f2d 100%);">
                <h6 class="m-0 font-weight-bold text-white">
                    <i class="fas fa-exclamation-triangle mr-2"></i> Needs Attention (Shortage)
                </h6>
            </div>
            <div class="card-body p-0">
                <table class="table table-sm mb-0">
                    <thead class="thead-light">
                        <tr>
                            <th>Employee</th>
                            <th>Department</th>
                            <th class="text-center">Shortage</th>
                        </tr>
                    </thead>
                    <tbody>
                        @php
                            $needsAttention = collect();
                            foreach($employees as $emp) {
                                $attendance = $attendanceData->where('employee_id', $emp->employee_id)->first();
                                if($attendance && $attendance->check_in && $attendance->check_out) {
                                    $checkIn = \Carbon\Carbon::parse($attendance->check_in);
                                    $checkOut = \Carbon\Carbon::parse($attendance->check_out);
                                    $breakOut = $attendance->break_out ? \Carbon\Carbon::parse($attendance->break_out) : null;
                                    $breakIn = $attendance->break_in ? \Carbon\Carbon::parse($attendance->break_in) : null;
                                    $totalMins = $checkIn->diffInMinutes($checkOut);
                                    $breakMins = ($breakOut && $breakIn) ? $breakOut->diffInMinutes($breakIn) : 0;
                                    $workMins = max(0, $totalMins - $breakMins);
                                    $workHours = $workMins / 60;
                                    if($workHours < $standardWorkHours) {
                                        $needsAttention->push([
                                            'name' => $emp->name,
                                            'department' => $emp->department,
                                            'shortage' => round($standardWorkHours - $workHours, 2)
                                        ]);
                                    }
                                }
                            }
                            $needsAttention = $needsAttention->sortByDesc('shortage')->take(5);
                        @endphp
                        @forelse($needsAttention as $emp)
                            <tr>
                                <td>{{ $emp['name'] }}</td>
                                <td>{{ $emp['department'] ?? '-' }}</td>
                                <td class="text-center">
                                    <span class="badge badge-danger">-{{ sprintf('%02d:%02d', floor($emp['shortage']), ($emp['shortage'] - floor($emp['shortage'])) * 60) }}</span>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="3" class="text-center text-muted">All employees met target hours</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script>
$(document).ready(function() {
    $('#dailyReportTable').DataTable({
        dom: 'Bfrtip',
        buttons: [
            { extend: 'copy', className: 'btn btn-secondary btn-sm' },
            { extend: 'csv', className: 'btn btn-secondary btn-sm' },
            { extend: 'excel', className: 'btn btn-secondary btn-sm' },
            { extend: 'pdf', className: 'btn btn-secondary btn-sm' },
            { extend: 'print', className: 'btn btn-secondary btn-sm' },
            { extend: 'colvis', className: 'btn btn-secondary btn-sm' }
        ],
        pageLength: 25,
        responsive: true,
        order: [[3, 'asc'], [0, 'asc']], // Sort by status then employee ID
        language: {
            emptyTable: "No data available for selected date"
        }
    });
});
</script>
@endsection
