@extends('layouts.dashboard.superadminapp')

@section('title', 'Employee Leave Requests')

@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;
    }
</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 Leave Requests</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
@if($errors->any())
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle mr-2"></i>
        <ul class="mb-0 d-inline-block">
            @foreach($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif

<!-- Leave Requests 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-check mr-2"></i> Leave Requests List
        </h6>
        <button class="btn btn-light btn-sm" id="addLeaveBtn">
            <i class="fas fa-plus mr-1"></i> New Leave Request
        </button>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered table-striped table-sm" id="leaveTable" width="100%" cellspacing="0">
                <thead class="thead-light">
                    <tr>
                        <th>Employee ID</th>
                        <th>Employee Name</th>
                        <th>Department</th>
                        <th>Leave Type</th>
                        <th>Leave From</th>
                        <th>Leave To</th>
                        <th>No. of Days</th>
                        <th>Duration Type</th>
                        <th>Status</th>
                        <th>CL Bal (Year)</th>
                        <th>CL Bal (Month)</th>
                        <th>Reason</th>
                        <th>Requested On</th>
                        <th>Approved By</th>
                        <th>Approval Date</th>
                        <th width="100" class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($leaves as $leave)
                        @php
                            $empId = $leave->employee_id;
                            $leaveYear = \Carbon\Carbon::parse($leave->leave_from)->year ?? now()->year;
                            $leaveMonth = \Carbon\Carbon::parse($leave->leave_from)->month ?? now()->month;

                            $usedClYear = \App\Models\EmployeeLeave::where('employee_id', $empId)
                                ->where('leave_type', 'CL')
                                ->where('status', 'Approved')
                                ->whereYear('leave_from', $leaveYear)
                                ->sum('number_of_days');

                            $usedClMonth = \App\Models\EmployeeLeave::where('employee_id', $empId)
                                ->where('leave_type', 'CL')
                                ->where('status', 'Approved')
                                ->whereYear('leave_from', $leaveYear)
                                ->whereMonth('leave_from', $leaveMonth)
                                ->sum('number_of_days');

                            $clAvailableYear = max(0, 12 - $usedClYear);
                            $clAvailableMonth = max(0, 1 - $usedClMonth);
                        @endphp
                        <tr id="row-{{ $leave->id }}">
                            <td>{{ $leave->employee->employee_id ?? '-' }}</td>
                            <td>{{ $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>{{ $leave->number_of_days }}</td>
                            <td>{{ $leave->duration_type }}</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>{{ $clAvailableYear }}</td>
                            <td>{{ $clAvailableMonth }}</td>
                            <td>{{ Str::limit($leave->reason, 20) }}</td>
                            <td>{{ $leave->requested_on ? \Carbon\Carbon::parse($leave->requested_on)->format('d-m-Y') : '-' }}</td>
                            <td>{{ $leave->approved_by ?? '-' }}</td>
                            <td>{{ $leave->approval_date ? \Carbon\Carbon::parse($leave->approval_date)->format('d-m-Y') : '-' }}</td>
                            <td>
                                <div class="text-center" style="white-space: nowrap;">
                                    <button class="btn btn-warning btn-sm edit-btn" data-id="{{ $leave->id }}" title="Edit">
                                        <i class="fa fa-edit"></i>
                                    </button>
                                    <button class="btn btn-danger btn-sm delete-btn" data-id="{{ $leave->id }}" title="Delete">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add/Edit Leave Modal -->
<div class="modal fade" id="leaveModal" tabindex="-1" role="dialog" aria-labelledby="leaveModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <form id="leaveForm" method="POST" action="{{ route('superadmin.employeeleave.store') }}">
                @csrf
                <input type="hidden" name="_method" id="leaveFormMethod" value="POST">
                <input type="hidden" id="leaveIdHidden" name="leaveIdHidden">
                <div class="modal-header" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
                    <h5 class="modal-title text-white" id="leaveModalLabel">
                        <i class="fas fa-plus-circle mr-2"></i> New Leave Request
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div id="formError" class="alert alert-danger" style="display: none;"></div>

                    <!-- Row 1: Employee Info -->
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">Employee ID <span class="text-danger">*</span></label>
                            <select class="form-control" id="leave_employee_id" name="employee_id" required>
                                <option value="">Select Employee</option>
                                @foreach($employees as $employee)
                                    <option value="{{ $employee->id }}"
                                            data-name="{{ $employee->name }}"
                                            data-department="{{ $employee->department }}">
                                        {{ $employee->employee_id }} - {{ $employee->name }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">Employee Name</label>
                            <input type="text" class="form-control" id="leave_employee_name" name="employee_name" readonly>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">Department</label>
                            <input type="text" class="form-control" id="leave_department" name="department" readonly>
                        </div>
                    </div>

                    <!-- Row 2: CL Balance (shown only for CL leave type) -->
                    <div class="row" id="clBalanceRow" style="display: none;">
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">CL Balance (Year)</label>
                            <input type="text" class="form-control bg-light" id="cl_balance_year" readonly>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">CL Balance (Month)</label>
                            <input type="text" class="form-control bg-light" id="cl_balance_month" readonly>
                        </div>
                    </div>

                    <!-- Row 3: Leave Details -->
                    <!-- Row 3: Leave Details -->
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">Leave Type <span class="text-danger">*</span></label>
                            <select class="form-control" id="leave_type" name="leave_type" required>
                                <option value="">Select Leave Type</option>
                                <option value="CL">Casual Leave (CL)</option>
                                <option value="SL">Sick Leave (SL)</option>
                                <option value="PL">Paid Leave (PL)</option>
                                <option value="LOP">Loss of Pay (LOP)</option>
                                <option value="Other">Other</option>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">Leave From <span class="text-danger">*</span></label>
                            <input type="datetime-local" class="form-control" id="leave_from" name="leave_from" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">Leave To <span class="text-danger">*</span></label>
                            <input type="datetime-local" class="form-control" id="leave_to" name="leave_to" required>
                        </div>
                    </div>

                    <!-- Row 4: Duration & Status -->
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Duration Type <span class="text-danger">*</span></label>
                            <select class="form-control" id="duration_type" name="duration_type" required>
                                <option value="">Select Duration</option>
                                <option value="Full Day">Full Day</option>
                                <option value="Half Day">Half Day</option>
                                <option value="Hourly">Hourly</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Number of Days <span class="text-danger">*</span></label>
                            <input type="number" step="0.01" class="form-control" id="number_of_days" name="number_of_days" required readonly>
                        </div>
                        <!-- Status Removed from Add Form, will default to Pending in Controller -->
                        <input type="hidden" name="status" value="Pending"> 
                    </div>

                    <!-- Row 5: Reason -->
                    <div class="row">
                        <div class="col-md-12 mb-3">
                            <label class="small font-weight-bold">Reason <span class="text-danger">*</span></label>
                            <textarea class="form-control" id="reason" name="reason" rows="2" required></textarea>
                        </div>
                    </div>
                    
                    <!-- Hidden fields for Edit mode if needed, or remove completely if handled by separate approvals -->
                    <div id="approvalFields" style="display: none;">
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="small font-weight-bold">Status</label>
                                <select class="form-control" id="leave_status_edit" name="status_edit">
                                    <option value="Pending">Pending</option>
                                    <option value="Approved">Approved</option>
                                    <option value="Rejected">Rejected</option>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="small font-weight-bold">Approved By</label>
                                <input type="text" class="form-control" id="approved_by" name="approved_by" readonly>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="small font-weight-bold">Approval Date</label>
                                <input type="date" class="form-control" id="approval_date" name="approval_date" readonly>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">
                        <i class="fa fa-times mr-1"></i> Cancel
                    </button>
                    <button type="submit" class="btn btn-primary btn-sm" id="saveLeaveBtn">
                        <i class="fa fa-save mr-1"></i> Save Leave Request
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
const baseUrl = @json(url('/'));

$(document).ready(function() {
    // DataTable initialization
    $('#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: 10,
        scrollX: true,
        responsive: false,
        language: {
            emptyTable: "No leave requests found"
        }
    });

    // Add Leave Button
    $('#addLeaveBtn').on('click', function() {
        resetForm();
        $('#leaveForm').attr('action', '{{ route("superadmin.employeeleave.store") }}');
        $('#leaveFormMethod').val('POST');
        $('#leaveModalLabel').html('<i class="fas fa-plus-circle mr-2"></i> New Leave Request');
        $('#leaveModal').modal('show');
    });


    // Reset form function
    function resetForm() {
        $('#leaveForm')[0].reset();
        $('#leaveIdHidden').val('');
        $('#formError').hide();
        $('#leave_employee_name').val('');
        $('#leave_department').val('');
        $('#cl_balance_year').val('');
        $('#cl_balance_month').val('');
        $('#clBalanceRow').hide();
        $('#leaveFormMethod').val('POST');
        $('#approvalFields').hide(); // Hide approval fields by default
    }

    // Auto-calculate logic
    $('#leave_from, #leave_to, #duration_type').on('change', function() {
        calculateDuration();
    });

    function calculateDuration() {
        const from = $('#leave_from').val();
        const to = $('#leave_to').val();
        const type = $('#duration_type').val();

        if (from && to && type) {
            const start = new Date(from);
            const end = new Date(to);
            
            if (end < start) {
                // Swal.fire('Error', 'End date cannot be before start date', 'error');
                // return;
            }

            let diffDays = 0;

            if (type === 'Half Day') {
                diffDays = 0.5;
            } else if (type === 'Full Day') {
                // Calculate days inclusive
                const oneDay = 24 * 60 * 60 * 1000;
                // Reset times to midnight for accurate day calc
                const s = new Date(start.getFullYear(), start.getMonth(), start.getDate());
                const e = new Date(end.getFullYear(), end.getMonth(), end.getDate());
                diffDays = Math.round(Math.abs((e - s) / oneDay)) + 1;
            } else if (type === 'Hourly') {
                 const diffMs = Math.abs(end - start);
                 const diffHrs = diffMs / (1000 * 60 * 60);
                 // For hourly, we might store actual hours or fraction of day. 
                 // Assuming 8 hours = 1 day for storage, or just storing hours value if system supports it.
                 // Given the field is decimal, we can store hours directly if the convention allows, 
                 // OR store fraction. 
                 // The prompt says "Auto calculate for Duration(Number of Days)".
                 // Let's store actual HOURS for hourly type, assuming the backend or report handles "days" vs "hours" context based on type.
                 diffDays = diffHrs.toFixed(2); 
            }

            if (diffDays > 0) {
                $('#number_of_days').val(diffDays);
            }
        }
    }

    // Edit Leave
    $(document).on('click', '.edit-btn', function() {
        const id = $(this).data('id');
        resetForm();

        $.ajax({
            url: `${baseUrl}/superadmin/employeeleave/${id}`,
            type: 'GET',
            success: function(leave) {
                $('#leaveIdHidden').val(id);
                $('#leave_employee_id').val(leave.employee_id);
                $('#leave_employee_name').val(leave.employee_name);
                $('#leave_department').val(leave.department);
                $('#leave_type').val(leave.leave_type);
                
                // Format datetime for input
                $('#leave_from').val(leave.leave_from ? leave.leave_from.replace(' ', 'T').slice(0, 16) : '');
                $('#leave_to').val(leave.leave_to ? leave.leave_to.replace(' ', 'T').slice(0, 16) : '');
                
                $('#number_of_days').val(leave.number_of_days);
                $('#duration_type').val(leave.duration_type);
                $('#reason').val(leave.reason);
                
                // Show approval fields in Edit
                $('#approvalFields').show();
                $('#leave_status_edit').val(leave.status);
                $('#approved_by').val(leave.approved_by);
                $('#approval_date').val(leave.approval_date);

                if (leave.leave_type === 'CL') {
                    $('#clBalanceRow').show();
                    setTimeout(updateClBalance, 100);
                }

                $('#leaveForm').attr('action', `${baseUrl}/superadmin/employeeleave/${id}`);
                $('#leaveFormMethod').val('PUT');
                $('#leaveModalLabel').html('<i class="fas fa-edit mr-2"></i> Edit Leave Request');
                $('#leaveModal').modal('show');
            },
            error: function() {
                Swal.fire('Error!', 'Failed to fetch leave data.', 'error');
            }
        });
    });
});
</script>
@endsection
