@extends('layouts.app')

@section('content')
<div class="container-fluid">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card shadow-lg border-0">
                <div class="card-header bg-primary text-white">
                    <h3 class="mb-0">
                        <i class="fas fa-user-plus me-2"></i>
                        {{ __('roles.create_new_user_with_role') }}
                    </h3>
                    <p class="mb-0 opacity-75">{{ __('roles.streamlined_user_creation') }}</p>
                </div>
                
                <div class="card-body p-4">
                    @if(session('success'))
                        <div class="alert alert-success border-0 shadow-sm">
                            <i class="fas fa-check-circle me-2"></i>
                            {{ session('success') }}
                        </div>
                    @endif

                    @if($errors->any())
                        <div class="alert alert-danger border-0 shadow-sm">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            <strong>{{ __('roles.please_fix_errors') }}:</strong>
                            <ul class="mb-0 mt-2">
                                @foreach($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif

                    <form method="POST" action="{{ route('roles.store_with_user') }}" id="userCreationForm">
                        @csrf
                        
                        <!-- User Information Section -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <h5 class="border-bottom pb-2 mb-3">
                                    <i class="fas fa-user me-2 text-primary"></i>
                                    {{ __('roles.user_information') }}
                                </h5>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label class="form-label fw-semibold">
                                        <i class="fas fa-user me-1"></i>
                                        {{ __('roles.full_name') }}
                                    </label>
                                    <input type="text" name="user_name" 
                                           class="form-control form-control-lg" 
                                           placeholder="{{ __('roles.enter_full_name') }}"
                                           value="{{ old('user_name') }}" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label class="form-label fw-semibold">
                                        <i class="fas fa-envelope me-1"></i>
                                        {{ __('roles.email_address') }}
                                    </label>
                                    <input type="email" name="user_email" 
                                           class="form-control form-control-lg" 
                                           placeholder="{{ __('roles.enter_email') }}"
                                           value="{{ old('user_email') }}" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label class="form-label fw-semibold">
                                        <i class="fas fa-lock me-1"></i>
                                        {{ __('roles.password') }}
                                    </label>
                                    <input type="password" name="user_password" 
                                           class="form-control form-control-lg" 
                                           placeholder="{{ __('roles.enter_password') }}" required>
                                </div>
                            </div>
                        </div>

                        <!-- Role Assignment Section -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <h5 class="border-bottom pb-2 mb-3">
                                    <i class="fas fa-shield-alt me-2 text-primary"></i>
                                    {{ __('roles.role_assignment') }}
                                </h5>
                                
                                <div class="row">
                                    <!-- Option 1: Use Existing Role -->
                                    <div class="col-md-6">
                                        <div class="card h-100 option-card" data-option="existing_role">
                                            <div class="card-body text-center">
                                                <div class="form-check mb-3">
                                                    <input class="form-check-input" type="radio" 
                                                           name="user_type" value="existing_role" 
                                                           id="existing_role_option">
                                                    <label class="form-check-label fw-bold" for="existing_role_option">
                                                        <i class="fas fa-users text-success fa-2x d-block mb-2"></i>
                                                        {{ __('roles.use_existing_role') }}
                                                    </label>
                                                </div>
                                                <p class="text-muted small mb-3">
                                                    {{ __('roles.user_inherits_all_permissions') }}
                                                </p>
                                                
                                                <div class="existing-role-section" style="display: none;">
                                                    <select name="existing_role_id" class="form-select">
                                                        <option value="">{{ __('roles.select_role') }}</option>
                                                        @foreach($existingRoles as $role)
                                                            <option value="{{ $role->id }}" 
                                                                    {{ old('existing_role_id') == $role->id ? 'selected' : '' }}>
                                                                {{ $role->name }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Option 2: Create New Role -->
                                    <div class="col-md-6">
                                        <div class="card h-100 option-card" data-option="new_role">
                                            <div class="card-body text-center">
                                                <div class="form-check mb-3">
                                                    <input class="form-check-input" type="radio" 
                                                           name="user_type" value="new_role" 
                                                           id="new_role_option">
                                                    <label class="form-check-label fw-bold" for="new_role_option">
                                                        <i class="fas fa-plus-circle text-primary fa-2x d-block mb-2"></i>
                                                        {{ __('roles.create_new_role') }}
                                                    </label>
                                                </div>
                                                <p class="text-muted small mb-3">
                                                    {{ __('roles.custom_role_with_selected_permissions') }}
                                                </p>
                                                
                                                <div class="new-role-section" style="display: none;">
                                                    <input type="text" name="role_name" 
                                                           class="form-control mb-3" 
                                                           placeholder="{{ __('roles.enter_role_name') }}"
                                                           value="{{ old('role_name') }}">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Permission Groups Section (Only for New Role) -->
                        <div class="permission-groups-section" style="display: none;">
                            <div class="row mb-4">
                                <div class="col-12">
                                    <h5 class="border-bottom pb-2 mb-3">
                                        <i class="fas fa-key me-2 text-primary"></i>
                                        {{ __('roles.permission_groups') }}
                                    </h5>
                                    <p class="text-muted mb-3">
                                        <i class="fas fa-info-circle me-1"></i>
                                        {{ __('roles.select_permission_groups_explanation') }}
                                    </p>
                                    
                                    <div class="row">
                                        @foreach($permissionGroups as $group)
                                            <div class="col-md-4 col-sm-6 mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" 
                                                           name="permission_groups[]" value="{{ $group }}" 
                                                           id="group_{{ $loop->index }}"
                                                           {{ in_array($group, old('permission_groups', [])) ? 'checked' : '' }}>
                                                    <label class="form-check-label fw-semibold" for="group_{{ $loop->index }}">
                                                        <i class="fas fa-folder me-1 text-warning"></i>
                                                        {{ ucfirst(str_replace('_', ' ', $group)) }}
                                                    </label>
                                                </div>
                                            </div>
                                        @endforeach
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Form Actions -->
                        <div class="d-flex justify-content-between align-items-center">
                            <a href="{{ route('users.index') }}" class="btn btn-outline-secondary">
                                <i class="fas fa-arrow-left me-1"></i>
                                {{ __('roles.back_to_users') }}
                            </a>
                            
                            <button type="submit" class="btn btn-primary btn-lg px-4">
                                <i class="fas fa-user-plus me-2"></i>
                                {{ __('roles.create_user') }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.option-card {
    border: 2px solid #e9ecef;
    transition: all 0.3s ease;
    cursor: pointer;
}

.option-card:hover {
    border-color: #007bff;
    box-shadow: 0 4px 8px rgba(0,123,255,0.1);
}

.option-card.active {
    border-color: #007bff;
    background-color: #f8f9ff;
}

.form-check-input:checked ~ .form-check-label {
    color: #007bff;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const userTypeRadios = document.querySelectorAll('input[name="user_type"]');
    const existingRoleSection = document.querySelector('.existing-role-section');
    const newRoleSection = document.querySelector('.new-role-section');
    const permissionGroupsSection = document.querySelector('.permission-groups-section');
    const optionCards = document.querySelectorAll('.option-card');
    
    // Handle radio button changes
    userTypeRadios.forEach(radio => {
        radio.addEventListener('change', function() {
            // Update card states
            optionCards.forEach(card => {
                card.classList.remove('active');
                if (card.dataset.option === this.value) {
                    card.classList.add('active');
                }
            });
            
            // Show/hide relevant sections
            if (this.value === 'existing_role') {
                existingRoleSection.style.display = 'block';
                newRoleSection.style.display = 'none';
                permissionGroupsSection.style.display = 'none';
                
                // Make existing role selection required and clear new role fields
                document.querySelector('select[name="existing_role_id"]').required = true;
                document.querySelector('input[name="role_name"]').required = false;
                document.querySelector('input[name="role_name"]').value = '';
                
                // Clear permission groups
                document.querySelectorAll('input[name="permission_groups[]"]').forEach(checkbox => {
                    checkbox.checked = false;
                });
                
            } else if (this.value === 'new_role') {
                existingRoleSection.style.display = 'none';
                newRoleSection.style.display = 'block';
                permissionGroupsSection.style.display = 'block';
                
                // Make new role inputs required and clear existing role selection
                document.querySelector('select[name="existing_role_id"]').required = false;
                document.querySelector('select[name="existing_role_id"]').value = '';
                document.querySelector('input[name="role_name"]').required = true;
            }
        });
    });
    
    // Handle card clicks
    optionCards.forEach(card => {
        card.addEventListener('click', function() {
            const radio = document.getElementById(this.dataset.option + '_option');
            if (radio) {
                radio.checked = true;
                radio.dispatchEvent(new Event('change'));
            }
        });
    });
    
    // Restore state if there are old values
    const oldUserType = '{{ old("user_type") }}';
    if (oldUserType) {
        const radio = document.querySelector(`input[name="user_type"][value="${oldUserType}"]`);
        if (radio) {
            radio.checked = true;
            radio.dispatchEvent(new Event('change'));
        }
    }
    
    // Form validation and cleanup
    document.getElementById('userCreationForm').addEventListener('submit', function(e) {
        const userType = document.querySelector('input[name="user_type"]:checked');
        
        if (!userType) {
            e.preventDefault();
            alert('{{ __("roles.please_select_user_type") }}');
            return false;
        }
        
        // Clean up form fields based on user type
        if (userType.value === 'existing_role') {
            const existingRoleId = document.querySelector('select[name="existing_role_id"]').value;
            if (!existingRoleId) {
                e.preventDefault();
                alert('{{ __("roles.please_select_existing_role") }}');
                return false;
            }
            
            // Disable new role fields so they don't get submitted
            document.querySelector('input[name="role_name"]').disabled = true;
            document.querySelectorAll('input[name="permission_groups[]"]').forEach(checkbox => {
                checkbox.disabled = true;
            });
            
        } else if (userType.value === 'new_role') {
            const roleName = document.querySelector('input[name="role_name"]').value;
            const permissionGroups = document.querySelectorAll('input[name="permission_groups[]"]:checked');
            
            if (!roleName.trim()) {
                e.preventDefault();
                alert('{{ __("roles.please_enter_role_name") }}');
                return false;
            }
            
            if (permissionGroups.length === 0) {
                e.preventDefault();
                alert('{{ __("roles.please_select_permission_groups") }}');
                return false;
            }
            
            // Disable existing role field so it doesn't get submitted
            document.querySelector('select[name="existing_role_id"]').disabled = true;
        }
        
        return true;
    });
});
</script>
@endsection