@extends('layouts.dashboard.superadminapp')

@section('title', 'Employee 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;
    }
    .nav-tabs .nav-link {
        font-weight: 600;
        color: #5a5c69;
        border: none;
        padding: 12px 24px;
        border-radius: 8px 8px 0 0;
        margin-right: 4px;
        background: #f8f9fc;
        transition: all 0.2s;
    }
    .nav-tabs .nav-link:hover {
        background: #eaecf4;
        color: #4e73df;
    }
    .nav-tabs .nav-link.active {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
        color: #fff;
        border: none;
    }
    .stat-card {
        border-radius: 10px;
        padding: 20px;
        text-align: center;
        color: #fff;
        transition: transform 0.2s;
    }
    .stat-card:hover {
        transform: translateY(-3px);
    }
    .stat-card .stat-value {
        font-size: 1.8rem;
        font-weight: bold;
    }
    .stat-card .stat-label {
        font-size: 0.85rem;
        opacity: 0.9;
    }
    .bg-total { background: linear-gradient(135deg, #4e73df 0%, #224abe 100%); }
    .bg-present { background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%); }
    .bg-leave { background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%); }
    .bg-absent { background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%); }
    .bg-ot { background: linear-gradient(135deg, #36b9cc 0%, #258391 100%); }
</style>
@endsection

@section('content')

<!-- Page Heading -->
<x-layout.page-header title="UEPL | Employee Report" icon="chart-bar" iconColor="info" />

<!-- 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 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 id="empReportFilters" method="POST" action="{{ route('superadmin.report.employeereport') }}">
            @csrf
            <input type="hidden" name="tab" id="tabInput" value="{{ $tab }}">
            <div class="row align-items-end">
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Employee</label>
                    <select name="employee_id" id="employee_id" class="form-control">
                        <option value="">All Employees</option>
                        @foreach ($employees as $emp)
                            <option value="{{ $emp->employee_id }}" {{ $employeeId == $emp->employee_id ? 'selected' : '' }}>
                                {{ $emp->employee_id }} - {{ $emp->name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2 mb-3">
                    <label class="small font-weight-bold">From Date</label>
                    <input type="date" name="from_date" id="from_date" class="form-control" value="{{ $fromDate }}">
                </div>
                <div class="col-md-2 mb-3">
                    <label class="small font-weight-bold">To Date</label>
                    <input type="date" name="to_date" id="to_date" class="form-control" value="{{ $toDate }}">
                </div>
                <div class="col-md-3 mb-3">
                    <button type="submit" class="btn btn-primary btn-sm mr-2">
                        <i class="fas fa-search mr-1"></i> Apply Filter
                    </button>
                    <a href="{{ route('superadmin.report.employeereport') }}" class="btn btn-secondary btn-sm">
                        <i class="fas fa-redo mr-1"></i> Reset
                    </a>
                </div>
                <div class="col-md-2 mb-3">
                    <button type="button" class="btn btn-success btn-sm" id="exportExcelBtn">
                        <i class="fas fa-file-excel mr-1"></i> Export Excel
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Report Tabs -->
<div class="card shadow mb-4">
    <div class="card-header py-3" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-chart-bar mr-2"></i> Employee Reports
        </h6>
    </div>
    <div class="card-body">
        <!-- Tab Navigation -->
        <ul class="nav nav-tabs mb-4" id="reportTabs">
            <li class="nav-item">
                <a class="nav-link {{ $tab == 'attendance' ? 'active' : '' }}" href="#" data-tab="attendance">
                    <i class="fas fa-clipboard-check mr-1"></i> Attendance Report
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link {{ $tab == 'leave' ? 'active' : '' }}" href="#" data-tab="leave">
                    <i class="fas fa-calendar-minus mr-1"></i> Leave Report
                </a>
            </li>
        </ul>

        <!-- Attendance Tab Content -->
        @if($tab == 'attendance')
            @php
                $totalRecords = $attendanceReports->count();
                $totalOT = $attendanceReports->sum('over_time');
                $totalWorkHours = $attendanceReports->sum('work_hours');
                $avgWorkHours = $totalRecords > 0 ? round($totalWorkHours / $totalRecords, 2) : 0;
            @endphp

            <!-- Summary Stats -->
            <div class="row mb-4">
                <div class="col-xl-3 col-md-6 mb-3">
                    <div class="stat-card bg-total">
                        <div class="stat-value">{{ $totalRecords }}</div>
                        <div class="stat-label"><i class="fas fa-database mr-1"></i> Total Records</div>
                    </div>
                </div>
                <div class="col-xl-3 col-md-6 mb-3">
                    <div class="stat-card bg-present">
                        <div class="stat-value">{{ number_format($totalWorkHours, 1) }}</div>
                        <div class="stat-label"><i class="fas fa-clock mr-1"></i> Total Work Hours</div>
                    </div>
                </div>
                <div class="col-xl-3 col-md-6 mb-3">
                    <div class="stat-card bg-ot">
                        <div class="stat-value">{{ number_format($totalOT, 1) }}</div>
                        <div class="stat-label"><i class="fas fa-hourglass-half mr-1"></i> Total OT Hours</div>
                    </div>
                </div>
                <div class="col-xl-3 col-md-6 mb-3">
                    <div class="stat-card bg-leave">
                        <div class="stat-value">{{ $avgWorkHours }}</div>
                        <div class="stat-label"><i class="fas fa-chart-line mr-1"></i> Avg Work Hours</div>
                    </div>
                </div>
            </div>

            <!-- Attendance Table -->
            <div class="table-responsive">
                <table id="attendanceTable" class="table table-bordered table-striped table-sm" width="100%">
                    <thead class="thead-light">
                        <tr class="text-center">
                            <th>Date</th>
                            <th>Employee ID</th>
                            <th>Employee Name</th>
                            <th>Shift</th>
                            <th>In Time 1</th>
                            <th>Out Time 1</th>
                            <th>In Time 2</th>
                            <th>Out Time 2</th>
                            <th>First Half</th>
                            <th>Second Half</th>
                            <th>Late In</th>
                            <th>Early Out</th>
                            <th>Work Hours</th>
                            <th>OT</th>
                            <th>Reason</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($attendanceReports as $report)
                            <tr class="text-center">
                                <td>{{ \Carbon\Carbon::parse($report->date)->format('d-m-Y') }}</td>
                                <td>{{ $report->employee_id }}</td>
                                <td class="text-left">{{ $report->employeeDetails->name ?? '-' }}</td>
                                <td>{{ $report->shift ?? '-' }}</td>
                                <td>{{ $report->in_spfid_1 ?? '-' }}</td>
                                <td>{{ $report->out_spfid_1 ?? '-' }}</td>
                                <td>{{ $report->in_spfid_2 ?? '-' }}</td>
                                <td>{{ $report->out_spfid_2 ?? '-' }}</td>
                                <td>
                                    @if($report->first_half)
                                        <span class="badge badge-{{ $report->first_half == 'P' ? 'success' : ($report->first_half == 'A' ? 'danger' : 'warning') }}">
                                            {{ $report->first_half }}
                                        </span>
                                    @else
                                        -
                                    @endif
                                </td>
                                <td>
                                    @if($report->second_half)
                                        <span class="badge badge-{{ $report->second_half == 'P' ? 'success' : ($report->second_half == 'A' ? 'danger' : 'warning') }}">
                                            {{ $report->second_half }}
                                        </span>
                                    @else
                                        -
                                    @endif
                                </td>
                                <td>
                                    @if($report->late_in && $report->late_in != '00:00:00')
                                        <span class="badge badge-danger">{{ $report->late_in }}</span>
                                    @else
                                        <span class="text-muted">-</span>
                                    @endif
                                </td>
                                <td>
                                    @if($report->early_out && $report->early_out != '00:00:00')
                                        <span class="badge badge-warning">{{ $report->early_out }}</span>
                                    @else
                                        <span class="text-muted">-</span>
                                    @endif
                                </td>
                                <td><strong>{{ $report->work_hours ?? '-' }}</strong></td>
                                <td>
                                    @if($report->over_time && $report->over_time > 0)
                                        <span class="badge badge-info">{{ $report->over_time }}</span>
                                    @else
                                        <span class="text-muted">-</span>
                                    @endif
                                </td>
                                <td>{{ $report->reason ?? '-' }}</td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        @endif

        <!-- Leave Tab Content -->
        @if($tab == 'leave')
            @php
                $totalLeaves = $leaveReports->count();
                $approvedLeaves = $leaveReports->where('status', 'Approved')->count();
                $pendingLeaves = $leaveReports->where('status', 'Pending')->count();
                $rejectedLeaves = $leaveReports->where('status', 'Rejected')->count();
                $totalDays = $leaveReports->sum('number_of_days');
            @endphp

            <!-- Summary Stats -->
            <div class="row mb-4">
                <div class="col-xl-3 col-md-6 mb-3">
                    <div class="stat-card bg-total">
                        <div class="stat-value">{{ $totalLeaves }}</div>
                        <div class="stat-label"><i class="fas fa-database mr-1"></i> Total Requests</div>
                    </div>
                </div>
                <div class="col-xl-3 col-md-6 mb-3">
                    <div class="stat-card bg-present">
                        <div class="stat-value">{{ $approvedLeaves }}</div>
                        <div class="stat-label"><i class="fas fa-check-circle mr-1"></i> Approved</div>
                    </div>
                </div>
                <div class="col-xl-3 col-md-6 mb-3">
                    <div class="stat-card bg-leave">
                        <div class="stat-value">{{ $pendingLeaves }}</div>
                        <div class="stat-label"><i class="fas fa-hourglass-half mr-1"></i> Pending</div>
                    </div>
                </div>
                <div class="col-xl-3 col-md-6 mb-3">
                    <div class="stat-card bg-absent">
                        <div class="stat-value">{{ $rejectedLeaves }}</div>
                        <div class="stat-label"><i class="fas fa-times-circle mr-1"></i> Rejected</div>
                    </div>
                </div>
            </div>

            <!-- Leave Table -->
            <div class="table-responsive">
                <table id="leaveTable" class="table table-bordered table-striped table-sm" width="100%">
                    <thead class="thead-light">
                        <tr class="text-center">
                            <th>Employee ID</th>
                            <th>Employee Name</th>
                            <th>Department</th>
                            <th>Leave Type</th>
                            <th>From Date</th>
                            <th>To Date</th>
                            <th>Days</th>
                            <th>Duration</th>
                            <th>Reason</th>
                            <th>Status</th>
                            <th>Requested On</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($leaveReports as $leave)
                            <tr class="text-center">
                                <td>{{ $leave->employee->employee_id ?? '-' }}</td>
                                <td class="text-left">{{ $leave->employee_name ?? ($leave->employee->name ?? '-') }}</td>
                                <td>{{ $leave->department ?? '-' }}</td>
                                <td>
                                    @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
                                </td>
                                <td>{{ $leave->leave_from ? \Carbon\Carbon::parse($leave->leave_from)->format('d-m-Y') : '-' }}</td>
                                <td>{{ $leave->leave_to ? \Carbon\Carbon::parse($leave->leave_to)->format('d-m-Y') : '-' }}</td>
                                <td><strong>{{ $leave->number_of_days ?? '-' }}</strong></td>
                                <td>{{ $leave->duration_type ?? 'Full Day' }}</td>
                                <td class="text-left" style="max-width: 200px;">{{ Str::limit($leave->reason, 50) ?? '-' }}</td>
                                <td>
                                    @if(strtolower($leave->status ?? '') == 'approved')
                                        <span class="badge badge-success">Approved</span>
                                    @elseif(strtolower($leave->status ?? '') == 'pending')
                                        <span class="badge badge-warning">Pending</span>
                                    @elseif(strtolower($leave->status ?? '') == 'rejected')
                                        <span class="badge badge-danger">Rejected</span>
                                    @else
                                        <span class="badge badge-secondary">{{ $leave->status ?? '-' }}</span>
                                    @endif
                                </td>
                                <td>{{ $leave->requested_on ? \Carbon\Carbon::parse($leave->requested_on)->format('d-m-Y') : '-' }}</td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        @endif
    </div>
</div>

@endsection

@section('scripts')
<script>
$(document).ready(function() {
    // Initialize DataTables
    @if($tab == 'attendance')
    $('#attendanceTable').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: [[0, 'desc']],
        language: {
            emptyTable: "No attendance records found"
        }
    });
    @endif

    @if($tab == 'leave')
    $('#leaveTable').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: [[4, 'desc']],
        language: {
            emptyTable: "No leave records found"
        }
    });
    @endif

    // Tab switching logic
    $('.nav-link[data-tab]').on('click', function(e) {
        e.preventDefault();
        $('#tabInput').val($(this).data('tab'));
        $('#empReportFilters').submit();
    });

    // Export Excel logic
    $('#exportExcelBtn').click(function() {
        let form = $('#empReportFilters');
        let originalAction = form.attr('action');
        form.attr('action', '{{ route('superadmin.exportEmployeeReport') }}');
        form.attr('target', '_blank');
        form.submit();
        setTimeout(function() {
            form.attr('action', originalAction);
            form.removeAttr('target');
        }, 100);
    });
});
</script>
@endsection
