@extends('layouts.dashboard.adminapp')

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

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

@section('content')

    <div class="container-fluid bg-white">
        <!-- Page Heading -->
        <div class="p-2 d-sm-flex align-items-center justify-content-between mb-4">
            <h1 class="h5 mb-0 text-gray-800">
                UEPL | Employee Details
            </h1>
            <div class="display-date">
                <span id="day">day</span>,
                <span id="daynum">00</span>
                <span id="month">month</span>
                <span id="year">0000</span>
            </div>
            <div class="display-time"></div>

        </div>
        <div class="row">
            <div class="col-lg-12">
                @if (session('success'))
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        {{ session('success') }}

                    </div>
                @endif
                @if (session('error'))
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        {{ session('error') }}

                    </div>
                @endif
            </div>
        </div>
        <div class="card">
            
            <div class="card-header d-flex justify-content-between align-items-center">
                <span></span>
                <div class="card-header-asd">
                    <a href="#" class="btn btn-primary btn-sm" id="openPopupButton" style="float: right" title="Add New Employee"><i class="fas fa-plus-square"></i></a>
                    <a href="#" class="btn btn-success btn-sm" data-toggle="modal" data-target="#bulkEmployeeImportModal"
                        style="float:right; margin-right:10px;">
                        <i class="fas fa-upload" title="Bulk Import"></i>
                    </a>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered" id="dataTable" width="100%"
                        cellspacing="0">
                        <thead>
                            <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>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach ($employees as $employee)
                                <tr id="row-{{ $employee->id }}">
                                    <td>{{ $employee->employee_id }}</td>
                                    <td>
                                        @if ($employee->profile_picture)
                                            <img src="{{ asset('storage/' . $employee->profile_picture) }}"
                                                alt="Profile Picture" class="profile-img"
                                                style="width: 42px; height: 42px; border-radius: 50%;"
                                                onerror="this.style.display='none';this.nextElementSibling.style.display='inline';">
                                            <i class="fas fa-user-circle" style="font-size: 42px; color: #ccc; display: none;"></i>
                                        @else
                                            <i class="fas fa-user-circle" style="font-size: 42px; 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>{{ $employee->category }}</td>
                                    <td>
                                        @if (strtolower($employee->status) == 'active')
                                            <span class="badge bg-success">Active</span>
                                        @else
                                            <span class="badge bg-secondary">Inactive</span>
                                        @endif
                                    </td>
                                    <td>
                                        <a href="javascript:void(0);" class="btn btn-warning btn-sm me-1"
                                            onclick="editEmployee({{ $employee->id }})">Edit</a>
                                        <form action="{{ route('admin.employees.delete', $employee->id) }}" method="POST"
                                            style="display:inline;">
                                            @csrf
                                            @method('DELETE')
                                            <button type="submit" class="btn btn-danger btn-sm"
                                                onclick="return confirm('Delete this employee?')">Delete</button>
                                        </form>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Popup Overlay for Add/Edit Employee -->
    <div class="new-employer-popup-overlay" id="new-employer-popup-overlay">
        @if ($errors->any())
            <div class="alert alert-danger m-3">
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        <form class="new-employer-popup-content" id="newEmployerForm" method="POST" enctype="multipart/form-data">
            @csrf
            <input type="hidden" name="_method" id="formMethod" value="POST">
            <h5>New Employee Details</h5><br>
            <div class="hidden"><input type="text" id="employeeIdHidden" name="employeeIdHidden"></div>
            <div class="row">
                <div class="col-md-4">
                    <label for="employeeId">Employee ID <span class="required">*</span></label>
                    <input type="text" id="employeeId" name="employee_id" placeholder="Employee ID" required>
                </div>
                <div class="col-md-4">
                    <label for="employeeName">Employee Name <span class="required">*</span></label>
                    <input type="text" id="employeeName" name="name" placeholder="Employee Name" required>
                </div>
                <div class="col-md-4">
                    <label for="gender">Gender <span class="required">*</span></label>
                    <select id="gender" name="gender" required>
                        <option value="">Select Gender</option>
                        <option value="Male" {{ old('gender') == 'Male' ? 'selected' : '' }}>Male</option>
                        <option value="Female" {{ old('gender') == 'Female' ? 'selected' : '' }}>Female</option>
                        <option value="Other" {{ old('gender') == 'Other' ? 'selected' : '' }}>Other</option>
                    </select>
                </div>
            </div><br>
            <div class="row">
                <div class="col-md-6">
                    <label for="dateOfBirth">Date of Birth</label>
                    <input type="date" id="dateOfBirth" name="dob">
                </div>
                <div class="col-md-6">
                    <label for="dateOfJoin">Date of Joining</label>
                    <input type="date" id="dateOfJoin" name="doj">
                </div>
            </div><br>
            <div class="row">
                <div class="col-md-6">
                    <label for="DepartmentNameSelect">Department</label>
                    <select id="DepartmentNameSelect" name="department">
                        <option value="">Select the option</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">
                    <label for="designation">Designation</label>
                    <input type="text" id="designation" name="designation" placeholder="Designation">
                </div>
            </div><br>
            <div class="row">
                <div class="col-md-6">
                    <label for="Mobile">Contact Number</label>
                    <input type="number" id="Mobile" name="mobile" placeholder="Contact Number"
                        pattern="^[6-9][0-9]{9}$">
                </div>
                <div class="col-md-6">
                    <label for="aadharNumber">Aadhar Number</label>
                    <input type="number" id="aadharNumber" name="aadhar_number" placeholder="Aadhar Number"
                        pattern="^\d{12}$">
                </div>
            </div><br>
            <div class="row">
                <div class="col-md-6">
                    <label for="CategorySelect">Category</label>
                    <select id="CategorySelect" name="category">
                        <option value="">Select the option</option>
                        <option value="E">Employee</option>
                        <option value="M">Management</option>
                        <option value="O">Other</option>
                    </select>
                </div>
                <div class="col-md-6">
                    <label for="Status">Status</label>
                    <select id="Status" name="status">
                        <option value="">Select the option</option>
                        <option value="ACTIVE">ACTIVE</option>
                        <option value="INACTIVE">INACTIVE</option>
                    </select>
                </div>
            </div><br>
            <div class="row">
                <div class="col-md-12">
                    <label for="profilePicture">Profile Picture</label>
                    <input type="file" id="profilePicture" name="profile_picture" accept="image/*">
                </div>
            </div>
            <br>
            <div class="new-employer-popup-buttons">
                <button class="btn btn-success" id="newemployeeSave" type="submit">Save</button>
                <button class="btn btn-danger" type="button" id="closePopup">Close</button>
            </div>
            <br>
        </form>
    </div>
    <!-- Bulk Import Modal -->
    <div class="modal fade" id="bulkEmployeeImportModal" tabindex="-1" role="dialog"
        aria-labelledby="bulkEmployeeImportModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <form method="POST" action="{{ route('admin.employee.import') }}" enctype="multipart/form-data">
                @csrf
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="bulkEmployeeImportModalLabel">Bulk Upload Employees</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="width: auto">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="excel_file" class="form-label">Upload Excel File (.xlsx)</label>
                            <input class="form-control" type="file" id="excel_file" name="excel_file" accept=".xlsx"
                                required>
                            <small>
                                <a href="{{ asset('templates/employee_import_template.xlsx') }}" download>
                                    Download Sample Template
                                </a>
                            </small>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-success">Import</button>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
@endsection

@section('scripts')
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap5.min.js"></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"
                }
            });

            // Popup logic
            const openPopupButton = document.getElementById('openPopupButton');
            const popupOverlay = document.getElementById('new-employer-popup-overlay');
            const closePopupButton = document.getElementById('closePopup');

            openPopupButton.addEventListener('click', function(event) {
                event.preventDefault();
                popupOverlay.style.display = 'flex';
                $('#newEmployerForm').trigger('reset');
                $('#newEmployerForm').attr('action', '{{ route('admin.employees.store') }}');
                $('#formMethod').val('POST');
            });

            closePopupButton.addEventListener('click', function() {
                popupOverlay.style.display = 'none';
            });
        });

        // Edit Employee AJAX
        function editEmployee(employeeId) {
            const baseUrl = @json(url('/'));
            const popupOverlay = document.getElementById('new-employer-popup-overlay');
            popupOverlay.style.display = 'flex';

            $.ajax({
                url: `${baseUrl}/admin/employees/${employeeId}`,
                type: 'GET',
                success: function(employee) {
                    $('#employeeId').val(employee.employee_id);
                    $('#employeeName').val(employee.name);
                    $('#gender').val(employee.gender);
                    $('#dateOfBirth').val(employee.dob);
                    $('#dateOfJoin').val(employee.doj);
                    $('#DepartmentNameSelect').val(employee.department);
                    $('#designation').val(employee.designation);
                    $('#Mobile').val(employee.mobile);
                    $('#aadharNumber').val(employee.aadhar_number);
                    $('#CategorySelect').val(employee.category);
                    $('#Status').val(employee.status);

                    $('#newEmployerForm').attr('action', `${baseUrl}/admin/employees/${employeeId}`);
                    $('#formMethod').val('PUT');
                },
                error: function() {
                    alert('Failed to fetch employee data.');
                }
            });
        }
    </script>
@endsection
