@extends('layouts.dashboard.superadminapp')

@section('title', 'Employee Details')

@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;
    }
    .profile-img {
        object-fit: cover;
    }
    #dataTable .badge {
        font-size: 0.85em;
    }
    .table-actions .btn {
        padding: 0.2rem 0.4rem;
        font-size: 0.75rem;
    }
</style>
@endsection

@section('content')

<!-- Page Heading -->
<x-layout.page-header title="UEPL | Employee Details" 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(session('errorRows'))
    <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(session('errorRows') 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

<!-- Employee 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-users mr-2"></i> Employee List
        </h6>
        <div>
            <button class="btn btn-success btn-sm mr-1" data-toggle="modal" data-target="#bulkImportModal">
                <i class="fas fa-file-excel mr-1"></i> Bulk Import
            </button>
            <button class="btn btn-light btn-sm" id="addEmployeeBtn">
                <i class="fas fa-plus mr-1"></i> Add Employee
            </button>
        </div>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered table-striped table-sm" id="dataTable" width="100%" cellspacing="0">
                <thead class="thead-light">
                    <tr>
                        <th>Employee ID</th>
                        <th>Image</th>
                        <th>Employee Name</th>
                        <th>Gender</th>
                        <th>Department</th>
                        <th>Designation</th>
                        <th>Date of Birth</th>
                        <th>Date of Joining</th>
                        <th>Contact Number</th>
                        <th>Aadhar Number</th>
                        <th>Category</th>
                        <th>Status</th>
                        <th width="100" class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($employees as $employee)
                        <tr id="row-{{ $employee->id }}">
                            <td>{{ $employee->employee_id }}</td>
                            <td class="text-center">
                                @if($employee->profile_picture)
                                    <img src="{{ asset('storage/' . $employee->profile_picture) }}"
                                         alt="Profile" class="profile-img"
                                         style="width: 40px; height: 40px; border-radius: 50%;"
                                         onerror="this.style.display='none';this.nextElementSibling.style.display='inline';">
                                    <i class="fas fa-user-circle" style="font-size: 40px; color: #ccc; display: none;"></i>
                                @else
                                    <i class="fas fa-user-circle" style="font-size: 40px; color: #ccc;"></i>
                                @endif
                            </td>
                            <td>{{ $employee->name }}</td>
                            <td>{{ $employee->gender }}</td>
                            <td>{{ $employee->department }}</td>
                            <td>{{ $employee->designation }}</td>
                            <td>{{ $employee->dob }}</td>
                            <td>{{ $employee->doj }}</td>
                            <td>{{ $employee->mobile }}</td>
                            <td>{{ $employee->aadhar_number }}</td>
                            <td>
                                @switch($employee->category)
                                    @case('E')
                                        <span class="badge badge-info">Employee</span>
                                        @break
                                    @case('M')
                                        <span class="badge badge-primary">Management</span>
                                        @break
                                    @case('O')
                                        <span class="badge badge-secondary">Others</span>
                                        @break
                                    @default
                                        <span class="badge badge-light">NA</span>
                                @endswitch
                            </td>
                            <td>
                                @if(strtolower($employee->status) == 'active')
                                    <span class="badge badge-success">Active</span>
                                @else
                                    <span class="badge badge-secondary">Inactive</span>
                                @endif
                            </td>
                            <td>
                                <div class="btn-group table-actions" role="group">
                                    <button class="btn btn-warning btn-sm edit-btn" data-id="{{ $employee->id }}" title="Edit">
                                        <i class="fa fa-edit"></i>
                                    </button>
                                    <button class="btn btn-danger btn-sm delete-btn" data-id="{{ $employee->id }}" title="Delete">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add/Edit Employee Modal -->
<div class="modal fade" id="employeeModal" tabindex="-1" role="dialog" aria-labelledby="employeeModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <form id="employeeForm" enctype="multipart/form-data">
                @csrf
                <input type="hidden" id="employeeIdHidden" name="employeeIdHidden">
                <div class="modal-header" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
                    <h5 class="modal-title text-white" id="employeeModalLabel">
                        <i class="fas fa-user-plus mr-2"></i> Add New Employee
                    </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>

                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">Employee ID <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="employeeId" name="employee_id" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">Employee Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="employeeName" name="name" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">Gender <span class="text-danger">*</span></label>
                            <select class="form-control" id="gender" name="gender" required>
                                <option value="">Select Gender</option>
                                <option value="Male">Male</option>
                                <option value="Female">Female</option>
                                <option value="Other">Other</option>
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Date of Birth</label>
                            <input type="date" class="form-control" id="dateOfBirth" name="dob">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Date of Joining</label>
                            <input type="date" class="form-control" id="dateOfJoin" name="doj">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Department</label>
                            <select class="form-control" id="department" name="department">
                                <option value="">Select Department</option>
                                <option value="MACHINING">MACHINING</option>
                                <option value="FABRICATION">FABRICATION</option>
                                <option value="MANAGEMENT">MANAGEMENT</option>
                                <option value="MAINTENANCE">MAINTENANCE</option>
                                <option value="DISPATCH">DISPATCH</option>
                                <option value="HOUSE KEEPING">HOUSE KEEPING</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Designation</label>
                            <input type="text" class="form-control" id="designation" name="designation">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Contact Number</label>
                            <input type="text" class="form-control" id="mobile" name="mobile" pattern="^[6-9][0-9]{9}$">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Aadhar Number</label>
                            <input type="text" class="form-control" id="aadharNumber" name="aadhar_number" pattern="^\d{12}$">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Category</label>
                            <select class="form-control" id="category" name="category">
                                <option value="">Select Category</option>
                                <option value="E">Employee</option>
                                <option value="M">Management</option>
                                <option value="O">Other</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Status</label>
                            <select class="form-control" id="status" name="status">
                                <option value="">Select Status</option>
                                <option value="ACTIVE">ACTIVE</option>
                                <option value="INACTIVE">INACTIVE</option>
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Profile Picture</label>
                            <input type="file" class="form-control" id="profilePicture" name="profile_picture" accept="image/*">
                        </div>
                        <div class="col-md-6 mb-3">
                            <div id="existingFileSection" style="display: none;">
                                <label class="small font-weight-bold">Current Picture</label>
                                <div class="d-flex align-items-center">
                                    <a href="#" id="existingFileLink" target="_blank" class="btn btn-outline-info btn-sm mr-2">
                                        <i class="fa fa-eye mr-1"></i> View
                                    </a>
                                    <button type="button" class="btn btn-outline-danger btn-sm" id="removeFileBtn">
                                        <i class="fa fa-trash mr-1"></i> Remove
                                    </button>
                                </div>
                            </div>
                            <div id="imagePreview" class="mt-2" style="display: none;">
                                <img id="previewImage" src="#" alt="Preview" style="max-width: 100px; max-height: 100px; border-radius: 5px;">
                            </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="saveEmployeeBtn">
                        <i class="fa fa-save mr-1"></i> Save Employee
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Bulk Import Modal -->
<div class="modal fade" id="bulkImportModal" tabindex="-1" role="dialog" aria-labelledby="bulkImportModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form method="POST" action="{{ route('superadmin.employee.import') }}" enctype="multipart/form-data">
                @csrf
                <div class="modal-header" style="background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%);">
                    <h5 class="modal-title text-white" id="bulkImportModalLabel">
                        <i class="fas fa-file-excel mr-2"></i> Bulk Upload Employees
                    </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 class="mb-3">
                        <label class="small font-weight-bold">Upload Excel File (.xlsx) <span class="text-danger">*</span></label>
                        <input class="form-control" type="file" id="excel_file" name="excel_file" accept=".xlsx" required>
                        <small class="text-muted">
                            <a href="{{ asset('templates/employee_import_template.xlsx') }}" download>
                                <i class="fas fa-download mr-1"></i> Download Sample Template
                            </a>
                        </small>
                    </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-success btn-sm">
                        <i class="fa fa-upload mr-1"></i> Import
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$(document).ready(function() {
    // DataTable initialization
    $('#dataTable').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,
        responsive: true,
        language: {
            emptyTable: "No employees found"
        }
    });

    // Add Employee Button
    $('#addEmployeeBtn').on('click', function() {
        resetForm();
        $('#employeeModalLabel').html('<i class="fas fa-user-plus mr-2"></i> Add New Employee');
        $('#employeeModal').modal('show');
    });

    // Reset form function
    function resetForm() {
        $('#employeeForm')[0].reset();
        $('#employeeIdHidden').val('');
        $('#formError').hide();
        $('#existingFileSection').hide();
        $('#imagePreview').hide();
        $('#previewImage').attr('src', '#');
    }

    // Image preview on file select
    $('#profilePicture').on('change', function(e) {
        const file = e.target.files[0];
        if (file && file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = function(e) {
                $('#previewImage').attr('src', e.target.result);
                $('#imagePreview').show();
            };
            reader.readAsDataURL(file);
        } else {
            $('#imagePreview').hide();
        }
    });

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

        $.ajax({
            url: '{{ url("/superadmin/employees") }}/' + id,
            type: 'GET',
            success: function(employee) {
                $('#employeeIdHidden').val(id);
                $('#employeeId').val(employee.employee_id);
                $('#employeeName').val(employee.name);
                $('#gender').val(employee.gender);
                $('#dateOfBirth').val(employee.dob);
                $('#dateOfJoin').val(employee.doj);
                $('#department').val(employee.department);
                $('#designation').val(employee.designation);
                $('#mobile').val(employee.mobile);
                $('#aadharNumber').val(employee.aadhar_number);
                $('#category').val(employee.category);
                $('#status').val(employee.status);

                if (employee.profile_picture) {
                    $('#existingFileLink').attr('href', '{{ asset("storage") }}/' + employee.profile_picture);
                    $('#existingFileSection').show();
                } else {
                    $('#existingFileSection').hide();
                }

                $('#employeeModalLabel').html('<i class="fas fa-user-edit mr-2"></i> Edit Employee');
                $('#employeeModal').modal('show');
            },
            error: function() {
                Swal.fire('Error!', 'Failed to fetch employee data.', 'error');
            }
        });
    });

    // Save Employee (Add/Edit)
    $('#employeeForm').on('submit', function(e) {
        e.preventDefault();

        const id = $('#employeeIdHidden').val();
        const formData = new FormData(this);

        if (id) {
            formData.append('_method', 'PUT');
        }

        const url = id
            ? '{{ url("/superadmin/employees") }}/' + id
            : '{{ route("superadmin.employees.store") }}';

        $.ajax({
            url: url,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            success: function(response) {
                if (response.success) {
                    $('#employeeModal').modal('hide');
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: id ? 'Employee updated successfully!' : 'Employee added successfully!',
                        timer: 1500,
                        showConfirmButton: false
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    $('#formError').text(response.message || 'Something went wrong!').show();
                }
            },
            error: function(xhr) {
                if (xhr.status === 422) {
                    const errors = xhr.responseJSON.errors;
                    const firstError = Object.values(errors)[0][0];
                    $('#formError').text(firstError).show();
                } else {
                    $('#formError').text('Server error. Please try again.').show();
                }
            }
        });
    });

    // Remove Profile Picture
    $('#removeFileBtn').on('click', function() {
        const employeeId = $('#employeeIdHidden').val();
        if (!employeeId) return;

        Swal.fire({
            title: 'Remove Picture?',
            text: "Are you sure you want to remove the profile picture?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, Remove!',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ url("/superadmin/employees") }}/' + employeeId + '/profile-picture',
                    type: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    },
                    success: function(response) {
                        if (response.success) {
                            $('#existingFileSection').hide();
                            Swal.fire('Removed!', 'Profile picture removed.', 'success');
                        } else {
                            Swal.fire('Error!', response.message || 'Failed to remove.', 'error');
                        }
                    },
                    error: function() {
                        Swal.fire('Error!', 'Server error.', 'error');
                    }
                });
            }
        });
    });

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

        Swal.fire({
            title: 'Delete Employee?',
            text: "Are you sure you want to delete this employee?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, Delete!',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ url("/superadmin/employees") }}/' + id,
                    type: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    },
                    success: function(response) {
                        $('#row-' + id).remove();
                        Swal.fire('Deleted!', 'Employee deleted successfully.', 'success');
                    },
                    error: function() {
                        Swal.fire('Error!', 'Failed to delete employee.', 'error');
                    }
                });
            }
        });
    });

    // Reset modal on close
    $('#employeeModal').on('hidden.bs.modal', function() {
        resetForm();
    });
});
</script>
@endsection
