<!-- Create User Modal -->
<div class="modal fade" id="createUserModal" tabindex="-1" role="dialog" aria-labelledby="createUserModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createUserModalLabel">Create New User</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form id="createUserForm">
                @csrf
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="create_first_name">First Name *</label>
                                <input type="text" class="form-control" id="create_first_name" name="first_name" required>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="create_last_name">Last Name *</label>
                                <input type="text" class="form-control" id="create_last_name" name="last_name" required>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="create_email">Email Address *</label>
                                <input type="email" class="form-control" id="create_email" name="email" required>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="create_phone">Phone Number</label>
                                <input type="text" class="form-control" id="create_phone" name="phone">
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="create_employee_id">Employee ID</label>
                                <input type="text" class="form-control" id="create_employee_id" name="employee_id" placeholder="Auto-generated if empty">
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="create_role_id">Role *</label>
                                <select class="form-control" id="create_role_id" name="role_id" required>
                                    <option value="">Select Role</option>
                                    @foreach($roles as $role)
                                        <option value="{{ $role->id }}">{{ $role->display_name }}</option>
                                    @endforeach
                                </select>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="create_status">Status *</label>
                                <select class="form-control" id="create_status" name="status" required>
                                    <option value="active">Active</option>
                                    <option value="inactive">Inactive</option>
                                    <option value="suspended">Suspended</option>
                                </select>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="alert alert-info">
                        <i class="material-icons mr-2">info</i>
                        A temporary password will be generated and displayed after user creation. The user will be required to set a new password on their first login.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="material-icons mr-2">person_add</i>
                        Create User
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.getElementById('createUserForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const form = this;
    const submitBtn = form.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    
    // Clear previous errors
    form.querySelectorAll('.is-invalid').forEach(el => el.classList.remove('is-invalid'));
    form.querySelectorAll('.invalid-feedback').forEach(el => el.textContent = '');
    
    // Show loading state
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="material-icons mr-2">hourglass_empty</i> Creating...';
    
    // Submit form
    fetch('{{ route("admin.users.store") }}', {
        method: 'POST',
        body: new FormData(form),
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
            'Accept': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Show success message with temporary password
            showToastMessage(data.message, 'success');
            
            // Reset button state immediately
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
            
            // Close create modal first (using jQuery for Bootstrap 4)
            if (typeof $ !== 'undefined') {
                $('#createUserModal').modal('hide');
            } else {
                // Fallback if jQuery not available
                const modal = document.getElementById('createUserModal');
                modal.classList.remove('show');
                modal.style.display = 'none';
                document.body.classList.remove('modal-open');
                const backdrop = document.querySelector('.modal-backdrop');
                if (backdrop) backdrop.remove();
            }
            
            // Wait a moment for modal to close, then show password modal
            setTimeout(() => {
                showPasswordModal(data.temp_password, data.user);
            }, 500);
        } else {
            // Handle validation errors
            if (data.errors) {
                Object.keys(data.errors).forEach(field => {
                    const input = form.querySelector(`[name="${field}"]`);
                    if (input) {
                        input.classList.add('is-invalid');
                        const feedback = input.nextElementSibling;
                        if (feedback && feedback.classList.contains('invalid-feedback')) {
                            feedback.textContent = data.errors[field][0];
                        }
                    }
                });
            } else {
                showToastMessage(data.message || 'An error occurred', 'error');
            }
            // Reset button state for error cases
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToastMessage('An error occurred while creating the user', 'error');
        // Reset button state for error cases
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
    });
});

// Reset form when modal is closed (using jQuery for Bootstrap 4)
if (typeof $ !== 'undefined') {
    $('#createUserModal').on('hidden.bs.modal', function() {
        document.getElementById('createUserForm').reset();
        this.querySelectorAll('.is-invalid').forEach(el => el.classList.remove('is-invalid'));
        this.querySelectorAll('.invalid-feedback').forEach(el => el.textContent = '');
    });
}

// Function to show password in a modal
function showPasswordModal(tempPassword, user) {
    // Create a modal dynamically to show the password
    const modalHtml = `
        <div class="modal fade" id="passwordModal" tabindex="-1" role="dialog" aria-labelledby="passwordModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
                <div class="modal-content border-0 shadow">
                    <div class="modal-header bg-success text-white">
                        <h5 class="modal-title" id="passwordModalLabel">
                            <i class="material-icons mr-2">check_circle</i>
                            User Created Successfully!
                        </h5>
                        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="text-center mb-4">
                            <div class="bg-success-light d-flex align-items-center justify-content-center rounded-circle mx-auto mb-3" style="width: 80px; height: 80px; background-color: rgba(40, 167, 69, 0.1);">
                                <i class="material-icons text-success" style="font-size: 48px;">person_add</i>
                            </div>
                            <h5 class="mb-3">User account has been created</h5>
                        </div>
                        
                        <div class="alert alert-warning">
                            <div class="d-flex align-items-start">
                                <i class="material-icons mr-2 text-warning">warning</i>
                                <div>
                                    <strong>Important:</strong> Please securely provide the following temporary password to the user. They will be required to change it on their first login.
                                </div>
                            </div>
                        </div>
                        
                        <div class="card border-primary">
                            <div class="card-body">
                                <div class="form-group mb-3">
                                    <label class="text-muted small">User Email:</label>
                                    <div class="font-weight-bold">${user ? user.email : ''}</div>
                                </div>
                                <div class="form-group mb-0">
                                    <label class="text-muted small">Temporary Password:</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control font-weight-bold" value="${tempPassword}" readonly id="tempPasswordField">
                                        <div class="input-group-append">
                                            <button class="btn btn-outline-secondary" type="button" onclick="copyPassword()">
                                                <i class="material-icons">content_copy</i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" onclick="closePasswordModalAndReload()">
                            <i class="material-icons mr-2">check</i>
                            I've Saved the Password
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Remove any existing password modal
    const existingModal = document.getElementById('passwordModal');
    if (existingModal) {
        existingModal.remove();
    }
    
    // Add the new modal to the body
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    // Show the modal (using jQuery for Bootstrap 4)
    if (typeof $ !== 'undefined') {
        $('#passwordModal').modal('show');
    } else {
        // Fallback if jQuery not available
        const modal = document.getElementById('passwordModal');
        modal.classList.add('show');
        modal.style.display = 'block';
        document.body.classList.add('modal-open');
        const backdrop = document.createElement('div');
        backdrop.className = 'modal-backdrop fade show';
        document.body.appendChild(backdrop);
    }
}

// Function to copy password to clipboard
function copyPassword() {
    const passwordField = document.getElementById('tempPasswordField');
    passwordField.select();
    document.execCommand('copy');
    showToastMessage('Password copied to clipboard!', 'success');
}

// Function to close password modal and reload page
function closePasswordModalAndReload() {
    // Close modal using jQuery for Bootstrap 4
    if (typeof $ !== 'undefined') {
        $('#passwordModal').modal('hide');
        // Wait for modal to fully close then reload
        $('#passwordModal').on('hidden.bs.modal', function () {
            location.reload();
        });
    } else {
        // Fallback if jQuery not available
        const modal = document.getElementById('passwordModal');
        if (modal) {
            modal.classList.remove('show');
            modal.style.display = 'none';
            // Remove the modal backdrop
            const backdrop = document.querySelector('.modal-backdrop');
            if (backdrop) {
                backdrop.remove();
            }
            // Remove overflow hidden from body
            document.body.classList.remove('modal-open');
            document.body.style.removeProperty('overflow');
            document.body.style.removeProperty('padding-right');
        }
        // Reload the page
        setTimeout(() => location.reload(), 100);
    }
}
</script>