@extends('admin-layouts.master')

@section('title', 'Edit User - ' . $user->name)

@section('content')
<style>
.card {
    border-radius: 8px;
    transition: all 0.3s ease;
}

.form-control {
    border-radius: 6px;
    border: 1px solid #e3e6f0;
}

.form-control:focus {
    border-color: #4e73df;
    box-shadow: 0 0 0 0.2rem rgba(78, 115, 223, 0.25);
}

.custom-control-label {
    cursor: pointer;
}

.custom-control-input:checked ~ .custom-control-label::before {
    background-color: #4e73df;
    border-color: #4e73df;
}

.custom-control-input:disabled ~ .custom-control-label {
    color: #6c757d;
    cursor: not-allowed;
}

.role-icon {
    flex-shrink: 0;
}

.user-avatar {
    flex-shrink: 0;
}

.badge {
    font-size: 0.75rem;
    font-weight: 500;
}

.badge-sm {
    font-size: 0.65rem;
    padding: 0.25rem 0.5rem;
}

.form-label {
    font-size: 0.85rem;
    margin-bottom: 0.25rem;
}

.alert {
    border-radius: 6px;
}

.input-group .form-control {
    border-radius: 6px 0 0 6px;
}

.progress-bar {
    transition: width 0.3s ease;
}

.progress-bar.bg-danger {
    background-color: #dc3545 !important;
}

.progress-bar.bg-warning {
    background-color: #ffc107 !important;
}

.progress-bar.bg-info {
    background-color: #17a2b8 !important;
}

.progress-bar.bg-success {
    background-color: #28a745 !important;
}

.role-item {
    background-color: #e7f1ff;
    color: #004085;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 0.75rem;
    margin: 2px;
    display: inline-block;
}

.modal-content {
    border-radius: 8px;
}

.changes-section {
    border-left: 3px solid #007bff;
    padding-left: 15px;
    margin-bottom: 20px;
}

.changes-section.added {
    border-color: #28a745;
}

.changes-section.removed {
    border-color: #dc3545;
}

.changes-section.modified {
    border-color: #ffc107;
}
</style>
<div class="container-fluid">
    <!-- Header Section -->
    <div class="row mb-4">
        <div class="col-md-12">
            <div class="d-flex justify-content-between align-items-center">
                <div class="d-flex align-items-center">
                    <!-- User Avatar -->
                    <div class="user-avatar mr-3">
                        @php
                            $avatarConfig = match(true) {
                                $user->hasRole('superadmin') => ['bg' => 'bg-danger', 'icon' => 'fa-crown'],
                                $user->hasRole('supervisor') => ['bg' => 'bg-warning', 'icon' => 'fa-user-tie'],
                                $user->hasRole('staff') => ['bg' => 'bg-info', 'icon' => 'fa-user-edit'],
                                $user->hasRole('administrator') => ['bg' => 'bg-success', 'icon' => 'fa-user-cog'],
                                $user->hasRole('guest') => ['bg' => 'bg-secondary', 'icon' => 'fa-user-clock'],
                                default => ['bg' => 'bg-secondary', 'icon' => 'fa-user']
                            };
                        @endphp
                        <div class="{{ $avatarConfig['bg'] }} rounded-circle d-flex align-items-center justify-content-center" style="width: 50px; height: 50px;">
                            <i class="fas {{ $avatarConfig['icon'] }} text-white fa-lg"></i>
                        </div>
                    </div>
                    <div>
                        <h2 class="mb-1 text-dark font-weight-bold">Edit User</h2>
                        <p class="text-muted mb-0">Modify user information and role assignments for {{ $user->name }}</p>
                    </div>
                </div>
                <div>
                    @can('user.view')
                    <a href="{{ route('users.show', $user) }}" class="btn btn-light btn-sm shadow-sm mr-2">
                        <i class="fas fa-eye mr-1"></i> View Details
                    </a>
                    @endcan
                    <a href="{{ route('users.index') }}" class="btn btn-light btn-sm shadow-sm">
                        <i class="fas fa-arrow-left mr-1"></i> Back to Users
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Alert Messages -->
    @if(session('success'))
    <div class="row mb-3">
        <div class="col-md-12">
            <div class="alert alert-success alert-dismissible fade show shadow-sm border-0" role="alert">
                <i class="fas fa-check-circle mr-2"></i>
                {{ session('success') }}
                <button type="button" class="close" data-dismiss="alert">
                    <span>&times;</span>
                </button>
            </div>
        </div>
    </div>
    @endif

    @if(session('error'))
    <div class="row mb-3">
        <div class="col-md-12">
            <div class="alert alert-danger alert-dismissible fade show shadow-sm border-0" role="alert">
                <i class="fas fa-exclamation-circle mr-2"></i>
                {{ session('error') }}
                <button type="button" class="close" data-dismiss="alert">
                    <span>&times;</span>
                </button>
            </div>
        </div>
    </div>
    @endif

    @if($errors->any())
    <div class="row mb-3">
        <div class="col-md-12">
            <div class="alert alert-danger alert-dismissible fade show shadow-sm border-0" role="alert">
                <i class="fas fa-exclamation-circle mr-2"></i>
                <strong>Please fix the following errors:</strong>
                <ul class="mb-0 mt-2">
                    @foreach($errors->all() as $error)
                    <li>{{ $error }}</li>
                    @endforeach
                </ul>
                <button type="button" class="close" data-dismiss="alert">
                    <span>&times;</span>
                </button>
            </div>
        </div>
    </div>
    @endif

    <form action="{{ route('users.update', $user) }}" method="POST" enctype="multipart/form-data" id="userForm">
        @csrf
        @method('PUT')
        <div class="row">
            <!-- User Information Card -->
            <div class="col-md-8 mb-4">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-white border-bottom-0 py-3">
                        <h6 class="mb-0 text-dark font-weight-semibold">
                            <i class="fas fa-user text-primary mr-2"></i>
                            User Information
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <!-- Username -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="username" class="form-label font-weight-semibold">Username <span class="text-danger">*</span></label>
                                    @if($user->hasRole('superadmin') && $user->id === auth()->id())
                                    <input type="hidden" name="username" value="{{ $user->username }}">
                                    <input type="text"
                                           class="form-control"
                                           value="{{ $user->username }}"
                                           disabled>
                                    <small class="form-text text-warning">
                                        <i class="fas fa-lock mr-1"></i>
                                        You cannot change your own username
                                    </small>
                                    @else
                                    <input type="text"
                                           class="form-control @error('username') is-invalid @enderror"
                                           id="username"
                                           name="username"
                                           value="{{ old('username', $user->username) }}"
                                           placeholder="Enter username"
                                           required>
                                    <small class="form-text text-muted">Unique identifier for login</small>
                                    @error('username')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                    @endif
                                </div>
                            </div>

                            <!-- Full Name -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="name" class="form-label font-weight-semibold">Full Name <span class="text-danger">*</span></label>
                                    <input type="text"
                                           class="form-control @error('name') is-invalid @enderror"
                                           id="name"
                                           name="name"
                                           value="{{ old('name', $user->name) }}"
                                           placeholder="Enter full name"
                                           required>
                                    @error('name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <!-- Email -->
                        <div class="form-group">
                            <label for="email" class="form-label font-weight-semibold">Email Address <span class="text-danger">*</span></label>
                            <input type="email"
                                   class="form-control @error('email') is-invalid @enderror"
                                   id="email"
                                   name="email"
                                   value="{{ old('email', $user->email) }}"
                                   placeholder="Enter email address"
                                   required>
                            <small class="form-text text-muted">Will be used for login and notifications</small>
                            @if($user->email_verified_at)
                                <small class="form-text text-success">
                                    <i class="fas fa-check mr-1"></i>
                                    Email verified {{ $user->email_verified_at->diffForHumans() }}
                                </small>
                            @else
                                <small class="form-text text-warning">
                                    <i class="fas fa-clock mr-1"></i>
                                    Email not verified
                                </small>
                            @endif
                            @error('email')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <!-- Password Section -->
                        <div class="bg-light rounded p-3 mb-3">
                            <h6 class="mb-3 text-dark">
                                <i class="fas fa-key mr-2"></i>
                                Change Password (Optional)
                            </h6>
                            <div class="row">
                                <!-- New Password -->
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="password" class="form-label font-weight-semibold">New Password</label>
                                        <div class="input-group">
                                            <input type="password"
                                                   class="form-control @error('password') is-invalid @enderror"
                                                   id="password"
                                                   name="password"
                                                   placeholder="Leave blank to keep current">
                                            <div class="input-group-append">
                                                <button class="btn btn-outline-secondary" type="button" id="togglePassword">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                            </div>
                                            @error('password')
                                                <div class="invalid-feedback">{{ $message }}</div>
                                            @enderror
                                        </div>
                                        <small class="form-text text-muted">Minimum 8 characters</small>
                                    </div>
                                </div>

                                <!-- Confirm Password -->
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="password_confirmation" class="form-label font-weight-semibold">Confirm New Password</label>
                                        <div class="input-group">
                                            <input type="password"
                                                   class="form-control"
                                                   id="password_confirmation"
                                                   name="password_confirmation"
                                                   placeholder="Confirm new password">
                                            <div class="input-group-append">
                                                <button class="btn btn-outline-secondary" type="button" id="togglePasswordConfirm">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Password Strength Indicator -->
                            <div class="form-group mb-0" id="passwordStrengthContainer" style="display: none;">
                                <div class="progress" style="height: 5px;">
                                    <div class="progress-bar" id="passwordStrength" role="progressbar" style="width: 0%"></div>
                                </div>
                                <small class="form-text" id="passwordStrengthText">Password strength will appear here</small>
                            </div>
                        </div>

                        <!-- Profile Photo -->
                        <div class="form-group">
                            <label for="profile_photo" class="form-label font-weight-semibold">Profile Photo</label>
                            @if($user->profile_photo)
                            <div class="mb-2">
                                <img src="{{ asset('storage/' . $user->profile_photo) }}" alt="Current Photo" class="img-thumbnail" style="max-width: 150px;">
                            </div>
                            @endif
                            <div class="custom-file">
                                <input type="file"
                                       class="custom-file-input @error('profile_photo') is-invalid @enderror"
                                       id="profile_photo"
                                       name="profile_photo"
                                       accept="image/jpeg,image/png,image/jpg">
                                <label class="custom-file-label" for="profile_photo">Choose new file</label>
                                @error('profile_photo')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                            <small class="form-text text-muted">Max 2MB (JPEG, PNG, JPG)</small>

                            <!-- Image Preview -->
                            <div id="imagePreview" class="mt-3" style="display: none;">
                                <img id="preview" src="" alt="Preview" class="img-thumbnail" style="max-width: 200px;">
                            </div>
                        </div>

                        <!-- Account Info -->
                        <div class="row text-center bg-light rounded p-3">
                            <div class="col-md-4">
                                <h6 class="mb-1 text-primary">{{ $user->created_at->format('M d, Y') }}</h6>
                                <small class="text-muted">Account Created</small>
                            </div>
                            <div class="col-md-4">
                                <h6 class="mb-1 text-info">{{ $user->roles->count() }}</h6>
                                <small class="text-muted">Current Roles</small>
                            </div>
                            <div class="col-md-4">
                                <h6 class="mb-1 text-success">{{ $user->email_verified_at ? 'Verified' : 'Pending' }}</h6>
                                <small class="text-muted">Email Status</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Roles Assignment Card -->
            <div class="col-md-4 mb-4">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-header bg-white border-bottom-0 py-3">
                        <h6 class="mb-0 text-dark font-weight-semibold">
                            <i class="fas fa-user-tag text-primary mr-2"></i>
                            Manage Roles
                        </h6>
                    </div>
                    <div class="card-body">
                        @if($roles->count() > 0)
                        <!-- Primary Role -->
                        <div class="form-group">
                            <label for="primary_role_id" class="form-label font-weight-semibold">Primary Role <span class="text-danger">*</span></label>
                            <select class="form-control @error('primary_role_id') is-invalid @enderror"
                                    id="primary_role_id"
                                    name="primary_role_id"
                                    required>
                                <option value="">Select Primary Role</option>
                                @foreach($roles as $role)
                                <option value="{{ $role->id }}"
                                        {{ old('primary_role_id', $user->primary_role_id) == $role->id ? 'selected' : '' }}
                                        data-description="{{ $role->description }}">
                                    {{ $role->display_name }}
                                </option>
                                @endforeach
                            </select>
                            <small class="form-text text-muted">Main role for this user</small>
                            @error('primary_role_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <!-- Role Description -->
                        <div id="roleDescription" class="mb-3 p-3 bg-light rounded" style="display: none;">
                            <small class="text-muted"></small>
                        </div>

                        <!-- Additional Roles -->
                        <div class="form-group">
                            <label class="form-label font-weight-semibold">Additional Roles</label>
                            <small class="form-text text-muted mb-2">Select all roles for this user (including primary)</small>

                            @foreach($roles as $role)
                            @php
                                $roleConfig = match($role->name) {
                                    'superadmin' => ['bg' => 'bg-danger', 'icon' => 'fa-crown'],
                                    'supervisor' => ['bg' => 'bg-warning', 'icon' => 'fa-user-tie'],
                                    'staff' => ['bg' => 'bg-info', 'icon' => 'fa-user-edit'],
                                    'administrator' => ['bg' => 'bg-success', 'icon' => 'fa-user-cog'],
                                    'guest' => ['bg' => 'bg-secondary', 'icon' => 'fa-user-clock'],
                                    default => ['bg' => 'bg-secondary', 'icon' => 'fa-user']
                                };
                                $isSuperadminProtected = $role->name === 'superadmin' && $user->hasRole('superadmin') && $user->id === auth()->id();
                            @endphp
                            <div class="custom-control custom-checkbox mb-2">
                                <input type="checkbox"
                                       class="custom-control-input role-checkbox"
                                       id="role{{ $role->id }}"
                                       name="roles[]"
                                       value="{{ $role->id }}"
                                       {{ in_array($role->id, old('roles', $userRoles)) ? 'checked' : '' }}
                                       {{ $isSuperadminProtected ? 'disabled' : '' }}>
                                <label class="custom-control-label" for="role{{ $role->id }}">
                                    <div class="d-flex align-items-center">
                                        <div class="role-icon mr-2">
                                            <div class="{{ $roleConfig['bg'] }} rounded-circle d-flex align-items-center justify-content-center" style="width: 25px; height: 25px;">
                                                <i class="fas {{ $roleConfig['icon'] }} text-white" style="font-size: 10px;"></i>
                                            </div>
                                        </div>
                                        <div>
                                            <span class="font-weight-medium">{{ $role->display_name }}</span>
                                            @if($isSuperadminProtected)
                                                <span class="badge badge-warning badge-sm ml-2">Protected</span>
                                            @endif
                                            @if($role->description)
                                            <br><small class="text-muted">{{ Str::limit($role->description, 30) }}</small>
                                            @endif
                                        </div>
                                    </div>
                                </label>
                            </div>
                            @if($isSuperadminProtected)
                            <input type="hidden" name="roles[]" value="{{ $role->id }}">
                            @endif
                            @endforeach

                            @if($user->hasRole('superadmin') && $user->id === auth()->id())
                            <small class="form-text text-warning">
                                <i class="fas fa-shield-alt mr-1"></i>
                                You cannot remove your own superadmin role
                            </small>
                            @endif

                            @error('roles')
                                <div class="text-danger small">{{ $message }}</div>
                            @enderror
                        </div>

                        <!-- Selected Roles Summary -->
                        <div class="mt-3 p-3 bg-light rounded">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span class="font-weight-semibold text-dark">Selected Roles</span>
                                <span class="badge badge-primary" id="selectedRolesCount">{{ count($userRoles) }}</span>
                            </div>
                            <div id="selectedRolesList" class="text-muted small">
                                @if(count($userRoles) > 0)
                                    @foreach($user->roles->take(3) as $role)
                                        <span class="role-item">{{ $role->display_name }}</span>
                                    @endforeach
                                    @if($user->roles->count() > 3)
                                        <span class="text-muted">... and {{ $user->roles->count() - 3 }} more</span>
                                    @endif
                                @else
                                    No roles selected
                                @endif
                            </div>
                        </div>

                        @else
                        <div class="text-center py-4">
                            <i class="fas fa-exclamation-triangle fa-2x text-warning mb-2"></i>
                            <h6 class="text-muted">No Roles Available</h6>
                            <p class="text-muted small">Please create roles first before editing users.</p>
                        </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="row">
            <div class="col-md-12">
                <div class="card border-0 shadow-sm">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <a href="{{ route('users.show', $user) }}" class="btn btn-light px-4">
                                <i class="fas fa-times mr-1"></i> Cancel
                            </a>
                            <div>

                                <button type="submit" class="btn btn-primary px-4" id="submitBtn">
                                    <i class="fas fa-save mr-1"></i> Update User
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>

    <!-- Changes Preview Modal -->
    <div class="modal fade" id="changesModal" tabindex="-1">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content border-0 shadow">
                <div class="modal-header border-bottom-0 bg-info text-white">
                    <h6 class="modal-title">
                        <i class="fas fa-eye mr-2"></i>
                        Preview Changes
                    </h6>
                    <button type="button" class="close text-white" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="changesContent">
                    <!-- Content will be populated by JavaScript -->
                </div>
                <div class="modal-footer border-top-0">
                    <button type="button" class="btn btn-light" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" onclick="$('#userForm').submit()">
                        <i class="fas fa-save mr-1"></i> Apply Changes
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
$(document).ready(function() {
    const originalRoles = @json($userRoles);
    const originalUserData = {
        username: '{{ $user->username }}',
        name: '{{ $user->name }}',
        email: '{{ $user->email }}',
        primary_role_id: {{ $user->primary_role_id ?? 'null' }}
    };

    // Profile photo preview
    $('#profile_photo').change(function() {
        const file = this.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                $('#preview').attr('src', e.target.result);
                $('#imagePreview').show();
            }
            reader.readAsDataURL(file);
            $(this).next('.custom-file-label').text(file.name);
        }
    });

    // Password visibility toggle
    $('#togglePassword, #togglePasswordConfirm').click(function() {
        const target = $(this).attr('id') === 'togglePassword' ? '#password' : '#password_confirmation';
        const input = $(target);
        const type = input.attr('type') === 'password' ? 'text' : 'password';
        input.attr('type', type);
        $(this).find('i').toggleClass('fa-eye fa-eye-slash');
    });

    // Password strength checker (rest of the existing JavaScript...)
    // ... (keep all existing JavaScript code)

    // Initialize
    updateSelectedRoles();
    setTimeout(() => $('.alert').fadeOut('slow'), 5000);
});
</script>
@endpush
@endsection
