<?php $__env->startSection('title', 'Users Management'); ?>

<?php $__env->startSection('content'); ?>
<div class="bg-white shadow-md rounded-lg p-4 mb-4 flex justify-between items-center">

    <div class="flex items-center space-x-2">

        <label for="entriesPerPage" class="text-sm font-medium text-gray-700">Show</label>

        <select id="entriesPerPage" class="border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring focus:border-blue-500 text-sm">

            <option value="10" selected>10</option>

            <option value="25">25</option>

            <option value="50">50</option>

            <option value="100">100</option>

        </select>

        <span class="text-sm font-medium text-gray-700">entries</span>
</div>
        <input type="text" id="searchInput" placeholder="Search..." 
        class="border border-gray-300 rounded-lg px-4 py-2 w-64 focus:ring focus:border-blue-500 shadow-sm">
</div>
<div class="flex justify-between mb-4">
    <div class="flex space-x-4">
        <!-- Filter by Role -->
        <div>
            <label for="filter_role" class="block text-sm font-semibold">User Role</label>
            <select id="filter_role" name="filter_role" class="w-full px-3 py-2 border rounded">
                <option value="">-- Select --</option>
                <option value="HR">HR</option>
                <option value="Team Lead">Team Lead</option>
                <option value="Employee">Employee</option>
                <option value="Freelancer">Freelancer</option>
                <option value="Project Manager">Project Manager</option>
            </select>
        </div>
        <div>
            <label for="filter_department" class="block text-sm font-semibold">Department</label>
            <select id="filter_department" name="filter_department" class="w-full px-3 py-2 border rounded">
                <option value="">-- Select --</option>
                <?php $__currentLoopData = $departments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $department): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <option value="<?php echo e($department->id); ?>"><?php echo e($department->name); ?></option>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </select>
        </div>
         <div>
            <label for="filter_reporting_person" class="block text-sm font-semibold">Reporting Person</label>
            <select id="filter_reporting_person" name="filter_reporting_person" class="w-full px-3 py-2 border rounded">
                <option value="">-- Select --</option>
                <?php $__currentLoopData = $allUsersForDropdown; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $user): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <option value="<?php echo e($user->id); ?>"><?php echo e($user->name); ?></option>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </select>
        </div>

        
        <div class="pt-8">
            <button id="filterButton" class="bg-blue-600 text-white px-4 py-2 rounded-md">Filter</button>
        </div>
       
    </div>
</div>

<div class="bg-white shadow-lg rounded-lg p-6">
    <div class="flex justify-between items-center mb-4">
        <div id="successMessage" class="hidden bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4">
            <strong>Success!</strong> <span id="successText"></span>
        </div>
        <h2 class="text-2xl font-bold text-gray-700">Users Management</h2>
        <button onclick="openModal('userModal')" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg shadow-md transition-all">+ Add User</button>
    </div>
    
    <div class="overflow-x-auto bg-white shadow-md rounded-lg">
        <table class="min-w-full border-collapse border border-gray-200 rounded-lg overflow-hidden" id="usersTable">
            <thead>
                <tr class="bg-blue-100 text-gray-700 text-left">
                    <th class="border px-6 py-3">S/No</th>
                    <th class="border px-6 py-3">Name</th>
                    <th class="border px-6 py-3">User Info</th>
                    <th class="border px-6 py-3">User Role</th>
                    <th class="border px-6 py-3">User Target</th>
                    <th class="border px-6 py-3">Action</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-200">
                <?php $__currentLoopData = $users; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $user): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <tr id="user-<?php echo e($user->id); ?>" class="hover:bg-gray-50 transition-all">
                    <td class="border px-6 py-4 text-center"><?php echo e($users->firstItem() + $loop->index); ?></td>
                    <td class="border px-6 py-4 flex items-center space-x-3">
                        <img src="<?php echo e($user->image ? asset('storage/' . $user->image) : asset('storage/images/default.png')); ?>" alt="User Image" class="w-12 h-12 rounded-full object-cover shadow-md">
                        <span class="font-semibold text-gray-700"><?php echo e($user->name); ?></span>
                    </td>
                    <td class="border px-6 py-4 text-gray-600">
                        <span class="block"><strong>Email:</strong> <?php echo e($user->email); ?></span>
                        <span class="block"><strong>Phone:</strong> <?php echo e($user->phone_number); ?></span>
                        <span class="block"><strong>Disable Login:</strong> <?php echo e($user->disable_login ? 'Yes' : 'No'); ?></span>
                    </td>
                    <td class="border px-6 py-4">
                        <span class="block font-semibold text-blue-700">Role:<?php echo e($user->roles->pluck('name')->first()); ?></span>
                        <span class="block text-gray-600">Dept: <?php echo e($user->department->name ?? '-'); ?></span>
                        <span class="block text-gray-600">Emp Code: <?php echo e($user->employee_code); ?></span>
                        <span class="block text-gray-600">Reporting: <?php echo e(optional($user->reportingPerson)->name ?? '-'); ?></span><br>
                    </td>
                    <td class="border px-6 py-4 text-gray-600">
                        <strong>Monthly:</strong> <?php echo e($user->monthly_target); ?><br>
                        <strong>Incentive:</strong> <?php echo e($user->upsell_incentive); ?>%
                    </td>
                    <td class="border px-6 py-4 flex space-x-2">
                        <button onclick="editUser(<?php echo e($user->id); ?>)" class="bg-yellow-500 hover:bg-yellow-600 text-white px-3 py-1 rounded shadow-md transition-all">Edit</button>
                        <button onclick="deleteUser(<?php echo e($user->id); ?>)" class="bg-red-500 hover:bg-red-600 text-white px-3 py-1 rounded shadow-md transition-all">Delete</button>
                    </td>
                </tr>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </tbody>
        </table>
    </div>
    <?php if($users instanceof \Illuminate\Pagination\LengthAwarePaginator && $users->total() > 6): ?>

    <div id="paginationLinks" class="mt-4">
        <?php echo e($users->links()); ?>

    </div>
    <?php endif; ?>
</div>

<!-- Add/Edit User Modal -->
<div id="userModal" class="fixed inset-0 bg-gray-900 bg-opacity-50 hidden flex items-center justify-center p-4">
    <div class="bg-white p-6 rounded-lg w-full max-w-2xl relative overflow-y-auto max-h-[90vh]">
        <button onclick="closeModal('userModal')" class="absolute top-3 right-3 text-xl text-gray-500 hover:text-black">&times;</button>
        <h2 class="text-xl font-bold mb-4 text-center" id="modalTitle">Add User</h2>
        <div class="max-h-[70vh] overflow-y-auto p-2">
            <form id="userForm" method="POST" action="<?php echo e(route('users.store')); ?>" enctype="multipart/form-data">
                <?php echo csrf_field(); ?>
                <input type="hidden" id="userId" name="userId">
                <div class="grid grid-cols-2 gap-4">
                    <div><label>Name</label><input type="text" id="name" name="name" class="w-full px-3 py-2 border rounded"></div>
                    <div><label>Email</label><input type="email" id="email" name="email" class="w-full px-3 py-2 border rounded"></div>
                    <div><label>Phone Number</label><input type="text" id="phone_number" name="phone_number" class="w-full px-3 py-2 border rounded"></div>
                    <div>
    <label>Role</label>
    <select id="role" name="role" class="w-full px-3 py-2 border rounded">
        <option value="">Select Role</option>
        <option value="Admin">Admin</option>
        <option value="HR">HR</option>
        <option value="Team Lead">Team Lead</option>
        <option value="Employee">Employee</option>
        <option value="Freelancer">Freelancer</option>
        <option value="Project Manager">Project Manager</option>
    </select>
</div>

                    <div><label>Monthly Target</label><input type="text" id="monthly_target" name="monthly_target" class="w-full px-3 py-2 border rounded"></div>
                    <div><label>Upsell Incentive (%)</label><input type="number" id="upsell_incentive" name="upsell_incentive" class="w-full px-3 py-2 border rounded"></div>
                    <div>
    <label>Reporting Person</label>
    <select id="reporting_person" name="reporting_person" class="w-full px-3 py-2 border rounded">
        <option value="">Select Reporting Person</option>
        <?php $__currentLoopData = $allUsersForDropdown; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $user): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            <option value="<?php echo e($user->id); ?>"><?php echo e($user->name); ?></option>
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
    </select>
</div>

                    <div>
                        <label>Department</label>
                        <select id="department" name="department" class="w-full px-3 py-2 border rounded">
                            <option value="">Select Department</option>
                            <?php $__currentLoopData = $departments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $department): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($department->id); ?>"><?php echo e($department->name); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>
                    <div><label>Experience</label><input type="text" id="experience" name="experience" class="w-full px-3 py-2 border rounded"></div>
                    <div><label>Qualification</label><input type="text" id="qualification" name="qualification" class="w-full px-3 py-2 border rounded"></div>
                    <div><label>Specialization</label><input type="text" id="specialization" name="specialization" class="w-full px-3 py-2 border rounded"></div>
                    <div><label>Date of Joining</label><input type="date" id="date_of_joining" name="date_of_joining" class="w-full px-3 py-2 border rounded"></div>
                    <div>
    <label>Employee Code</label>
    <div class="flex">
        <input type="text" id="employee_code" name="employee_code" class="w-full px-3 py-2 border rounded" >
        <button type="button" id="generateEmployeeCode" class="ml-2 px-3 py-2 bg-blue-500 text-white rounded">Generate</button>
    </div>
</div>

                    <div><label>Password</label><input type="password" id="password" name="password" class="w-full px-3 py-2 border rounded"></div>
                    <div><label>Confirm Password</label><input type="password" id="password_confirmation" name="password_confirmation" class="w-full px-3 py-2 border rounded"></div>
                    <div class="mb-4">
    <label>Profile Image</label>
    <img id="imagePreview" src="" class="w-24 h-24 rounded-full object-cover mb-2 hidden">
    <input type="file" id="image" name="image" accept="image/*" class="w-full px-3 py-2 border rounded">
</div>
                </div>
            </form>
        </div>
        <div class="flex justify-end space-x-2 mt-4">
            <button type="button" onclick="closeModal('userModal')" class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600 transition-all">Cancel</button>
            <button type="button" id="submitUserForm" class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-all">Save</button>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>


<?php $__env->startSection('scripts'); ?>
<script>
    function openModal(id) {
        document.getElementById(id).classList.remove('hidden');
    }

    function closeModal(id) {
    document.getElementById(id).classList.add('hidden');
    document.getElementById('userForm').reset();
    document.getElementById('userId').value = '';
    document.getElementById('modalTitle').innerText = 'Add User';
    document.getElementById('successMessage').classList.add('hidden');

    $('#generateEmployeeCode').show(); // Show the button when opening the modal for adding a new user
    $('#employee_code').prop('readonly', false); // Make the field editable
}
</script>
<script>
$(document).ready(function () {
    $('#submitUserForm').on('click', function (event) {
        event.preventDefault();

        let userId = $('#userId').val();
        let url = userId ? `/users/${userId}` : "<?php echo e(route('users.store')); ?>";
        let method = userId ? "POST" : "POST"; // Always POST, use _method for PUT

        let formData = new FormData($('#userForm')[0]);
        formData.append('_token', '<?php echo e(csrf_token()); ?>');
        if (userId) {
            formData.append('_method', 'PUT'); // Required for updates
        }

        // Clear previous errors
        $('.error-message').remove();
        $('.border-red-500').removeClass('border-red-500');

        $.ajax({
            url: url,
            method: method,
            data: formData,
            processData: false,
            contentType: false,
            success: function (response) {
                if (response.success) {
                    alert(response.success);
                    location.reload();
                }
            },
            error: function (xhr) {
                if (xhr.status === 422) {
                    let errors = xhr.responseJSON.errors;
                    $.each(errors, function (key, value) {
                        let input = $('#' + key);
                        input.addClass('border-red-500'); // Highlight the field with error
                        input.after('<span class="error-message text-red-500 text-sm">' + value[0] + '</span>');
                    });
                } else {
                    alert('Something went wrong!');
                }
            }
        });
    });
});



</script>
<script>

function editUser(userId) {
    $.ajax({
        url: `/users/${userId}/edit`,
        method: "GET",
        success: function (response) {
            $('#userId').val(response.id);
            $('#name').val(response.name);
            $('#email').val(response.email);
            $('#phone_number').val(response.phone_number);
            $('#monthly_target').val(response.monthly_target);
            $('#upsell_incentive').val(response.upsell_incentive);
            $('#reporting_person').val(response.reporting_person).change();
            $('#department').val(response.department).change();
            $('#experience').val(response.experience);
            $('#qualification').val(response.qualification);
            $('#specialization').val(response.specialization);
            $('#date_of_joining').val(response.date_of_joining);
            
            $('#employee_code').val(response.employee_code).prop('readonly', true); // Disable field
            $('#generateEmployeeCode').hide(); // Hide the button in edit mode

            $('#role').val(response.role).change();
            $('#disable_login').val(response.disable_login).change();

            // Show stored image
            if (response.image) {
                $('#imagePreview').attr('src', response.image).removeClass('hidden');
            } else {
                $('#imagePreview').addClass('hidden');
            }

            $('#modalTitle').text('Edit User');
            openModal('userModal');
        },
        error: function (xhr) {
            console.error('Error fetching user data:', xhr.responseText);
            alert('Error fetching user data');
        }
    });
}



</script>
<script>
    function deleteUser(userId) {
        if (!confirm('Are you sure you want to delete this user?')) return;

        fetch(`/users/${userId}`, {
            method: 'DELETE',
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                'Content-Type': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            alert(data.success);
            location.reload(); // Reload the page after successful deletion
        })
        .catch(error => console.error('Error:', error));
    }
</script>
<script>
$(document).ready(function () {
    function fetchUsers(page = 1) {
        var role = $('#filter_role').val();
        var department = $('#filter_department').val();
        var reportingPerson = $('#filter_reporting_person').val(); // Get selected reporting person


        $.ajax({
            url: "<?php echo e(route('users.filter')); ?>?page=" + page,
            type: "GET",
            data: { 
                role: role, 
                department: department,
                reporting_person: reportingPerson // Include reporting person in the request
            },
            success: function (response) {
    let tbody = $('table#usersTable tbody');
    let htmlContent = $.trim(response.html);

    // Check if the response contains valid table rows
    if (htmlContent !== '' && htmlContent !== '<div id="paginationLinks" style="display: none;"></div>') {
        tbody.html(htmlContent);
    } else {
        tbody.html('<tr><td colspan="6" class="text-center py-4 text-gray-500">No records found</td></tr>');
    }

    $('#paginationLinks').html(response.pagination || '');
},
            error: function (xhr) {
                console.log(xhr.responseText);
                alert("Error fetching users. Please try again.");
            }
        });
    }

    // Apply filter on button click
    $('#filterButton').click(function (e) {
        e.preventDefault();
        fetchUsers(); // Load filtered results
    });

    // Handle pagination clicks
    $(document).on('click', '#paginationLinks a', function (e) {
        e.preventDefault();
        var page = $(this).attr('href').split('page=')[1];
        fetchUsers(page);
    });
});



</script>
<script>
    var generateCodeUrl = "<?php echo e(route('users.generateEmployeeCode')); ?>";
</script>

<script>
    $(document).ready(function () {
    $('#generateEmployeeCode').on('click', function () {
        $.ajax({
            url: generateCodeUrl,
            method: "GET",
            success: function (response) {
                if (response.code) {
                    $('#employee_code').val(response.code);
                }
            },
            error: function (xhr) {
                alert("Error generating Employee Code. Please try again.");
            }
        });
    });
});
document.addEventListener("DOMContentLoaded", function () {
    let searchInput = document.getElementById("searchInput");
    let entriesSelect = document.getElementById("entriesPerPage");
    let table = document.querySelector("table tbody");
    let rows = table.getElementsByTagName("tr");

    // Function to filter table rows based on search input
    function filterTable() {
        let searchText = searchInput.value.toLowerCase();

        Array.from(rows).forEach(row => {
            let textContent = row.innerText.toLowerCase();
            row.style.display = textContent.includes(searchText) ? "" : "none";
        });
    }

    // Function to control entries per page
    function updateEntriesPerPage() {
        let numEntries = parseInt(entriesSelect.value);
        let totalRows = rows.length;

        // Show only selected number of rows
        Array.from(rows).forEach((row, index) => {
            row.style.display = index < numEntries ? "" : "none";
        });
    }

    // Event listeners
    searchInput.addEventListener("keyup", filterTable);
    entriesSelect.addEventListener("change", updateEntriesPerPage);

    // Initialize the table with the default entries per page
    updateEntriesPerPage();
});


    </script>


<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.dashboard', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH C:\xampp\htdocs\crm\resources\views/users/index.blade.php ENDPATH**/ ?>