@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 -->
<x-layout.page-header title="UEPL | Employee Leave Requests" 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
@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

<!-- Filters Card -->
<div class="card shadow mb-4">
    <div class="card-header py-2" style="background: linear-gradient(135deg, #36b9cc 0%, #1e90a6 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-filter mr-2"></i> Filters
        </h6>
    </div>
    <div class="card-body py-3">
        <form method="GET" action="{{ route('superadmin.employee.employeeleave') }}" id="filterForm">
            <div class="row">
                <div class="col-md-2 mb-2">
                    <label class="small font-weight-bold">Department</label>
                    <select class="form-control form-control-sm" name="department" id="filter_department">
                        <option value="">All Departments</option>
                        @foreach($departments ?? [] as $dept)
                            <option value="{{ $dept }}" {{ request('department') == $dept ? 'selected' : '' }}>{{ $dept }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2 mb-2">
                    <label class="small font-weight-bold">Employee</label>
                    <select class="form-control form-control-sm" name="employee_id" id="filter_employee">
                        <option value="">All Employees</option>
                        @foreach($employees as $emp)
                            <option value="{{ $emp->id }}" data-dept="{{ $emp->department }}" {{ request('employee_id') == $emp->id ? 'selected' : '' }}>
                                {{ $emp->employee_id }} - {{ $emp->name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2 mb-2">
                    <label class="small font-weight-bold">Leave Type</label>
                    <select class="form-control form-control-sm" name="leave_type">
                        <option value="">All Types</option>
                        <option value="CL" {{ request('leave_type') == 'CL' ? 'selected' : '' }}>Casual Leave (CL)</option>
                        <option value="SL" {{ request('leave_type') == 'SL' ? 'selected' : '' }}>Sick Leave (SL)</option>
                        <option value="PL" {{ request('leave_type') == 'PL' ? 'selected' : '' }}>Paid Leave (PL)</option>
                        <option value="LOP" {{ request('leave_type') == 'LOP' ? 'selected' : '' }}>Loss of Pay (LOP)</option>
                    </select>
                </div>
                <div class="col-md-2 mb-2">
                    <label class="small font-weight-bold">Status</label>
                    <select class="form-control form-control-sm" name="status">
                        <option value="">All Status</option>
                        <option value="Pending" {{ request('status') == 'Pending' ? 'selected' : '' }}>Pending</option>
                        <option value="Approved" {{ request('status') == 'Approved' ? 'selected' : '' }}>Approved</option>
                        <option value="Rejected" {{ request('status') == 'Rejected' ? 'selected' : '' }}>Rejected</option>
                    </select>
                </div>
                <div class="col-md-2 mb-2">
                    <label class="small font-weight-bold">From Date</label>
                    <input type="date" class="form-control form-control-sm" name="from_date" value="{{ request('from_date') }}">
                </div>
                <div class="col-md-2 mb-2">
                    <label class="small font-weight-bold">To Date</label>
                    <input type="date" class="form-control form-control-sm" name="to_date" value="{{ request('to_date') }}">
                </div>
            </div>
            <div class="row mt-2">
                <div class="col-md-12 text-right">
                    <button type="submit" class="btn btn-primary btn-sm">
                        <i class="fas fa-search mr-1"></i> Filter
                    </button>
                    <a href="{{ route('superadmin.employee.employeeleave') }}" class="btn btn-secondary btn-sm">
                        <i class="fas fa-undo mr-1"></i> Reset
                    </a>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- 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;">
                                    @if($leave->status == 'Pending')
                                        <button class="btn btn-success btn-sm approve-btn" data-id="{{ $leave->id }}" title="Approve">
                                            <i class="fa fa-check"></i>
                                        </button>
                                        <button class="btn btn-danger btn-sm reject-btn" data-id="{{ $leave->id }}" title="Reject">
                                            <i class="fa fa-times"></i>
                                        </button>
                                    @endif
                                    <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 Type & Duration -->
                    <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">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-4 mb-3">
                            <label class="small font-weight-bold" id="durationLabel">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>
                    </div>

                    <!-- Row 4a: Full Day Inputs (From Date - To Date) -->
                    <div class="row group-fullday" style="display:none;">
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Leave From <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" id="leave_from_date" name="leave_from_fullday" disabled>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Leave To <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" id="leave_to_date" name="leave_to_fullday" disabled>
                        </div>
                    </div>

                    <!-- Row 4b: Half Day Inputs (On Date + First/Second Half) -->
                    <div class="row group-halfday" style="display:none;">
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">On Date <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" id="leave_on_date_half" name="leave_on_date_half" disabled>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Half Type <span class="text-danger">*</span></label>
                            <select class="form-control" id="half_type" name="half_type" disabled>
                                <option value="">Select Half</option>
                                <option value="First Half">First Half (Morning)</option>
                                <option value="Second Half">Second Half (Afternoon)</option>
                            </select>
                        </div>
                    </div>

                    <!-- Row 4c: Hourly Inputs (On Date + From Hour - To Hour) -->
                    <div class="row group-hourly" style="display:none;">
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">On Date <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" id="leave_on_date_hourly" name="leave_on_date_hourly" disabled>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">From Hour <span class="text-danger">*</span></label>
                            <input type="time" class="form-control" id="from_hour" name="from_hour" disabled>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">To Hour <span class="text-danger">*</span></label>
                            <input type="time" class="form-control" id="to_hour" name="to_hour" disabled>
                        </div>
                    </div>

                    <!-- Hidden inputs for actual form submission -->
                    <input type="hidden" id="leave_from_hidden" name="leave_from">
                    <input type="hidden" id="leave_to_hidden" name="leave_to">
                        <!-- Status Removed from Add Form, will default to Pending in Controller -->
                        <input type="hidden" name="status" value="Pending">


                    <!-- 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('/'));
const clBalances = @json($clBalances ?? []);

$(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-fill Employee Name and Department
    $('#leave_employee_id').on('change', function() {
        const option = $(this).find('option:selected');
        const name = option.data('name');
        const dept = option.data('department');
        
        $('#leave_employee_name').val(name || '');
        $('#leave_department').val(dept || '');

        updateClBalance();
    });

    function updateClBalance() {
        const empId = $('#leave_employee_id').val();
        const type = $('#leave_type').val();
        
        if (type === 'CL' && empId && clBalances[empId]) {
            const bal = clBalances[empId];
            $('#cl_balance_year').val(bal.cl_available_year);
            $('#cl_balance_month').val(bal.cl_available_month);
            $('#clBalanceRow').show();
        } else {
            $('#clBalanceRow').hide();
        }
    }

    $('#leave_type').on('change', function() {
        updateClBalance();
    });

    // Toggle Fields & Calculate based on Duration Type
    $('#duration_type').on('change', function() {
        toggleDateFields();
        calculateDuration();
    });

    // Listen for changes in all date/time fields
    $('#leave_from_date, #leave_to_date, #leave_on_date_half, #half_type, #leave_on_date_hourly, #from_hour, #to_hour').on('change', function() {
        calculateDuration();
        updateHiddenFields();
    });

    function toggleDateFields() {
        const type = $('#duration_type').val();

        // Reset all groups
        $('.group-fullday, .group-halfday, .group-hourly').hide();
        $('.group-fullday input, .group-halfday input, .group-halfday select, .group-hourly input').prop('disabled', true);
        $('#number_of_days').val('');

        if (type === 'Full Day') {
            $('.group-fullday').show().find('input').prop('disabled', false);
            $('#durationLabel').text('Number of Days');
        } else if (type === 'Half Day') {
            $('.group-halfday').show().find('input, select').prop('disabled', false);
            $('#durationLabel').text('Number of Days');
            $('#number_of_days').val('0.5');
        } else if (type === 'Hourly') {
            $('.group-hourly').show().find('input').prop('disabled', false);
            $('#durationLabel').text('Duration (Hours)');
        }
    }

    function calculateDuration() {
        const type = $('#duration_type').val();
        let diff = 0;

        if (type === 'Hourly') {
            const fromHour = $('#from_hour').val();
            const toHour = $('#to_hour').val();

            if (fromHour && toHour) {
                const [fh, fm] = fromHour.split(':').map(Number);
                const [th, tm] = toHour.split(':').map(Number);
                const fromMinutes = fh * 60 + fm;
                const toMinutes = th * 60 + tm;

                if (toMinutes > fromMinutes) {
                    diff = ((toMinutes - fromMinutes) / 60).toFixed(2);
                }
            }
        } else if (type === 'Half Day') {
            diff = 0.5;
        } else if (type === 'Full Day') {
            const startDateStr = $('#leave_from_date').val();
            const endDateStr = $('#leave_to_date').val();

            if (startDateStr && endDateStr) {
                const s = new Date(startDateStr);
                const e = new Date(endDateStr);

                if (e >= s) {
                    const oneDay = 24 * 60 * 60 * 1000;
                    diff = Math.round(Math.abs((e - s) / oneDay)) + 1;
                }
            }
        }

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

        updateHiddenFields();
    }

    function updateHiddenFields() {
        const type = $('#duration_type').val();

        if (type === 'Full Day') {
            $('#leave_from_hidden').val($('#leave_from_date').val());
            $('#leave_to_hidden').val($('#leave_to_date').val());
        } else if (type === 'Half Day') {
            const onDate = $('#leave_on_date_half').val();
            $('#leave_from_hidden').val(onDate);
            $('#leave_to_hidden').val(onDate);
        } else if (type === 'Hourly') {
            const onDate = $('#leave_on_date_hourly').val();
            $('#leave_from_hidden').val(onDate);
            $('#leave_to_hidden').val(onDate);
        }
    }

    // Filter: Department filters employees
    $('#filter_department').on('change', function() {
        const dept = $(this).val();
        $('#filter_employee option').each(function() {
            const empDept = $(this).data('dept');
            if (!dept || empDept === dept || $(this).val() === '') {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
        $('#filter_employee').val('');
    });

    // 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);
                $('#duration_type').val(leave.duration_type).trigger('change');

                const leaveFromDate = leave.leave_from ? leave.leave_from.slice(0, 10) : '';
                const leaveToDate = leave.leave_to ? leave.leave_to.slice(0, 10) : '';

                // Populate correct fields based on duration type
                if (leave.duration_type === 'Hourly') {
                    $('#leave_on_date_hourly').val(leaveFromDate);
                    $('#from_hour').val(leave.from_hour || '');
                    $('#to_hour').val(leave.to_hour || '');
                } else if (leave.duration_type === 'Half Day') {
                    $('#leave_on_date_half').val(leaveFromDate);
                    $('#half_type').val(leave.half_type || 'First Half');
                } else {
                    // Full Day
                    $('#leave_from_date').val(leaveFromDate);
                    $('#leave_to_date').val(leaveToDate);
                }

                // Set hidden fields
                $('#leave_from_hidden').val(leaveFromDate);
                $('#leave_to_hidden').val(leaveToDate);

                $('#number_of_days').val(leave.number_of_days);
                $('#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');
            }
        });
    });

    // Approve Leave
    $(document).on('click', '.approve-btn', function() {
        const id = $(this).data('id');
        updateLeaveStatus(id, 'Approved');
    });

    // Reject Leave
    $(document).on('click', '.reject-btn', function() {
        const id = $(this).data('id');
        updateLeaveStatus(id, 'Rejected');
    });

    function updateLeaveStatus(id, status) {
        Swal.fire({
            title: `Confirm ${status}?`,
            text: `Are you sure you want to mark this leave as ${status}?`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: status === 'Approved' ? '#1cc88a' : '#e74a3b',
            cancelButtonColor: '#858796',
            confirmButtonText: `Yes, ${status} it!`
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: `${baseUrl}/superadmin/employeeleave/${id}/status`,
                    type: 'POST',
                    data: {
                        _token: '{{ csrf_token() }}',
                        status: status
                    },
                    success: function(response) {
                        if (response.success) {
                            Swal.fire('Updated!', response.message, 'success')
                            .then(() => location.reload());
                        } else {
                            Swal.fire('Error!', 'Something went wrong.', 'error');
                        }
                    },
                    error: function() {
                        Swal.fire('Error!', 'Failed to update status.', 'error');
                    }
                });
            }
        });
    }

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

        Swal.fire({
            title: 'Delete Leave Request?',
            text: 'This action cannot be undone!',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#e74a3b',
            cancelButtonColor: '#858796',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: `${baseUrl}/superadmin/employeeleave/${id}`,
                    type: 'DELETE',
                    data: {
                        _token: '{{ csrf_token() }}'
                    },
                    success: function(response) {
                        if (response.success) {
                            Swal.fire('Deleted!', response.message, 'success')
                            .then(() => {
                                $(`#row-${id}`).fadeOut(300, function() {
                                    $(this).remove();
                                });
                            });
                        } else {
                            Swal.fire('Error!', 'Something went wrong.', 'error');
                        }
                    },
                    error: function(xhr) {
                        Swal.fire('Error!', 'Failed to delete leave request.', 'error');
                    }
                });
            }
        });
    });

});
</script>
@endsection
