@extends('admin.layouts.app')

@section('title', __('admin/admin-management.edit_title'))

@section('content')
<div class="container-fluid px-4">
    <x-admin.page-header
        :title="__('admin/admin-management.edit_title') . ' - ' . $admin->name"
        icon="fas fa-user-edit"
        :buttons="[
            ['label' => __('admin/admin-management.buttons_cancel'), 'route' => route('admin.admin-management.index'), 'icon' => 'fas fa-arrow-left', 'color' => 'outline-secondary'],
        ]"
    >
        @if($admin->id === Auth::id())
            <div class="badge bg-info ms-2">{{ __('admin/admin-management.messages_editing_self') }}</div>
        @endif
    </x-admin.page-header>

    <x-admin.alert />

    @if($errors->any())
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i>
            <strong>{{ __('admin/common.validation_errors') }}</strong>
            <ul class="mb-0 mt-2">
                @foreach($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    @endif

    <form id="adminForm" action="{{ route('admin.admin-management.update', $admin) }}" method="POST">
        @csrf
        @method('PUT')

        <x-admin.card>
            <div class="row">
                <div class="col-md-6">
                    <!-- Name Field -->
                    <div class="mb-3">
                        <label for="edit_name" class="form-label">
                            {{ __('admin/admin-management.fields_name') }}
                            <span class="text-danger">*</span>
                        </label>
                        <input type="text" class="form-control @error('name') is-invalid @enderror"
                               id="edit_name" name="name" value="{{ old('name', $admin->name) }}" required
                               placeholder="{{ __('admin/admin-management.placeholders_name') }}">
                        @error('name')
                        <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>

                    <!-- Email Field -->
                    <div class="mb-3">
                        <label for="edit_email" class="form-label">
                            {{ __('admin/admin-management.fields_email') }}
                            <span class="text-danger">*</span>
                        </label>
                        <input type="email" class="form-control @error('email') is-invalid @enderror"
                               id="edit_email" name="email" value="{{ old('email', $admin->email) }}" required
                               placeholder="{{ __('admin/admin-management.placeholders_email') }}">
                        @error('email')
                        <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>

                    <!-- Password Field -->
                    <div class="mb-3">
                        <label for="edit_password" class="form-label">
                            {{ __('admin/admin-management.fields_password') }}
                        </label>
                        <div class="input-group">
                            <input type="password" class="form-control @error('password') is-invalid @enderror"
                                   id="edit_password" name="password"
                                   autocomplete="new-password"
                                   placeholder="{{ __('admin/admin-management.placeholders_password') }}">
                            <button class="btn btn-outline-secondary js-password-toggle" type="button" tabindex="-1"
                                    aria-label="{{ __('auth.password_show') }}"
                                    data-show-label="{{ __('auth.password_show') }}"
                                    data-hide-label="{{ __('auth.password_hide') }}">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="btn btn-outline-secondary" type="button" id="generatePassword">
                                {{ __('admin/admin-management.buttons_generate_password') }}
                            </button>
                        </div>
                        <div class="form-text">{{ __('admin/admin-management.help_texts_password_edit') }}</div>
                        @error('password')
                        <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>

                    <!-- Password Confirmation Field -->
                    <div class="mb-3">
                        <label for="edit_password_confirmation" class="form-label">
                            {{ __('admin/admin-management.fields_password_confirmation') }}
                        </label>
                        <div class="input-group">
                            <input type="password" class="form-control"
                                   id="edit_password_confirmation" name="password_confirmation"
                                   autocomplete="new-password"
                                   placeholder="{{ __('admin/admin-management.placeholders_password_confirmation') }}">
                            <button class="btn btn-outline-secondary js-password-toggle" type="button" tabindex="-1"
                                    aria-label="{{ __('auth.password_show') }}"
                                    data-show-label="{{ __('auth.password_show') }}"
                                    data-hide-label="{{ __('auth.password_hide') }}">
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>
                    </div>
                </div>

                <div class="col-md-6">
                    <!-- Role Assignment -->
                    <div class="mb-3">
                        <label class="form-label">{{ __('admin/admin-management.fields_roles') }}</label>
                        <div class="card">
                            <div class="card-body">
                                @foreach($roles as $role)
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox"
                                               id="role_{{ $role->id }}" name="roles[]" value="{{ $role->name }}"
                                               {{ $admin->hasRole($role->name) ? 'checked' : '' }}>
                                        <label class="form-check-label" for="role_{{ $role->id }}">
                                            {{ $role->name }}
                                        </label>
                                    </div>
                                @endforeach
                            </div>
                        </div>
                        <div class="form-text">{{ __('admin/admin-management.help_texts_roles') }}</div>
                    </div>

                    <!-- Status Field -->
                    <div class="mb-3">
                        <label for="edit_status" class="form-label">
                            {{ __('admin/admin-management.fields_status') }}
                        </label>
                        <select class="form-select @error('status') is-invalid @enderror"
                                id="edit_status" name="status"
                                {{ $admin->id === Auth::id() ? 'disabled' : '' }}>
                            <option value="active" @selected(old('status', $admin->status) === 'active')>
                                {{ __('admin/admin-management.status_active') }}
                            </option>
                            @if($admin->id !== Auth::id())
                                <option value="inactive" @selected(old('status', $admin->status) === 'inactive')>
                                    {{ __('admin/admin-management.status_inactive') }}
                                </option>
                                <option value="suspended" @selected(old('status', $admin->status) === 'suspended')>
                                    {{ __('admin/admin-management.status_suspended') }}
                                </option>
                            @endif
                        </select>
                        @if($admin->id === Auth::id())
                            <input type="hidden" name="status" value="active">
                            <div class="form-text text-warning">
                                {{ __('admin/admin-management.help_texts_cannot_deactivate_self') }}
                            </div>
                        @endif
                        @error('status')
                        <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>

                    <!-- Admin Info -->
                    <div class="alert alert-info">
                        <strong>{{ __('admin/admin-management.fields_last_login_at') }}:</strong>
                        {{ $admin->last_login_at ? $admin->last_login_at->format($dateTimeFormat) : __('admin/admin-management.messages_never_logged_in') }}
                        <br>
                        <strong>{{ __('admin/admin-management.fields_created_at') }}:</strong>
                        {{ $admin->created_at->format($dateTimeFormat) }}
                    </div>
                </div>
            </div>
        </x-admin.card>

        <!-- Notification Channels -->
        <x-admin.card :title="__('admin/admin-management.notification_channels')" icon="fas fa-broadcast-tower" class="mt-4">
            <p class="text-muted small mb-3">{{ __('admin/admin-management.notification_channels_desc') }}</p>
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="edit_phone" class="form-label">{{ __('admin/admin-management.field_phone') }}</label>
                        <input type="text" class="form-control @error('phone') is-invalid @enderror"
                               id="edit_phone" name="phone" value="{{ old('phone', $admin->phone) }}"
                               placeholder="+905551234567">
                        @error('phone')
                        <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    <div class="mb-3">
                        <label for="edit_slack_user_id" class="form-label">{{ __('admin/admin-management.field_slack_user_id') }}</label>
                        <input type="text" class="form-control @error('slack_user_id') is-invalid @enderror"
                               id="edit_slack_user_id" name="slack_user_id" value="{{ old('slack_user_id', $admin->slack_user_id) }}"
                               placeholder="U01ABCDEF">
                        @error('slack_user_id')
                        <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    <div class="mb-3">
                        <label for="edit_telegram_user_id" class="form-label">{{ __('admin/admin-management.field_telegram_user_id') }}</label>
                        <input type="text" class="form-control @error('telegram_user_id') is-invalid @enderror"
                               id="edit_telegram_user_id" name="telegram_user_id" value="{{ old('telegram_user_id', $admin->telegram_user_id) }}"
                               placeholder="123456789">
                        @error('telegram_user_id')
                        <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="edit_discord_webhook" class="form-label">{{ __('admin/admin-management.field_discord_webhook') }}</label>
                        <input type="url" class="form-control @error('discord_webhook') is-invalid @enderror"
                               id="edit_discord_webhook" name="discord_webhook" value="{{ old('discord_webhook', $admin->discord_webhook) }}"
                               placeholder="https://discord.com/api/webhooks/...">
                        @error('discord_webhook')
                        <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    <div class="mb-3">
                        <label for="edit_pushover_user_key" class="form-label">{{ __('admin/admin-management.field_pushover_user_key') }}</label>
                        <input type="text" class="form-control @error('pushover_user_key') is-invalid @enderror"
                               id="edit_pushover_user_key" name="pushover_user_key" value="{{ old('pushover_user_key', $admin->pushover_user_key) }}"
                               placeholder="uQiRzpo4DXghDmr9QzzfQu27cmVRsG">
                        @error('pushover_user_key')
                        <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
            </div>
        </x-admin.card>

        <!-- Notification Preferences Matrix -->
        <x-admin.card :title="__('admin/admin-management.notification_preferences')" icon="fas fa-bell" class="mt-4">
            <p class="text-muted small mb-3">{{ __('admin/admin-management.notification_preferences_desc') }}</p>

            @php
                // PRC-624 — anahtarlar şablon adıdır (Title Case); JSON pref
                // anahtarı NotificationService::prefKey ile türetilir.
                $notificationTypes = [
                    'Provisioning Failed' => ['label' => __('admin/admin-management.event_provisioning_failed'), 'icon' => 'fas fa-exclamation-triangle text-danger'],
                    'Admin Ticket Created Notification' => ['label' => __('admin/admin-management.event_ticket_created'), 'icon' => 'fas fa-ticket-alt text-primary'],
                    'Admin Ticket Replied Notification' => ['label' => __('admin/admin-management.event_ticket_replied'), 'icon' => 'fas fa-reply text-info'],
                    'Admin Payment Received Notification' => ['label' => __('admin/admin-management.event_payment_received'), 'icon' => 'fas fa-dollar-sign text-success'],
                    'Admin Domain Expiring Notification' => ['label' => __('admin/admin-management.event_domain_expiring'), 'icon' => 'fas fa-globe text-warning'],
                    'Admin Service Suspended Notification' => ['label' => __('admin/admin-management.event_service_suspended'), 'icon' => 'fas fa-pause-circle text-danger'],
                ];
                $availableChannels = ['email', 'slack', 'telegram', 'discord', 'whatsapp', 'pushover', 'sms'];
                $adminPrefs = old('notification_preferences', $admin->notification_preferences ?? []);
            @endphp

            <div class="table-responsive">
                <table class="table table-sm align-middle">
                    <thead>
                        <tr>
                            <th>{{ __('admin/admin-management.notification_event') }}</th>
                            @foreach($availableChannels as $ch)
                                <th class="text-center" style="width: 100px;">
                                    @if($ch === 'email')<i class="fas fa-envelope"></i>
                                    @elseif($ch === 'slack')<i class="fab fa-slack"></i>
                                    @elseif($ch === 'telegram')<i class="fab fa-telegram"></i>
                                    @elseif($ch === 'discord')<i class="fab fa-discord"></i>
                                    @elseif($ch === 'whatsapp')<i class="fab fa-whatsapp"></i>
                                    @elseif($ch === 'pushover')<i class="fas fa-bell"></i>
                                    @elseif($ch === 'sms')<i class="fas fa-sms"></i>
                                    @endif
                                    {{ ucfirst($ch) }}
                                </th>
                            @endforeach
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($notificationTypes as $eventType => $info)
                            @php
                                $prefKey = \App\Services\NotificationService::prefKey($eventType);
                                $currentChannels = $adminPrefs[$prefKey] ?? [];
                            @endphp
                            <tr>
                                <td><i class="{{ $info['icon'] }} me-2"></i>{{ $info['label'] }}</td>
                                @foreach($availableChannels as $ch)
                                    <td class="text-center">
                                        <input type="checkbox" class="form-check-input"
                                               name="notification_preferences[{{ $prefKey }}][]"
                                               value="{{ $ch }}"
                                               {{ in_array($ch, $currentChannels) ? 'checked' : '' }}>
                                    </td>
                                @endforeach
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </x-admin.card>

        <!-- Form Actions -->
        <x-admin.card class="mt-4">
            <x-admin.form-actions
                :submit-text="__('admin/admin-management.buttons_save')"
                :cancel-url="route('admin.admin-management.index')"
            />
        </x-admin.card>
    </form>
</div>
@endsection

@push('scripts')
<script>
    // Admin verilerini JavaScript'e aktar
    window.adminData = {
        id: {{ $admin->id }},
        name: '{{ $admin->name }}',
        email: '{{ $admin->email }}',
        status: '{{ $admin->status }}',
        roles: @json($admin->roles->pluck('name')),
        is_current_user: {{ $admin->id === Auth::id() ? 'true' : 'false' }}
    };

    // Route bilgilerini JavaScript'e aktar
    window.routes = {
        adminManagement: {
            update: '{{ route("admin.admin-management.update", $admin) }}'
        }
    };

    // Çevirileri JavaScript'e aktar
    window.translations = {
        validation: {
            required: '{{ __("validation.required") }}',
            email: '{{ __("validation.email") }}',
            confirmed: '{{ __("validation.confirmed") }}',
            min: '{{ __("validation.min_string") }}'
        },
        messages: {
            success: '{{ __("admin/admin-management.messages_updated") }}',
            error: '{{ __("admin/admin-management.messages_update_error") }}'
        }
    };
</script>
@vite('resources/js/admin/admin-management/edit.js')
@endpush