@extends('layouts.dashboard.adminapp')

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

@section('styles')
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap5.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css">
    <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;
        }

        /* Popup overlay for form */
        .new-employer-popup-overlay {
            display: none;
            position: fixed;
            z-index: 1055;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: rgba(40, 40, 40, 0.35);
            justify-content: center;
            align-items: center;
        }

        .new-employer-popup-content {
            background: #fff;
            padding: 2rem;
            border-radius: 18px;
            min-width: 420px;
            max-width: 600px;
            margin: auto;
            box-shadow: 0 5px 30px rgba(0, 0, 0, .1);
        }

        .profile-img {
            object-fit: cover;
        }

        .new-employer-popup-buttons {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
        }

        .leave-popup-overlay {
            display: none;
            position: fixed;
            z-index: 1055;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: rgba(40, 40, 40, 0.35);
            justify-content: center;
            align-items: center;
        }

        .leave-popup-content {
            background: #fff;
            padding: 2rem;
            border-radius: 18px;
            min-width: 420px;
            max-width: 900px;
            max-height: 90vh;
            overflow-y: auto;
            margin: auto;
            box-shadow: 0 5px 30px rgba(0, 0, 0, .1);
        }

        @media (max-width: 600px) {
            .leave-popup-content {
                min-width: 90vw;
                max-width: 98vw;
                padding: 1rem;
            }

            .row>[class^='col-md-'] {
                flex: 0 0 100%;
                max-width: 100%;
            }
        }
    </style>
@endsection

@section('content')
    <div class="container-fluid bg-white">
        <div class="p-2 d-sm-flex align-items-center justify-content-between mb-4">
            <h1 class="h5 mb-0 text-gray-800">
                <i class="fas fa-calendar-check me-2"></i>
                UEPL / Employee Leave Requests
            </h1>
        </div>

        <div class="card">
            <div class="card-header">
                <a href="#" class="btn btn-primary btn-sm" id="openLeavePopup" style="float: right">
                    <i class="fas fa-plus"></i> New Leave Request
                </a>
            </div>
            <div class="card-header d-flex justify-content-between align-items-center">
                <span><i class="fas fa-table me-2"></i> Leave Requests</span>
            </div>
            <div class="card-body">
                @if (session('success'))
                    <div class="alert alert-success">{{ session('success') }}</div>
                @endif
                <div class="table-responsive">
                    <table class="table table-striped table-hover table-bordered" id="leaveTable" width="100%">
                        <thead>
                            <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>Reason</th>
                                <th>Requested On</th>
                                <th>Approved By</th>
                                <th>Approval Date</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach ($leaves as $leave)
                                <tr>
                                    <td>{{ $leave->employee->employee_id ?? '' }}</td>
                                    <td>{{ $leave->employee_name ?: ($leave->employee->name ?? '') }}</td>
                                    <td>{{ $leave->department }}</td>
                                    <td>{{ $leave->leave_type }}</td>
                                    <td>{{ $leave->leave_from }}</td>
                                    <td>{{ $leave->leave_to }}</td>
                                    <td>{{ $leave->number_of_days }}</td>
                                    <td>{{ $leave->duration_type }}</td>
                                    <td>
                                        @if (strtolower($leave->status) == 'approved')
                                            <span class="badge bg-success">Approved</span>
                                        @elseif(strtolower($leave->status) == 'pending')
                                            <span class="badge bg-warning text-dark">Pending</span>
                                        @elseif(strtolower($leave->status) == 'rejected')
                                            <span class="badge bg-danger">Rejected</span>
                                        @else
                                            <span class="badge bg-secondary">{{ $leave->status }}</span>
                                        @endif
                                    </td>
                                    <td>{{ $leave->reason }}</td>
                                    <td>{{ $leave->requested_on }}</td>
                                    <td>{{ $leave->approved_by }}</td>
                                    <td>{{ $leave->approval_date }}</td>
                                    <td>
                                        <a href="javascript:void(0);" class="btn btn-warning btn-sm me-1"
                                            onclick="editLeave({{ $leave->id }})">Edit</a>
                                        <form action="{{ route('admin.employeeleave.destroy', $leave->id) }}"
                                            method="POST" style="display:inline;">
                                            @csrf
                                            @method('DELETE')
                                            <button type="submit" class="btn btn-danger btn-sm"
                                                onclick="return confirm('Delete this leave request?')">Delete</button>
                                        </form>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Popup Overlay for Add/Edit Leave -->
    <div class="leave-popup-overlay" id="leave-popup-overlay">
        <form class="leave-popup-content" id="leaveForm" method="POST"
            action="{{ route('admin.employeeleave.store') }}">
            @csrf
            <input type="hidden" name="_method" id="leaveFormMethod" value="POST">
            <h5>Employee Leave Request</h5>
            <br>
            <div class="row">
                <div class="col-md-4">
                    <label for="leave_employee_id">Employee ID <span class="required">*</span></label>
                    <select id="leave_employee_id" name="employee_id" required>
                        <option value="">Select Employee ID</option>
                        @foreach ($employees as $employee)
                            <option value="{{ $employee->id }}">{{ $employee->employee_id }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-4">
                    <label for="leave_employee_name">Employee Name</label>
                    <input type="text" id="leave_employee_name" name="employee_name" readonly>
                </div>
                <div class="col-md-4">
                    <label for="leave_department">Department</label>
                    <input type="text" id="leave_department" name="department" readonly>
                </div>
            </div>
            <br>
            <div class="row">
                <div class="col-md-4">
                    <label for="leave_type">Leave Type <span class="required">*</span></label>
                    <select id="leave_type" name="leave_type" required>
                        <option value="">Select</option>
                        <option value="CL">Casual Leave</option>
                        <option value="SL">Sick Leave</option>
                        <option value="PL">Paid Leave</option>
                        <option value="LOP">Loss of Pay</option>
                        <option value="Other">Other</option>
                    </select>
                </div>
                <div class="col-md-4">
                    <label for="leave_from">Leave From <span class="required">*</span></label>
                    <input type="date" id="leave_from" name="leave_from" required>
                </div>
                <div class="col-md-4">
                    <label for="leave_to">Leave To <span class="required">*</span></label>
                    <input type="date" id="leave_to" name="leave_to" required>
                </div>
            </div>
            <br>
            <div class="row">
                <div class="col-md-4">
                    <label for="number_of_days">Number of Days <span class="required">*</span></label>
                    <input type="number" step="0.5" id="number_of_days" name="number_of_days" required>
                </div>
                <div class="col-md-4">
                    <label for="duration_type">Duration Type <span class="required">*</span></label>
                    <select id="duration_type" name="duration_type" required>
                        <option value="">Select</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-4">
                    <label for="status">Status <span class="required">*</span></label>
                    <select id="status" name="status" required>
                        <option value="Pending">Pending</option>
                        <option value="Approved">Approved</option>
                        <option value="Rejected">Rejected</option>
                    </select>
                </div>
            </div>
            <br>
            <div class="row">
                <div class="col-md-4">
                    <label for="reason">Reason <span class="required">*</span></label>
                    <input type="text" id="reason" name="reason" required>
                </div>
                <div class="col-md-4">
                    <label for="approved_by">Approved By</label>
                    <input type="text" id="approved_by" name="approved_by">
                </div>
                <div class="col-md-4">
                    <label for="approval_date">Approval Date</label>
                    <input type="date" id="approval_date" name="approval_date">
                </div>
            </div>
            <br>
            <div class="d-flex justify-content-end gap-2">
                <button class="btn btn-success" type="submit">Save</button>
                <button class="btn btn-danger" type="button" id="closeLeavePopup">Close</button>
            </div>
        </form>
    </div>
@endsection

@section('scripts')
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
    <script>
        $(document).ready(function() {
            // DataTable initialization
            $('#leaveTable').DataTable({
                dom: 'Bfrtip',
                responsive: true,
                scrollX: true,
                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'
                    }
                ],
                pageLength: 10,
                language: {
                    "emptyTable": "No leave requests found"
                }
            });

            // Popup logic
            $('#openLeavePopup').on('click', function(event) {
                event.preventDefault();
                $('#leave-popup-overlay').css('display', 'flex');
                $('#leaveForm').trigger('reset');
                $('#leaveForm').attr('action', '{{ route('admin.employeeleave.store') }}');
                $('#leaveFormMethod').val('POST');
                $('#leaveForm input[name="_method"]').val('POST');
            });

            $('#closeLeavePopup').on('click', function() {
                $('#leave-popup-overlay').hide();
            });

            // Autofill employee name & department
            $('#leave_employee_id').on('change', function() {
                var empId = $(this).val();
                if (empId) {
                    $.ajax({
                        url: '{{ url('/admin/employee') }}/' + empId + '/name-dept',
                        method: 'GET',
                        success: function(res) {
                            $('#leave_employee_name').val(res.name);
                            $('#leave_department').val(res.department);
                        }
                    });
                } else {
                    $('#leave_employee_name').val('');
                    $('#leave_department').val('');
                }
            });
        });

        // Edit Leave (AJAX)
        function editLeave(leaveId) {
            const baseUrl = @json(url('/'));
            const popupOverlay = document.getElementById('leave-popup-overlay');
            popupOverlay.style.display = 'flex';
            $('#leaveForm').trigger('reset');
            $('#leaveForm').attr('action', `${baseUrl}/admin/employeeleave/${leaveId}`);
            $('#leaveFormMethod').val('PUT');
            $('#leaveForm input[name="_method"]').val('PUT');

            $.ajax({
                url: `${baseUrl}/admin/employeeleave/${leaveId}`,
                type: 'GET',
                success: function(leave) {
                    $('#leave_employee_id').val(leave.employee_id).trigger('change');
                    $('#leave_employee_name').val(leave.employee_name);
                    $('#leave_department').val(leave.department);
                    $('#leave_type').val(leave.leave_type);
                    $('#leave_from').val(leave.leave_from);
                    $('#leave_to').val(leave.leave_to);
                    $('#number_of_days').val(leave.number_of_days);
                    $('#duration_type').val(leave.duration_type);
                    $('#status').val(leave.status);
                    $('#reason').val(leave.reason);
                    $('#approved_by').val(leave.approved_by);
                    $('#approval_date').val(leave.approval_date);
                },
                error: function() {
                    alert('Failed to fetch leave data.');
                }
            });
        }
    </script>
@endsection
