@extends('layouts.admin-simple')

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

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item active">User Management</li>
@endsection

@section('page-title')
    <div class="d-flex justify-content-between align-items-center w-100">
        <div class="page-title-left">
            <h3 class="mb-1">User Management</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Manage warehouse user accounts and roles</p>
        </div>
        <div class="page-actions-right d-flex align-items-center">
            @can('warehouse.users.create')
            <button type="button" onclick="showAddUserModal()" class="btn btn-sm btn-primary" title="Add new user">
                <i class="material-icons mr-1" style="font-size: 16px;">person_add</i>
                Add User
            </button>
            @endcan
        </div>
    </div>
@endsection

@section('content')
    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-4">
            <x-warehouse.stats-card
                title="Total Users"
                value="0"
                icon="people"
                color="primary"
                subtitle="Warehouse users"
                :loading="true"
                id="total-users-card"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <x-warehouse.stats-card
                title="Active Users"
                value="0"
                icon="person"
                color="success"
                subtitle="Currently active"
                :loading="true"
                id="active-users-card"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <x-warehouse.stats-card
                title="Inactive Users"
                value="0"
                icon="person_off"
                color="warning"
                subtitle="Currently inactive"
                :loading="true"
                id="inactive-users-card"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <x-warehouse.stats-card
                title="Roles"
                value="5"
                icon="admin_panel_settings"
                color="info"
                subtitle="Available roles"
            />
        </div>
    </div>

    <!-- Users Table -->
    <div class="card">
        <div class="card-header">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <h5 class="mb-0 d-flex align-items-center">
                        <i class="material-icons mr-2">people</i>
                        Users List
                    </h5>
                </div>
                <div class="col-md-6">
                    <div class="row">
                        <div class="col-md-6">
                            <select id="role-filter" class="form-control form-control-sm" title="Filter by role">
                                <option value="">All Roles</option>
                                @foreach($roles as $role)
                                    <option value="{{ $role->id }}">{{ $role->display_name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-6">
                            <select id="status-filter" class="form-control form-control-sm" title="Filter by status">
                                <option value="">All Status</option>
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table id="users-table" class="table table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>User</th>
                            <th>Contact</th>
                            <th>Department</th>
                            <th>Role</th>
                            <th>Status</th>
                            <th>Last Login</th>
                            <th class="text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Data will be populated by DataTables -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add User Modal -->
    <div class="modal fade" id="addUserModal" tabindex="-1" role="dialog" aria-labelledby="addUserModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addUserModalLabel">
                        <i class="material-icons mr-2">person_add</i>
                        Add New User
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="addUserForm">
                        @csrf
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="name">Full Name <span class="text-danger">*</span></label>
                                    <input type="text" name="name" id="name" class="form-control" required>
                                    <div class="invalid-feedback"></div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="email">Email Address <span class="text-danger">*</span></label>
                                    <input type="email" name="email" id="email" class="form-control" required>
                                    <div class="invalid-feedback"></div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="employee_id">Employee ID</label>
                                    <input type="text" name="employee_id" id="employee_id" class="form-control">
                                    <div class="invalid-feedback"></div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="phone">Phone Number</label>
                                    <input type="tel" name="phone" id="phone" class="form-control">
                                    <div class="invalid-feedback"></div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="department">Department <span class="text-danger">*</span></label>
                                    <input type="text" name="department" id="department" class="form-control" required>
                                    <div class="invalid-feedback"></div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="role_id">Role <span class="text-danger">*</span></label>
                                    <select name="role_id" id="role_id" class="form-control" required>
                                        <option value="">Select a role</option>
                                        @foreach($roles as $role)
                                            <option value="{{ $role->id }}">{{ $role->display_name }}</option>
                                        @endforeach
                                    </select>
                                    <div class="invalid-feedback"></div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="password">Password <span class="text-danger">*</span></label>
                                    <input type="password" name="password" id="password" class="form-control" required minlength="8">
                                    <div class="invalid-feedback"></div>
                                    <small class="form-text text-muted">Minimum 8 characters</small>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="password_confirmation">Confirm Password <span class="text-danger">*</span></label>
                                    <input type="password" name="password_confirmation" id="password_confirmation" class="form-control" required minlength="8">
                                    <div class="invalid-feedback"></div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" onclick="saveUser()" class="btn btn-primary">
                        <i class="material-icons mr-1" style="font-size: 16px;">save</i>
                        Create User
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit User Modal -->
    <div class="modal fade" id="editUserModal" tabindex="-1" role="dialog" aria-labelledby="editUserModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editUserModalLabel">
                        <i class="material-icons mr-2">edit</i>
                        Edit User
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="editUserForm">
                        @csrf
                        @method('PUT')
                        <input type="hidden" id="edit_user_id" name="user_id">

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_name">Full Name <span class="text-danger">*</span></label>
                                    <input type="text" name="name" id="edit_name" class="form-control" required>
                                    <div class="invalid-feedback"></div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_email">Email Address <span class="text-danger">*</span></label>
                                    <input type="email" name="email" id="edit_email" class="form-control" required>
                                    <div class="invalid-feedback"></div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_employee_id">Employee ID</label>
                                    <input type="text" name="employee_id" id="edit_employee_id" class="form-control">
                                    <div class="invalid-feedback"></div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_phone">Phone Number</label>
                                    <input type="tel" name="phone" id="edit_phone" class="form-control">
                                    <div class="invalid-feedback"></div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_department">Department <span class="text-danger">*</span></label>
                                    <input type="text" name="department" id="edit_department" class="form-control" required>
                                    <div class="invalid-feedback"></div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_role_id">Role <span class="text-danger">*</span></label>
                                    <select name="role_id" id="edit_role_id" class="form-control" required>
                                        <option value="">Select a role</option>
                                        @foreach($roles as $role)
                                            <option value="{{ $role->id }}">{{ $role->display_name }}</option>
                                        @endforeach
                                    </select>
                                    <div class="invalid-feedback"></div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_status">Status <span class="text-danger">*</span></label>
                                    <select name="status" id="edit_status" class="form-control" required>
                                        <option value="active">Active</option>
                                        <option value="inactive">Inactive</option>
                                    </select>
                                    <div class="invalid-feedback"></div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_password">New Password</label>
                                    <input type="password" name="password" id="edit_password" class="form-control" minlength="8">
                                    <div class="invalid-feedback"></div>
                                    <small class="form-text text-muted">Leave blank to keep current password</small>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_password_confirmation">Confirm New Password</label>
                                    <input type="password" name="password_confirmation" id="edit_password_confirmation" class="form-control" minlength="8">
                                    <div class="invalid-feedback"></div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" onclick="updateUser()" class="btn btn-primary">
                        <i class="material-icons mr-1" style="font-size: 16px;">save</i>
                        Update User
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Change Role Modal -->
    <div class="modal fade" id="changeRoleModal" tabindex="-1" role="dialog" aria-labelledby="changeRoleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="changeRoleModalLabel">
                        <i class="material-icons mr-2">admin_panel_settings</i>
                        Change User Role
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="changeRoleForm">
                        @csrf
                        @method('PUT')
                        <input type="hidden" id="role_change_user_id" name="user_id">

                        <div class="form-group">
                            <label>Current User</label>
                            <p id="current_user_info" class="form-control-plaintext font-weight-medium"></p>
                        </div>

                        <div class="form-group">
                            <label for="new_role_id">New Role <span class="text-danger">*</span></label>
                            <select name="role_id" id="new_role_id" class="form-control" required>
                                <option value="">Select a role</option>
                                @foreach($roles as $role)
                                    <option value="{{ $role->id }}">{{ $role->display_name }}</option>
                                @endforeach
                            </select>
                            <div class="invalid-feedback"></div>
                            <small class="form-text text-muted">This will change the user's access permissions immediately.</small>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" onclick="saveRoleChange()" class="btn btn-primary">
                        <i class="material-icons mr-1" style="font-size: 16px;">save</i>
                        Change Role
                    </button>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('styles')
    <style>
        /* Table styling */
        .table th {
            border-top: none;
            font-weight: 600;
            color: #495057;
            background-color: #f8f9fa;
        }

        .table-responsive {
            border-radius: 0.375rem;
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
            line-height: 1.5;
            border-radius: 4px;
        }

        .btn-sm .material-icons {
            font-size: 16px !important;
        }

        /* Status badges */
        .status-badge {
            display: inline-flex;
            align-items: center;
            padding: 0.25rem 0.75rem;
            font-size: 0.75rem;
            font-weight: 500;
            line-height: 1;
            border-radius: 0.375rem;
        }

        .status-active {
            color: #155724;
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
        }

        .status-inactive {
            color: #721c24;
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
        }

        /* Loading state for stats cards */
        .stats-loading {
            opacity: 0.6;
        }

        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }

        .spinning {
            animation: spin 1s linear infinite;
        }
    </style>
@endpush

@push('scripts')
    <script>
        // Set global permission flags (with admin fallback)
        window.userCanEdit = @json(auth()->user()->hasPermission('warehouse.users.edit') || auth()->user()->role?->name === 'admin' || auth()->user()->role?->name === 'super_admin');
        window.userCanDelete = @json(auth()->user()->hasPermission('warehouse.users.delete') || auth()->user()->role?->name === 'admin' || auth()->user()->role?->name === 'super_admin');
        window.userCanManageRoles = @json(auth()->user()->hasPermission('warehouse.users.roles') || auth()->user()->role?->name === 'admin' || auth()->user()->role?->name === 'super_admin');

        // Debug: Log permission values
        console.log('Permission Debug:');
        console.log('- Can Edit:', window.userCanEdit);
        console.log('- Can Delete:', window.userCanDelete);
        console.log('- Can Manage Roles:', window.userCanManageRoles);
        console.log('- User Role:', @json(auth()->user()->role?->display_name ?? 'No Role'));

        let usersTable;
        let usersInitialized = false;

        function initializeUsersPage() {
            if (usersInitialized) {
                console.log('⚠️ Users page already initialized, skipping...');
                return;
            }

            console.log('🔧 Initializing users page...');
            initializeDataTable();
            loadUserStats();

            // Filter change handlers
            $('#role-filter, #status-filter').change(function() {
                if (usersTable) {
                    usersTable.draw();
                }
            });

            usersInitialized = true;
        }

        // Listen for the custom dataTablesReady event
        window.addEventListener('dataTablesReady', function() {
            console.log('🎉 Users: DataTables ready event received!');
            initializeUsersPage();
        });

        $(document).ready(function() {
            console.log('📄 Users page ready, checking if DataTables is available...');

            // Wait a bit then check if DataTables is available
            setTimeout(function() {
                if (typeof $ !== 'undefined' && typeof $.fn.DataTable !== 'undefined' && !usersInitialized) {
                    console.log('✅ Users: DataTables found on document ready, initializing...');
                    initializeUsersPage();
                } else if (!usersInitialized) {
                    console.log('⏳ Users: DataTables not ready yet, waiting for dataTablesReady event...');
                }
            }, 1000);
        });

        function initializeDataTable() {
            if (typeof $.fn.DataTable === 'undefined') {
                console.error('DataTables library not loaded');
                return;
            }

            usersTable = $('#users-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: '{{ route("warehouse.users.index") }}',
                    type: 'GET',
                    data: function(d) {
                        d.role_filter = $('#role-filter').val();
                        d.status_filter = $('#status-filter').val();
                    }
                },
                columns: [
                    { data: 'id', name: 'id' },
                    {
                        data: 'name',
                        name: 'name',
                        render: function(data, type, row) {
                            return `
                                <div class="d-flex align-items-center">
                                    <div class="mr-3">
                                        <div class="bg-primary text-white d-flex align-items-center justify-content-center rounded-circle" style="width: 40px; height: 40px;">
                                            <i class="material-icons" style="font-size: 20px;">person</i>
                                        </div>
                                    </div>
                                    <div>
                                        <div class="font-weight-medium">${data}</div>
                                        <small class="text-muted">ID: ${row.employee_id || 'N/A'}</small>
                                    </div>
                                </div>
                            `;
                        }
                    },
                    {
                        data: 'email',
                        name: 'email',
                        render: function(data, type, row) {
                            return `
                                <div>
                                    <div class="small">${data}</div>
                                    <small class="text-muted">Email</small>
                                </div>
                            `;
                        }
                    },
                    { data: 'department', name: 'department' },
                    {
                        data: 'role',
                        name: 'role',
                        render: function(data, type, row) {
                            return `<span class="badge badge-info">${data}</span>`;
                        }
                    },
                    {
                        data: 'status',
                        name: 'status',
                        render: function(data, type, row) {
                            const badgeClass = data === 'active' ? 'status-active' : 'status-inactive';
                            return `<span class="status-badge ${badgeClass}">${data.charAt(0).toUpperCase() + data.slice(1)}</span>`;
                        }
                    },
                    { data: 'last_login_at', name: 'last_login_at' },
                    {
                        data: null,
                        name: 'actions',
                        orderable: false,
                        searchable: false,
                        render: function(data, type, row) {
                            // Build dropdown menu items
                            let menuItems = [];

                            // Always show view option
                            menuItems.push(`
                                <a class="dropdown-item" href="javascript:void(0)" onclick="viewUser(${row.id})">
                                    <i class="material-icons mr-2" style="font-size: 16px;">visibility</i>
                                    View Details
                                </a>
                            `);

                            // Check edit permission
                            if (window.userCanEdit) {
                                menuItems.push(`
                                    <a class="dropdown-item" href="javascript:void(0)" onclick="editUser(${row.id})">
                                        <i class="material-icons mr-2" style="font-size: 16px;">edit</i>
                                        Edit User
                                    </a>
                                `);
                            }

                            // Role management section
                            if (window.userCanManageRoles) {
                                menuItems.push(`<div class="dropdown-divider"></div>`);
                                menuItems.push(`<h6 class="dropdown-header">Role Management</h6>`);
                                menuItems.push(`
                                    <a class="dropdown-item" href="javascript:void(0)" onclick="changeUserRole(${row.id})">
                                        <i class="material-icons mr-2" style="font-size: 16px;">admin_panel_settings</i>
                                        Change Role
                                    </a>
                                `);
                                menuItems.push(`
                                    <a class="dropdown-item" href="javascript:void(0)" onclick="viewUserPermissions(${row.id})">
                                        <i class="material-icons mr-2" style="font-size: 16px;">security</i>
                                        View Permissions
                                    </a>
                                `);
                                menuItems.push(`
                                    <a class="dropdown-item" href="javascript:void(0)" onclick="viewRoleHistory(${row.id})">
                                        <i class="material-icons mr-2" style="font-size: 16px;">history</i>
                                        Role History
                                    </a>
                                `);
                            }

                            // Add divider if we have actions above and delete below
                            if ((window.userCanEdit || window.userCanManageRoles) && window.userCanDelete) {
                                menuItems.push(`<div class="dropdown-divider"></div>`);
                            }

                            // Check delete permission
                            if (window.userCanDelete) {
                                menuItems.push(`
                                    <a class="dropdown-item text-danger" href="javascript:void(0)" onclick="deleteUser(${row.id})">
                                        <i class="material-icons mr-2" style="font-size: 16px;">delete</i>
                                        Delete User
                                    </a>
                                `);
                            }

                            // If no edit/delete/role permissions, show message
                            if (!window.userCanEdit && !window.userCanDelete && !window.userCanManageRoles) {
                                menuItems.push(`<div class="dropdown-divider"></div>`);
                                menuItems.push(`<span class="dropdown-item-text text-muted">Limited permissions</span>`);
                            }

                            return `
                                <div class="dropdown">
                                    <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" id="actionsDropdown${row.id}" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                        <i class="material-icons" style="font-size: 16px;">more_vert</i>
                                    </button>
                                    <div class="dropdown-menu dropdown-menu-right" aria-labelledby="actionsDropdown${row.id}">
                                        ${menuItems.join('')}
                                    </div>
                                </div>
                            `;
                        }
                    }
                ],
                order: [[0, 'desc']],
                pageLength: 25,
                lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
                language: {
                    processing: '<div class="text-center"><div class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></div></div>',
                    emptyTable: 'No users found',
                    zeroRecords: 'No matching users found'
                }
            });
        }

        function loadUserStats() {
            fetch('{{ route("warehouse.users.stats") }}')
                .then(response => response.json())
                .then(data => {
                    updateStatsCard('total-users-card', data.total_users, false);
                    updateStatsCard('active-users-card', data.active_users, false);
                    updateStatsCard('inactive-users-card', data.inactive_users, false);
                })
                .catch(error => {
                    console.error('Error loading user stats:', error);
                    updateStatsCard('total-users-card', '0', false);
                    updateStatsCard('active-users-card', '0', false);
                    updateStatsCard('inactive-users-card', '0', false);
                });
        }

        function updateStatsCard(cardId, value, loading) {
            const card = document.getElementById(cardId);
            if (!card) return;

            const valueElement = card.querySelector('.warehouse-stat-value h3');
            const loadingElement = card.querySelector('.spinner-border');
            const iconElement = card.querySelector('.material-icons');

            if (loading) {
                if (loadingElement) loadingElement.style.display = 'block';
                if (iconElement) iconElement.style.display = 'none';
            } else {
                if (loadingElement) loadingElement.style.display = 'none';
                if (iconElement) iconElement.style.display = 'block';
                if (valueElement) valueElement.textContent = value;
            }
        }

        function showAddUserModal() {
            $('#addUserForm')[0].reset();
            clearValidationErrors();
            $('#addUserModal').modal('show');
        }

        function saveUser() {
            const form = $('#addUserForm')[0];
            const formData = new FormData(form);

            clearValidationErrors();

            const saveBtn = $('button[onclick="saveUser()"]');
            const originalHtml = saveBtn.html();
            saveBtn.prop('disabled', true);
            saveBtn.html('<i class="material-icons mr-1 spinning" style="font-size: 16px;">sync</i>Creating...');

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            $.ajax({
                url: '{{ route("warehouse.users.store") }}',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        $('#addUserModal').modal('hide');
                        usersTable.draw();
                        loadUserStats();
                        showAlert('User created successfully!', 'success');
                    } else {
                        showAlert(response.message || 'Error creating user', 'error');
                    }
                },
                error: function(xhr) {
                    if (xhr.status === 422) {
                        const errors = xhr.responseJSON.errors;
                        displayValidationErrors(errors);
                    } else {
                        showAlert('Error creating user. Please try again.', 'error');
                    }
                },
                complete: function() {
                    saveBtn.prop('disabled', false);
                    saveBtn.html(originalHtml);
                }
            });
        }

        function editUser(userId) {
            fetch(`{{ url('warehouse/users') }}/${userId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const user = data.user;
                        $('#edit_user_id').val(user.id);
                        $('#edit_name').val(user.name);
                        $('#edit_email').val(user.email);
                        $('#edit_employee_id').val(user.employee_id);
                        $('#edit_phone').val(user.phone);
                        $('#edit_department').val(user.department);
                        $('#edit_role_id').val(user.role_id);
                        $('#edit_status').val(user.status);
                        $('#edit_password').val('');
                        $('#edit_password_confirmation').val('');

                        clearValidationErrors('edit');
                        $('#editUserModal').modal('show');
                    } else {
                        showAlert('Error loading user data', 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showAlert('Error loading user data', 'error');
                });
        }

        function updateUser() {
            const userId = $('#edit_user_id').val();
            const form = $('#editUserForm')[0];
            const formData = new FormData(form);

            clearValidationErrors('edit');

            const updateBtn = $('button[onclick="updateUser()"]');
            const originalHtml = updateBtn.html();
            updateBtn.prop('disabled', true);
            updateBtn.html('<i class="material-icons mr-1 spinning" style="font-size: 16px;">sync</i>Updating...');

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            $.ajax({
                url: `{{ url('warehouse/users') }}/${userId}`,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        $('#editUserModal').modal('hide');
                        usersTable.draw();
                        loadUserStats();
                        showAlert('User updated successfully!', 'success');
                    } else {
                        showAlert(response.message || 'Error updating user', 'error');
                    }
                },
                error: function(xhr) {
                    if (xhr.status === 422) {
                        const errors = xhr.responseJSON.errors;
                        displayValidationErrors(errors, 'edit');
                    } else {
                        showAlert('Error updating user. Please try again.', 'error');
                    }
                },
                complete: function() {
                    updateBtn.prop('disabled', false);
                    updateBtn.html(originalHtml);
                }
            });
        }

        function deleteUser(userId) {
            if (confirm('Are you sure you want to delete this user?')) {
                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });

                $.ajax({
                    url: `{{ url('warehouse/users') }}/${userId}`,
                    type: 'DELETE',
                    success: function(response) {
                        if (response.success) {
                            usersTable.draw();
                            loadUserStats();
                            showAlert('User deleted successfully', 'success');
                        } else {
                            showAlert(response.message, 'error');
                        }
                    },
                    error: function(xhr) {
                        showAlert('Error deleting user', 'error');
                    }
                });
            }
        }

        function viewUser(userId) {
            fetch(`{{ url('warehouse/users') }}/${userId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const user = data.user;
                        alert(`User Details:\n\nName: ${user.name}\nEmail: ${user.email}\nEmployee ID: ${user.employee_id || 'N/A'}\nDepartment: ${user.department}\nRole: ${user.role.display_name}\nStatus: ${user.status}`);
                    } else {
                        showAlert('Error loading user data', 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showAlert('Error loading user data', 'error');
                });
        }

        function clearValidationErrors(prefix = '') {
            const formPrefix = prefix ? `${prefix}_` : '';
            $(`.form-control`).removeClass('is-invalid');
            $(`.invalid-feedback`).text('');
        }

        function displayValidationErrors(errors, prefix = '') {
            const formPrefix = prefix ? `${prefix}_` : '';

            $.each(errors, function(field, messages) {
                const input = $(`[name="${field}"], #${formPrefix}${field}`);
                input.addClass('is-invalid');
                input.siblings('.invalid-feedback').text(messages[0]);
            });
        }

        function changeUserRole(userId) {
            fetch(`{{ url('warehouse/users') }}/${userId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const user = data.user;
                        $('#role_change_user_id').val(user.id);
                        $('#current_user_info').text(`${user.name} (${user.email})`);
                        $('#new_role_id').val(user.role_id);

                        clearValidationErrors('role');
                        $('#changeRoleModal').modal('show');
                    } else {
                        showAlert('Error loading user data', 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showAlert('Error loading user data', 'error');
                });
        }

        function saveRoleChange() {
            const userId = $('#role_change_user_id').val();
            const form = $('#changeRoleForm')[0];
            const formData = new FormData(form);

            clearValidationErrors('role');

            const saveBtn = $('button[onclick="saveRoleChange()"]');
            const originalHtml = saveBtn.html();
            saveBtn.prop('disabled', true);
            saveBtn.html('<i class="material-icons mr-1 spinning" style="font-size: 16px;">sync</i>Changing...');

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            $.ajax({
                url: `{{ url('warehouse/users') }}/${userId}/role`,
                type: 'PUT',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        $('#changeRoleModal').modal('hide');
                        usersTable.draw();
                        loadUserStats();
                        showAlert('User role changed successfully!', 'success');
                    } else {
                        showAlert(response.message || 'Error changing user role', 'error');
                    }
                },
                error: function(xhr) {
                    if (xhr.status === 422) {
                        const errors = xhr.responseJSON.errors;
                        displayValidationErrors(errors, 'role');
                    } else {
                        showAlert('Error changing user role. Please try again.', 'error');
                    }
                },
                complete: function() {
                    saveBtn.prop('disabled', false);
                    saveBtn.html(originalHtml);
                }
            });
        }

        function viewUserPermissions(userId) {
            fetch(`{{ url('warehouse/users') }}/${userId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const user = data.user;
                        const role = user.role;

                        let permissionsHtml = `
                            <div class="mb-3">
                                <strong>User:</strong> ${user.name}<br>
                                <strong>Role:</strong> ${role ? role.display_name : 'No Role'}<br>
                                <strong>Status:</strong> <span class="badge badge-${user.status === 'active' ? 'success' : 'warning'}">${user.status}</span>
                            </div>
                        `;

                        if (role && role.permissions && role.permissions.length > 0) {
                            const permissionGroups = {};
                            role.permissions.forEach(permission => {
                                const group = permission.group || 'general';
                                if (!permissionGroups[group]) {
                                    permissionGroups[group] = [];
                                }
                                permissionGroups[group].push(permission);
                            });

                            permissionsHtml += '<h6>Current Permissions:</h6>';
                            Object.keys(permissionGroups).forEach(group => {
                                permissionsHtml += `<h6 class="text-primary mt-3">${group.replace('_', ' ').toUpperCase()}</h6>`;
                                permissionsHtml += '<ul class="list-unstyled ml-3">';
                                permissionGroups[group].forEach(permission => {
                                    permissionsHtml += `<li><i class="material-icons text-success mr-1" style="font-size: 16px;">check_circle</i> ${permission.display_name}</li>`;
                                });
                                permissionsHtml += '</ul>';
                            });
                        } else {
                            permissionsHtml += '<p class="text-muted">This user has no specific permissions assigned.</p>';
                        }

                        // Create modal
                        const modalHtml = `
                            <div class="modal fade" id="permissionsModal" tabindex="-1" role="dialog">
                                <div class="modal-dialog modal-lg" role="document">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title">
                                                <i class="material-icons mr-2">security</i>
                                                User Permissions
                                            </h5>
                                            <button type="button" class="close" data-dismiss="modal">&times;</button>
                                        </div>
                                        <div class="modal-body">
                                            ${permissionsHtml}
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `;

                        // Remove existing modal if present
                        $('#permissionsModal').remove();

                        // Add and show modal
                        $('body').append(modalHtml);
                        $('#permissionsModal').modal('show');

                    } else {
                        showAlert('Error loading user permissions', 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showAlert('Error loading user permissions', 'error');
                });
        }

        function viewRoleHistory(userId) {
            // Create a simple role history modal (placeholder implementation)
            const modalHtml = `
                <div class="modal fade" id="roleHistoryModal" tabindex="-1" role="dialog">
                    <div class="modal-dialog modal-lg" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">
                                    <i class="material-icons mr-2">history</i>
                                    Role Change History
                                </h5>
                                <button type="button" class="close" data-dismiss="modal">&times;</button>
                            </div>
                            <div class="modal-body">
                                <div class="text-center py-4">
                                    <i class="material-icons text-muted mb-3" style="font-size: 48px;">history</i>
                                    <h6>Role History Feature</h6>
                                    <p class="text-muted">Role change tracking will be available in a future update.<br>
                                    This feature will show when and by whom user roles were changed.</p>
                                    <div class="alert alert-info">
                                        <strong>Coming Soon:</strong>
                                        <ul class="text-left mt-2 mb-0">
                                            <li>Role change timestamps</li>
                                            <li>Previous and new role details</li>
                                            <li>Admin who made the change</li>
                                            <li>Change reason/notes</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            `;

            // Remove existing modal if present
            $('#roleHistoryModal').remove();

            // Add and show modal
            $('body').append(modalHtml);
            $('#roleHistoryModal').modal('show');
        }

        function showAlert(message, type) {
            const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
            const alert = `
                <div class="alert ${alertClass} alert-dismissible fade show position-fixed" style="top: 20px; right: 20px; z-index: 9999;">
                    ${message}
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                </div>
            `;
            $('body').append(alert);
            setTimeout(() => $('.alert').alert('close'), 5000);
        }
    </script>
@endpush