@extends('layouts.dashboard.managerapp')

@section('title', 'Leave Management')

@section('styles')
<style>
    div.dt-buttons {
        float: left;
        display: flex !important;
    }
    .dt-buttons .btn {
        margin-right: 0.5rem !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 | Leave Management</h1>
    <div>
        @if($pendingCount > 0)
            <span class="badge badge-warning badge-lg">{{ $pendingCount }} Pending Approvals</span>
        @endif
    </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"><span>&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"><span>&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('manager.leave.index') }}">
            <div class="row">
                <div class="col-md-3 mb-2">
                    <label class="small font-weight-bold">Employee</label>
                    <select class="form-control form-control-sm" name="employee_id">
                        <option value="">All Employees</option>
                        @foreach($employees as $emp)
                            <option value="{{ $emp->id }}" {{ $employeeId == $emp->id ? 'selected' : '' }}>
                                {{ $emp->employee_id }} - {{ $emp->name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-3 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>
                        @foreach($leaveTypes as $type)
                            <option value="{{ $type }}" {{ request('leave_type') == $type ? 'selected' : '' }}>{{ $type }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-3 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" {{ $status == 'Pending' ? 'selected' : '' }}>Pending</option>
                        <option value="Approved" {{ $status == 'Approved' ? 'selected' : '' }}>Approved</option>
                        <option value="Rejected" {{ $status == 'Rejected' ? 'selected' : '' }}>Rejected</option>
                    </select>
                </div>
                <div class="col-md-3 mb-2 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary btn-sm mr-2"><i class="fas fa-search mr-1"></i> Filter</button>
                    <a href="{{ route('manager.leave.index') }}" 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</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%">
                <thead class="thead-light">
                    <tr>
                        <th>Employee</th>
                        <th>Department</th>
                        <th>Leave Type</th>
                        <th>From</th>
                        <th>To</th>
                        <th>Days</th>
                        <th>Duration</th>
                        <th>Status</th>
                        <th>Reason</th>
                        <th>Requested On</th>
                        <th width="140" class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($leaves as $leave)
                        <tr id="row-{{ $leave->id }}">
                            <td>
                                <div class="font-weight-bold">{{ $leave->employee->name ?? $leave->employee_name }}</div>
                                <small class="text-muted">{{ $leave->employee->employee_id ?? '-' }}</small>
                            </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
                                    @case('Comp Off') <span class="badge badge-success">Comp Off</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($leave->status == 'Approved') <span class="badge badge-success">Approved</span>
                                @elseif($leave->status == 'Pending') <span class="badge badge-warning">Pending</span>
                                @elseif($leave->status == 'Rejected') <span class="badge badge-danger">Rejected</span>
                                @else <span class="badge badge-secondary">{{ $leave->status }}</span>
                                @endif
                            </td>
                            <td>{{ Str::limit($leave->reason, 25) }}</td>
                            <td>{{ $leave->requested_on ? \Carbon\Carbon::parse($leave->requested_on)->format('d-m-Y') : '-' }}</td>
                            <td class="text-center">
                                @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>
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add/Edit Leave Modal -->
<div class="modal fade" id="leaveModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <form id="leaveForm">
                @csrf
                <input type="hidden" id="leaveId" name="leave_id">
                <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"><span>&times;</span></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Employee <span class="text-danger">*</span></label>
                            <select class="form-control" id="employee_id" name="employee_id" required>
                                <option value="">Select Employee</option>
                                @foreach($employees as $emp)
                                    <option value="{{ $emp->id }}">{{ $emp->employee_id }} - {{ $emp->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-6 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 Type</option>
                                @foreach($leaveTypes as $type)
                                    <option value="{{ $type }}">{{ $type }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">Duration Type</label>
                            <select class="form-control" id="duration_type" name="duration_type">
                                <option value="Full Day">Full Day</option>
                                <option value="Half Day">Half Day</option>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3 half-type-group" style="display: none;">
                            <label class="small font-weight-bold">Half Type</label>
                            <select class="form-control" id="half_type" name="half_type">
                                <option value="First Half">First Half</option>
                                <option value="Second Half">Second Half</option>
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">From Date <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" id="leave_from" name="leave_from" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">To Date <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" id="leave_to" name="leave_to" required>
                        </div>
                    </div>
                    <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="3" required></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary btn-sm"><i class="fa fa-save mr-1"></i> Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Reject Reason Modal -->
<div class="modal fade" id="rejectModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form id="rejectForm">
                @csrf
                <input type="hidden" id="rejectLeaveId">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title"><i class="fas fa-times-circle mr-2"></i> Reject Leave</h5>
                    <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label class="font-weight-bold">Rejection Reason <span class="text-danger">*</span></label>
                        <textarea class="form-control" id="rejection_reason" name="remarks" rows="3" required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger btn-sm">Reject Leave</button>
                </div>
            </form>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$(document).ready(function() {
    $('#leaveTable').DataTable({
        dom: 'Bfrtip',
        buttons: ['copy', 'csv', 'excel', 'pdf', 'print'],
        order: [[9, 'desc']]
    });

    $('#duration_type').on('change', function() {
        if ($(this).val() === 'Half Day') {
            $('.half-type-group').show();
            $('#leave_to').val($('#leave_from').val());
        } else {
            $('.half-type-group').hide();
        }
    });

    $('#addLeaveBtn').on('click', function() {
        $('#leaveForm')[0].reset();
        $('#leaveId').val('');
        $('#leaveModalLabel').html('<i class="fas fa-plus-circle mr-2"></i> New Leave Request');
        $('#leaveModal').modal('show');
    });

    $('#leaveForm').on('submit', function(e) {
        e.preventDefault();
        const leaveId = $('#leaveId').val();
        const url = leaveId ? '{{ url("manager/leave") }}/' + leaveId : '{{ route("manager.leave.store") }}';

        $.ajax({
            url: url,
            type: leaveId ? 'PUT' : 'POST',
            data: $(this).serialize(),
            success: function(response) {
                if (response.success) {
                    Swal.fire('Success', response.message, 'success').then(() => location.reload());
                }
            },
            error: function(xhr) {
                Swal.fire('Error', xhr.responseJSON?.message || 'Failed to save', 'error');
            }
        });
    });

    $(document).on('click', '.edit-btn', function() {
        const id = $(this).data('id');
        $.ajax({
            url: '{{ url("manager/leave") }}/' + id + '/edit',
            success: function(response) {
                if (response.success) {
                    const leave = response.data;
                    $('#leaveId').val(leave.id);
                    $('#employee_id').val(leave.employee_id);
                    $('#leave_type').val(leave.leave_type);
                    $('#duration_type').val(leave.duration_type).trigger('change');
                    $('#half_type').val(leave.half_type);
                    $('#leave_from').val(leave.leave_from ? leave.leave_from.slice(0, 10) : '');
                    $('#leave_to').val(leave.leave_to ? leave.leave_to.slice(0, 10) : '');
                    $('#reason').val(leave.reason);
                    $('#leaveModalLabel').html('<i class="fas fa-edit mr-2"></i> Edit Leave Request');
                    $('#leaveModal').modal('show');
                }
            }
        });
    });

    // Approve Leave
    $(document).on('click', '.approve-btn', function() {
        const id = $(this).data('id');
        Swal.fire({
            title: 'Approve Leave?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#1cc88a',
            confirmButtonText: 'Yes, Approve'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ url("manager/leave") }}/' + id + '/approve',
                    type: 'POST',
                    data: { _token: '{{ csrf_token() }}' },
                    success: function(response) {
                        if (response.success) {
                            Swal.fire('Approved!', response.message, 'success').then(() => location.reload());
                        }
                    },
                    error: function(xhr) {
                        Swal.fire('Error', xhr.responseJSON?.message || 'Failed to approve', 'error');
                    }
                });
            }
        });
    });

    // Reject Leave - Show Modal
    $(document).on('click', '.reject-btn', function() {
        $('#rejectLeaveId').val($(this).data('id'));
        $('#rejection_reason').val('');
        $('#rejectModal').modal('show');
    });

    // Reject Form Submit
    $('#rejectForm').on('submit', function(e) {
        e.preventDefault();
        const id = $('#rejectLeaveId').val();
        $.ajax({
            url: '{{ url("manager/leave") }}/' + id + '/reject',
            type: 'POST',
            data: $(this).serialize(),
            success: function(response) {
                if (response.success) {
                    $('#rejectModal').modal('hide');
                    Swal.fire('Rejected', response.message, 'success').then(() => location.reload());
                }
            },
            error: function(xhr) {
                Swal.fire('Error', xhr.responseJSON?.message || 'Failed to reject', 'error');
            }
        });
    });

    // Delete Leave
    $(document).on('click', '.delete-btn', function() {
        const id = $(this).data('id');
        Swal.fire({
            title: 'Delete Leave?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#e74a3b',
            confirmButtonText: 'Yes, Delete'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ url("manager/leave") }}/' + id,
                    type: 'DELETE',
                    data: { _token: '{{ csrf_token() }}' },
                    success: function(response) {
                        if (response.success) {
                            Swal.fire('Deleted!', response.message, 'success');
                            $('#row-' + id).fadeOut(300, function() { $(this).remove(); });
                        }
                    }
                });
            }
        });
    });
});
</script>
@endsection
