@extends('agency.layouts.app')

@section('title', 'Kaynağı Düzenle')
@section('page_title', 'Kaynağı Düzenle')

@php
    $breadcrumbs = [
        ['title' => 'Dashboard', 'url' => route('agency.dashboard')],
        ['title' => 'Kaynak Yönetimi', 'url' => route('agency.resources.index')],
        ['title' => 'Düzenle: ' . $resource->name, 'url' => '']
    ];
@endphp

@push('styles')
<style>
.create-wrap { display: grid; grid-template-columns: 260px 1fr; gap: 1.5rem; align-items: start; }
@media(max-width:991px){ .create-wrap{grid-template-columns:1fr;} }

.stepper-card {
    background:#fff; border-radius:16px; border:1px solid #f1f5f9;
    box-shadow:0 1px 4px rgba(0,0,0,.04); padding:1.5rem; position:sticky; top:80px;
}
.stepper-title { font-size:.7rem; font-weight:700; color:#94a3b8; letter-spacing:.7px; text-transform:uppercase; margin-bottom:1.25rem; }
.step-item { display:flex;align-items:center;gap:.75rem;padding:.6rem .75rem;border-radius:10px;cursor:pointer;transition:background .15s;margin-bottom:.25rem; }
.step-item:hover { background:#f8fafc; }
.step-item.active { background:#eff6ff; }
.step-num { width:30px;height:30px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:.8rem;font-weight:700;flex-shrink:0;background:#f1f5f9;color:#64748b;transition:all .2s; }
.step-item.active .step-num { background:#3b82f6;color:#fff; }
.step-item.done  .step-num  { background:#10b981;color:#fff; }
.step-name { font-size:.875rem;font-weight:600;color:#475569; }
.step-item.active .step-name { color:#2563eb; }
.step-item.done  .step-name  { color:#059669; }

.form-card { background:#fff;border-radius:16px;border:1px solid #f1f5f9;box-shadow:0 1px 4px rgba(0,0,0,.04);overflow:hidden; }
.form-section { padding:1.75rem 2rem;border-bottom:1px solid #f8fafc;display:none; }
.form-section.active { display:block; }
.section-header { margin-bottom:1.5rem; }
.section-header h3 { font-size:1.05rem;font-weight:700;color:#0f172a;margin:0 0 4px; }
.section-header p  { font-size:.825rem;color:#94a3b8;margin:0; }

.type-grid { display:grid;grid-template-columns:repeat(3,1fr);gap:1rem; }
.type-card { border:2px solid #e2e8f0;border-radius:14px;padding:1.25rem 1rem;text-align:center;cursor:pointer;transition:all .2s;background:#f8fafc;position:relative; }
.type-card:hover { border-color:#bfdbfe;background:#fff;transform:translateY(-2px);box-shadow:0 4px 16px rgba(0,0,0,.06); }
.type-card.selected { background:#fff;box-shadow:0 4px 16px rgba(59,130,246,.12); }
.type-card.guide-sel   { border-color:#3b82f6; }
.type-card.vehicle-sel { border-color:#10b981; }
.type-card.captain-sel { border-color:#8b5cf6; }
.type-card-icon  { font-size:1.75rem;margin-bottom:.6rem; }
.type-card-label { font-weight:700;font-size:.9rem;color:#0f172a; }
.type-card-sub   { font-size:.72rem;color:#94a3b8;margin-top:4px; }
.type-check { position:absolute;top:10px;right:10px;width:20px;height:20px;border-radius:50%;background:#e2e8f0;display:flex;align-items:center;justify-content:center;font-size:11px;color:#fff;transition:all .2s; }
.type-card.selected  .type-check { background:#3b82f6; }
.type-card.vehicle-sel .type-check { background:#10b981; }
.type-card.captain-sel .type-check { background:#8b5cf6; }

.f-group { margin-bottom:1.25rem; }
.f-label { display:block;font-size:.78rem;font-weight:700;color:#475569;letter-spacing:.3px;margin-bottom:.45rem;text-transform:uppercase; }
.f-label .req { color:#ef4444;margin-left:2px; }
.f-input,.f-select,.f-textarea { width:100%;padding:.65rem .9rem;border:1.5px solid #e2e8f0;border-radius:10px;font-size:.875rem;color:#0f172a;background:#f8fafc;transition:border-color .2s,box-shadow .2s; }
.f-input:focus,.f-select:focus,.f-textarea:focus { outline:none;border-color:#3b82f6;box-shadow:0 0 0 3px rgba(59,130,246,.1);background:#fff; }
.f-input-group { display:flex;align-items:stretch; }
.f-input-group .prefix { padding:.65rem .9rem;background:#f1f5f9;border:1.5px solid #e2e8f0;border-right:none;border-radius:10px 0 0 10px;font-size:.85rem;color:#64748b;font-weight:600;display:flex;align-items:center; }
.f-input-group .f-input { border-radius:0 10px 10px 0; }
.f-hint { font-size:.75rem;color:#94a3b8;margin-top:.35rem; }
.f-error { font-size:.75rem;color:#ef4444;margin-top:.35rem; }

.toggle-wrap { display:flex;align-items:center;gap:.75rem;padding:1rem 1.25rem;background:#f8fafc;border-radius:12px; }
.toggle-label { font-size:.875rem;font-weight:600;color:#0f172a; }
.toggle-sub   { font-size:.75rem;color:#94a3b8; }
.form-switch .form-check-input { width:2.5rem;height:1.3rem; }

.source-grid { display:grid;grid-template-columns:1fr 1fr;gap:.75rem;margin-bottom:1.25rem; }
.source-card { border:2px solid #e2e8f0;border-radius:12px;padding:1rem;cursor:pointer;transition:all .15s;background:#f8fafc; }
.source-card:hover  { border-color:#bfdbfe;background:#fff; }
.source-card.active { border-color:#3b82f6;background:#eff6ff; }
.source-card-label  { font-size:.875rem;font-weight:700;color:#0f172a; }
.source-card-sub    { font-size:.75rem;color:#94a3b8;margin-top:3px; }

.step-nav { padding:1.25rem 2rem;background:#fff;border-top:1px solid #f1f5f9;display:flex;justify-content:space-between;align-items:center; }
.btn-step { padding:.6rem 1.5rem;border-radius:10px;font-weight:600;font-size:.875rem;border:none;cursor:pointer;transition:all .15s;display:inline-flex;align-items:center;gap:.5rem; }
.btn-prev { background:#f1f5f9;color:#475569; }
.btn-prev:hover { background:#e2e8f0; }
.btn-next { background:linear-gradient(135deg,#3b82f6,#2563eb);color:#fff; }
.btn-next:hover { transform:translateY(-1px);box-shadow:0 4px 12px rgba(59,130,246,.35); }
.btn-submit { background:linear-gradient(135deg,#10b981,#059669);color:#fff; }
.btn-submit:hover { transform:translateY(-1px);box-shadow:0 4px 12px rgba(16,185,129,.35); }

.lang-tags { display:flex;flex-wrap:wrap;gap:.4rem; }
.lang-tag { padding:4px 10px;border-radius:20px;font-size:.75rem;font-weight:600;cursor:pointer;border:1.5px solid #e2e8f0;background:#f8fafc;color:#475569;transition:all .15s; }
.lang-tag.active { background:#eff6ff;border-color:#3b82f6;color:#2563eb; }

/* Multi-select (diller) */
.ms-wrap { position:relative; }
.ms-control { min-height:46px; width:100%; display:flex; align-items:center; gap:.4rem; flex-wrap:wrap; padding:.4rem .6rem; border:1.5px solid #e2e8f0; border-radius:10px; background:#f8fafc; cursor:text; transition:border-color .2s, box-shadow .2s; }
.ms-control.open { border-color:#3b82f6; box-shadow:0 0 0 3px rgba(59,130,246,.1); background:#fff; }
.ms-chips { display:flex; align-items:center; flex-wrap:wrap; gap:.4rem; flex:1; min-width:0; }
.ms-chip { display:inline-flex; align-items:center; gap:.35rem; background:#eff6ff; color:#2563eb; border:1px solid #bfdbfe; border-radius:8px; padding:3px 5px 3px 10px; font-size:.78rem; font-weight:700; }
.ms-chip-x { border:none; background:transparent; color:#3b82f6; cursor:pointer; font-size:1rem; line-height:1; padding:0 3px; border-radius:5px; transition:.15s; }
.ms-chip-x:hover { background:#dbeafe; color:#1d4ed8; }
.ms-search-inline { border:none; outline:none; background:transparent; flex:1; min-width:120px; font-size:.85rem; color:#0f172a; padding:4px 2px; }
.ms-chev { color:#94a3b8; font-size:.75rem; flex-shrink:0; transition:transform .2s; }
.ms-control.open .ms-chev { transform:rotate(180deg); }
.ms-dropdown { display:none; position:absolute; top:calc(100% + 4px); left:0; right:0; z-index:1050; background:#fff; border:1.5px solid #e2e8f0; border-radius:12px; box-shadow:0 12px 32px rgba(0,0,0,.12); overflow:hidden; }
.ms-dropdown.open { display:block; }
.ms-count { font-size:.7rem; color:#94a3b8; font-weight:700; padding:.5rem .7rem .25rem; border-bottom:1px solid #f1f5f9; }
.ms-list { max-height:260px; overflow-y:auto; padding:.35rem; }
.ms-option { display:flex; align-items:center; gap:.6rem; padding:.5rem .65rem; border-radius:8px; font-size:.85rem; color:#334155; cursor:pointer; transition:background .1s; }
.ms-option:hover { background:#f1f5f9; }
.ms-option.hidden { display:none; }
.ms-option.selected { color:#1e293b; font-weight:600; }
.ms-check { width:18px; height:18px; flex-shrink:0; border-radius:5px; border:1.5px solid #cbd5e1; display:grid; place-items:center; color:#fff; font-size:.6rem; transition:.15s; }
.ms-option.selected .ms-check { background:#3b82f6; border-color:#3b82f6; }
.ms-option:not(.selected) .ms-check i { opacity:0; }
.ms-empty { padding:.7rem 1rem; font-size:.82rem; color:#94a3b8; text-align:center; display:none; }

/* Searchable dropdown */
.ss-wrap { position:relative; }
.ss-trigger {
    width:100%; padding:.65rem .9rem;
    border:1.5px solid #e2e8f0; border-radius:10px;
    font-size:.875rem; color:#0f172a; background:#f8fafc;
    cursor:pointer; text-align:left; transition:border-color .2s, box-shadow .2s;
    display:flex; align-items:center; justify-content:space-between; gap:.5rem;
    white-space:nowrap; overflow:hidden; outline:none;
}
.ss-trigger.open { border-color:#3b82f6; box-shadow:0 0 0 3px rgba(59,130,246,.1); background:#fff; border-radius:10px 10px 0 0; }
.ss-trigger-text { overflow:hidden; text-overflow:ellipsis; flex:1; min-width:0; }
.ss-trigger-text.placeholder { color:#94a3b8; }
.ss-chevron { flex-shrink:0; color:#94a3b8; font-size:.75rem; transition:transform .2s; }
.ss-trigger.open .ss-chevron { transform:rotate(180deg); }
.ss-dropdown {
    display:none; position:absolute; top:100%; left:0; right:0; z-index:1050;
    background:#fff; border:1.5px solid #3b82f6; border-top:none;
    border-radius:0 0 12px 12px; box-shadow:0 8px 24px rgba(0,0,0,.12);
    overflow:hidden;
}
.ss-dropdown.open { display:block; }
.ss-search-box {
    padding:.55rem .75rem; border-bottom:1px solid #f1f5f9;
    display:flex; align-items:center; gap:.5rem;
}
.ss-search-input { flex:1; border:none; outline:none; font-size:.85rem; color:#0f172a; background:transparent; }
.ss-search-icon { color:#94a3b8; font-size:.8rem; flex-shrink:0; }
.ss-list { max-height:220px; overflow-y:auto; }
.ss-option {
    padding:.55rem 1rem; font-size:.875rem; color:#334155; cursor:pointer;
    transition:background .1s; display:flex; align-items:center; gap:.6rem;
}
.ss-option:hover { background:#eff6ff; color:#2563eb; }
.ss-option.selected { background:#eff6ff; color:#2563eb; font-weight:600; }
.ss-option.hidden { display:none; }
.ss-empty { padding:.75rem 1rem; font-size:.82rem; color:#94a3b8; text-align:center; display:none; }

.res-info-badge { display:inline-flex;align-items:center;gap:.5rem;padding:.4rem .85rem;border-radius:10px;font-size:.78rem;font-weight:600; }
.rib-guide   { background:#eff6ff;color:#2563eb; }
.rib-vehicle { background:#ecfdf5;color:#059669; }
.rib-captain { background:#f5f3ff;color:#7c3aed; }

/* Hızlı kullanıcı oluşturma */
.qu-toggle { border:1px solid #c7d2fe; background:#eef2ff; color:#4338ca; font-size:.72rem; font-weight:700; border-radius:8px; padding:4px 10px; cursor:pointer; transition:.15s; }
.qu-toggle:hover { background:#4338ca; color:#fff; border-color:#4338ca; }
.qu-panel { display:none; margin-top:10px; padding:14px; border:1px solid #e2e8f0; border-radius:14px; background:#f8fafc; }
.qu-panel.open { display:block; animation:quIn .18s ease; }
@keyframes quIn { from { opacity:0; transform:translateY(-6px); } to { opacity:1; transform:translateY(0); } }
.qu-title { font-size:.82rem; font-weight:800; color:#334155; margin-bottom:10px; }
.qu-panel .f-input, .qu-panel .f-select { font-size:.85rem; }
.qu-actions { display:flex; justify-content:flex-end; gap:8px; margin-top:10px; }
.qu-cancel { border:none; background:#e2e8f0; color:#475569; font-weight:700; font-size:.8rem; border-radius:9px; padding:8px 14px; cursor:pointer; }
.qu-cancel:hover { background:#cbd5e1; }
.qu-save { border:none; background:linear-gradient(135deg,#4f46e5,#7c3aed); color:#fff; font-weight:700; font-size:.8rem; border-radius:9px; padding:8px 16px; cursor:pointer; }
.qu-save:hover { filter:brightness(1.05); }
.qu-save:disabled { opacity:.6; cursor:not-allowed; }
.qu-note { font-size:.72rem; color:#94a3b8; margin-top:8px; }
</style>
@endpush

@section('content')
<div class="container-fluid">

    {{-- Resource summary bar --}}
    <div class="d-flex align-items-center gap-3 mb-4 p-3 bg-white rounded-3 shadow-sm" style="border:1px solid #f1f5f9">
        @php $initials = collect(explode(' ',$resource->name))->map(fn($w)=>mb_strtoupper(mb_substr($w,0,1)))->take(2)->implode(''); @endphp
        <div style="width:46px;height:46px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-weight:700;color:#fff;
                    background:{{ $resource->type==='guide'?'linear-gradient(135deg,#3b82f6,#2563eb)':($resource->type==='vehicle'?'linear-gradient(135deg,#10b981,#059669)':'linear-gradient(135deg,#8b5cf6,#7c3aed)') }}">
            {{ $initials }}
        </div>
        <div>
            <div style="font-weight:700;color:#0f172a">{{ $resource->name }}</div>
            <div style="font-size:.75rem;color:#94a3b8">Oluşturulma: {{ $resource->created_at->format('d.m.Y') }}</div>
        </div>
        <span class="res-info-badge rib-{{ $resource->type }} ms-2">
            @if($resource->type==='guide') <i class="fas fa-user-tie"></i> Rehber
            @elseif($resource->type==='vehicle') <i class="fas fa-bus"></i> Araç
            @else <i class="fas fa-id-card"></i> Kaptan
            @endif
        </span>
        <div class="ms-auto d-flex gap-2">
            <a href="{{ route('agency.resources.calendar', ['resource_id'=>$resource->id]) }}"
               class="btn btn-sm" style="background:#eff6ff;color:#2563eb;border-radius:10px;border:1.5px solid #bfdbfe;font-weight:600">
                <i class="fas fa-calendar-alt me-1"></i>Takvim
            </a>
        </div>
    </div>

    <form method="POST" action="{{ route('agency.resources.update', $resource) }}" id="editForm" enctype="multipart/form-data">
        @csrf @method('PUT')
        <input type="hidden" name="type"         id="hiddenType"      value="{{ old('type', $resource->type) }}">
        <input type="hidden" name="source_type"  id="hiddenSource"    value="{{ old('source_type', $resource->source_type) }}">
        <input type="hidden" name="languages"    id="hiddenLanguages" value="">

        <div class="create-wrap">

            {{-- Stepper --}}
            <div>
                <div class="stepper-card">
                    <div class="stepper-title">Form Adımları</div>
                    <div class="step-item active" id="si-1" onclick="goStep(1)">
                        <div class="step-num"><span>1</span></div>
                        <div class="step-name">Kaynak Türü</div>
                    </div>
                    <div class="step-item" id="si-2" onclick="goStep(2)">
                        <div class="step-num"><span>2</span></div>
                        <div class="step-name">Genel Bilgiler</div>
                    </div>
                    <div class="step-item" id="si-3" onclick="goStep(3)">
                        <div class="step-num"><span>3</span></div>
                        <div class="step-name">Detaylar & Belge</div>
                    </div>
                    <div class="step-item" id="si-4" onclick="goStep(4)">
                        <div class="step-num"><span>4</span></div>
                        <div class="step-name">Maliyet & Durum</div>
                    </div>
                    <div style="margin-top:1.5rem;padding-top:1rem;border-top:1px solid #f1f5f9">
                        <a href="{{ route('agency.resources.index') }}" class="btn btn-sm w-100"
                           style="border-radius:10px;border:1.5px solid #e2e8f0;color:#64748b;font-size:.8rem">
                            <i class="fas fa-arrow-left me-1"></i>Listeye Dön
                        </a>
                    </div>
                </div>
            </div>

            <div class="form-card">

                {{-- STEP 1 --}}
                <div class="form-section active" id="step-1">
                    <div class="section-header">
                        <h3><i class="fas fa-layer-group me-2 text-primary"></i>Kaynak Türü</h3>
                        <p>Kaynak türünü seçin. Değiştirirseniz bazı alanlar sıfırlanabilir.</p>
                    </div>
                    <div class="type-grid">
                        @foreach(['guide'=>['user-tie','#3b82f6','Rehber','Tur liderliği & yerel rehberlik'], 'vehicle'=>['bus','#10b981','Araç','Transfer & tur taşımacılığı'], 'captain'=>['id-card','#8b5cf6','Kaptan (Şoför)','Araç sürücüsü & transfer']] as $t=>$d)
                        <div class="type-card {{ old('type',$resource->type)===$t ? 'selected '.$t.'-sel' : '' }}"
                             onclick="selectType('{{ $t }}',this)" id="card-{{ $t }}">
                            <div class="type-check"><i class="fas fa-check"></i></div>
                            <div class="type-card-icon" style="color:{{ $d[1] }}"><i class="fas fa-{{ $d[0] }}"></i></div>
                            <div class="type-card-label">{{ $d[2] }}</div>
                            <div class="type-card-sub">{{ $d[3] }}</div>
                        </div>
                        @endforeach
                    </div>
                </div>

                {{-- STEP 2 --}}
                <div class="form-section" id="step-2">
                    <div class="section-header">
                        <h3><i class="fas fa-info-circle me-2 text-primary"></i>Genel Bilgiler</h3>
                        <p>Kaynağın temel bilgilerini güncelleyin.</p>
                    </div>
                    <div class="f-group">
                        <label class="f-label">Tedarik Şekli <span class="req">*</span></label>
                        <div class="source-grid">
                            <div class="source-card {{ old('source_type',$resource->source_type)==='internal' ? 'active' : '' }}"
                                 onclick="selectSource('internal',this)" id="src-internal">
                                <div class="source-card-label"><i class="fas fa-building me-2 text-primary"></i>İç Kaynak</div>
                                <div class="source-card-sub">Acentenin kendi bünyesindeki kaynak</div>
                            </div>
                            <div class="source-card {{ old('source_type',$resource->source_type)==='external' ? 'active' : '' }}"
                                 onclick="selectSource('external',this)" id="src-external">
                                <div class="source-card-label"><i class="fas fa-handshake me-2 text-warning"></i>Dış Kaynak</div>
                                <div class="source-card-sub">Tedarikçiden temin edilen kaynak</div>
                            </div>
                        </div>
                    </div>
                    <div class="f-group" id="supplier-wrap" style="{{ old('source_type',$resource->source_type)==='external' ? '' : 'display:none' }}">
                        <label class="f-label">Tedarikçi Firma <span id="sup-req-badge" style="display:none" class="req">*</span></label>
                        <input type="hidden" name="supplier_id" id="supplier_id" value="{{ old('supplier_id',$resource->supplier_id) }}">
                        <div class="ss-wrap" id="supplierDropWrap">
                            <button type="button" class="ss-trigger" id="ssTrigger" onclick="toggleSS()">
                                <span class="ss-trigger-text {{ old('supplier_id',$resource->supplier_id) ? '' : 'placeholder' }}" id="ssTriggerText">
                                    @php
                                        $curSupId = old('supplier_id', $resource->supplier_id);
                                        $curSup = $curSupId ? $suppliers->firstWhere('id',(int)$curSupId) : null;
                                    @endphp
                                    {{ $curSup ? $curSup->company_name : '— Seçin (opsiyonel) —' }}
                                </span>
                                <i class="fas fa-chevron-down ss-chevron"></i>
                            </button>
                            <div class="ss-dropdown" id="ssDropdown">
                                <div class="ss-search-box">
                                    <i class="fas fa-search ss-search-icon"></i>
                                    <input type="text" class="ss-search-input" id="ssSearch"
                                           placeholder="Tedarikçi ara..." oninput="filterSS(this.value)" autocomplete="off">
                                </div>
                                <div class="ss-list" id="ssList">
                                    <div class="ss-option {{ !old('supplier_id',$resource->supplier_id) ? 'selected' : '' }}"
                                         data-value="" onclick="selectSS('','',this)">
                                        <i class="fas fa-times-circle" style="color:#cbd5e1;font-size:.75rem"></i>
                                        Seçimi Kaldır
                                    </div>
                                    @foreach($suppliers as $sup)
                                        <div class="ss-option {{ old('supplier_id',$resource->supplier_id)==$sup->id ? 'selected' : '' }}"
                                             data-value="{{ $sup->id }}"
                                             data-label="{{ $sup->company_name }}"
                                             onclick="selectSS('{{ $sup->id }}','{{ addslashes($sup->company_name) }}',this)">
                                            <i class="fas fa-building" style="color:#94a3b8;font-size:.75rem"></i>
                                            {{ $sup->company_name }}
                                        </div>
                                    @endforeach
                                    <div class="ss-empty" id="ssEmpty">Sonuç bulunamadı</div>
                                </div>
                            </div>
                        </div>
                        @error('supplier_id')<div class="f-error">{{ $message }}</div>@enderror
                    </div>
                    <div class="row g-3">
                        {{-- Araç: tek ad/tanım alanı --}}
                        <div class="col-md-6" id="vehicle-name-wrap" style="display:none">
                            <div class="f-group">
                                <label class="f-label">Araç Kodu / Tanımlayıcı Ad <span class="req">*</span></label>
                                <input type="text" name="name" id="vehicle-name-input" class="f-input"
                                       placeholder="Örn: 34 ABC 123 Otobüs" value="{{ old('name',$resource->name) }}">
                                @error('name')<div class="f-error">{{ $message }}</div>@enderror
                            </div>
                        </div>
                        {{-- Rehber/Kaptan: ad ve soyad ayrı --}}
                        <div class="col-md-3" id="first-name-wrap">
                            <div class="f-group">
                                <label class="f-label" id="first-name-label">Ad <span class="req">*</span></label>
                                <input type="text" name="first_name" id="first-name-input" class="f-input"
                                       placeholder="Ad" value="{{ old('first_name',$resource->first_name) }}">
                                @error('first_name')<div class="f-error">{{ $message }}</div>@enderror
                            </div>
                        </div>
                        <div class="col-md-3" id="last-name-wrap">
                            <div class="f-group">
                                <label class="f-label" id="last-name-label">Soyad <span class="req">*</span></label>
                                <input type="text" name="last_name" id="last-name-input" class="f-input"
                                       placeholder="Soyad" value="{{ old('last_name',$resource->last_name) }}">
                                @error('last_name')<div class="f-error">{{ $message }}</div>@enderror
                            </div>
                        </div>
                        <div class="col-md-6" id="user-wrap">
                            <div class="f-group">
                                <label class="f-label d-flex justify-content-between align-items-center" style="gap:8px;">
                                    <span>Sistem Kullanıcısı</span>
                                    <button type="button" class="qu-toggle" id="quToggle"><i class="fas fa-user-plus"></i> Yeni Kullanıcı</button>
                                </label>
                                <select name="user_id" class="f-select" id="userSelect">
                                    <option value="">— Bağlantı Kurma —</option>
                                    @foreach($users as $u)
                                        <option value="{{ $u->id }}" {{ old('user_id',$resource->user_id)==$u->id ? 'selected' : '' }}>{{ $u->full_name }}</option>
                                    @endforeach
                                </select>
                                <div class="f-hint">Kendi programını görebilmesi için eşleştirin.</div>

                                {{-- Hızlı sistem kullanıcısı oluşturma --}}
                                <div class="qu-panel" id="quPanel">
                                    <div class="qu-title"><i class="fas fa-user-plus me-1"></i> Yeni Sistem Kullanıcısı Oluştur</div>
                                    <div class="row g-2">
                                        <div class="col-6"><input type="text" class="f-input" id="quFirst" placeholder="Ad *"></div>
                                        <div class="col-6"><input type="text" class="f-input" id="quLast" placeholder="Soyad *"></div>
                                        <div class="col-12"><input type="email" class="f-input" id="quEmail" placeholder="E-posta * (giriş için)"
                                               value="{{ $resource->email }}"></div>
                                        <div class="col-6"><input type="text" class="f-input" id="quPhone" placeholder="Telefon"
                                               value="{{ $resource->phone }}"></div>
                                        <div class="col-6"><input type="password" class="f-input" id="quPass" placeholder="Şifre * (min 6)"></div>
                                        <div class="col-12">
                                            <select class="f-select" id="quRole">
                                                @foreach($roles as $r)
                                                    <option value="{{ $r->id }}" {{ $r->name==='agency-staff' ? 'selected' : '' }}>{{ ucfirst(str_replace('-',' ',$r->name)) }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                    </div>
                                    <div class="qu-actions">
                                        <button type="button" class="qu-cancel" id="quCancel">Vazgeç</button>
                                        <button type="button" class="qu-save" id="quSave"><i class="fas fa-check me-1"></i> Oluştur & Seç</button>
                                    </div>
                                    <div class="qu-note"><i class="fas fa-circle-info me-1"></i>Kullanıcı oluşturulup listede seçilir; bağlamayı tamamlamak için formu <strong>kaydedin</strong>.</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6" id="phone-wrap">
                            <div class="f-group">
                                <label class="f-label">Telefon</label>
                                <input type="text" name="phone" class="f-input"
                                       value="{{ old('phone',$resource->phone) }}">
                            </div>
                        </div>
                        <div class="col-md-6" id="email-wrap">
                            <div class="f-group">
                                <label class="f-label">E-posta</label>
                                <input type="email" name="email" class="f-input"
                                       value="{{ old('email',$resource->email) }}">
                            </div>
                        </div>
                        <div class="col-md-6" id="identity-wrap">
                            <div class="f-group">
                                <label class="f-label">T.C. Kimlik / Pasaport No</label>
                                <input type="text" name="identity_number" class="f-input"
                                       value="{{ old('identity_number',$resource->identity_number) }}">
                            </div>
                        </div>
                    </div>
                </div>

                {{-- STEP 3 --}}
                <div class="form-section" id="step-3">
                    <div class="section-header">
                        <h3 id="detail-title"><i class="fas fa-clipboard-list me-2 text-primary"></i>Belge & Detay</h3>
                        <p id="detail-sub">Lisans ve dil bilgilerini düzenleyin.</p>
                    </div>
                    <div id="guide-fields">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <div class="f-group">
                                    <label class="f-label" id="license-label">Lisans Numarası</label>
                                    <input type="text" name="license_number" class="f-input"
                                           value="{{ old('license_number',$resource->license_number) }}">
                                </div>
                            </div>
                            <div class="col-12" id="lang-wrap">
                                <div class="f-group">
                                    <label class="f-label">Bildiği Diller</label>
                                    <div class="ms-wrap" id="langMs">
                                        <div class="ms-control" id="langControl">
                                            <div class="ms-chips" id="langChips">
                                                <input type="text" class="ms-search-inline" id="langSearch"
                                                       placeholder="Dil ara ve seç..." autocomplete="off">
                                            </div>
                                            <i class="fas fa-chevron-down ms-chev"></i>
                                        </div>
                                        <div class="ms-dropdown" id="langDropdown">
                                            <div class="ms-count" id="langCount"></div>
                                            <div class="ms-list" id="langList">
                                                @foreach($languages as $lang)
                                                    <div class="ms-option" data-label="{{ $lang }}">
                                                        <span class="ms-check"><i class="fas fa-check"></i></span>
                                                        <span>{{ $lang }}</span>
                                                    </div>
                                                @endforeach
                                                <div class="ms-empty" id="langEmpty">Sonuç bulunamadı</div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="f-hint">Aramak için yazın, seçmek için tıklayın. Seçili dilleri ✕ ile kaldırabilirsiniz.</div>
                                </div>
                            </div>
                        </div>

                        {{-- Rehbere özel mesleki bilgiler --}}
                        <div id="guide-pro-wrap">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <div class="f-group">
                                        <label class="f-label">Ruhsat Numarası</label>
                                        <input type="text" name="guide_registration_no" class="f-input"
                                               placeholder="Örn: 123456" value="{{ old('guide_registration_no',$resource->guide_registration_no) }}">
                                        @error('guide_registration_no')<div class="f-error">{{ $message }}</div>@enderror
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="f-group">
                                        @include('agency.resources._chamber-select')
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="f-group">
                                        <label class="f-label">Hizmet Bilgisi</label>
                                        <textarea name="guide_service_info" class="f-textarea" rows="3"
                                                  placeholder="Uzmanlık alanı, hizmet bölgeleri, deneyim notları...">{{ old('guide_service_info',$resource->guide_service_info) }}</textarea>
                                        <div class="f-hint">Rehberin uzmanlık/hizmet detaylarını yazın.</div>
                                        @error('guide_service_info')<div class="f-error">{{ $message }}</div>@enderror
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div id="vehicle-fields" style="display:none">
                        <div class="section-header" style="margin-bottom:1rem">
                            <h3><i class="fas fa-car me-2" style="color:#10b981"></i>Araç Teknik Bilgileri</h3>
                        </div>
                        <div class="row g-3">
                            <div class="col-md-12">
                                <div class="f-group">
                                    <label class="f-label">Araç Tipi</label>
                                    <select name="vehicle_class" class="f-select">
                                        <option value="">— Seçiniz —</option>
                                        @foreach(\App\Models\Resource::VEHICLE_CLASSES as $vcVal => $vcLabel)
                                            <option value="{{ $vcVal }}" {{ old('vehicle_class',$resource->vehicle_class) === $vcVal ? 'selected' : '' }}>{{ $vcLabel }}</option>
                                        @endforeach
                                    </select>
                                    @error('vehicle_class')<div class="f-error">{{ $message }}</div>@enderror
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="f-group">
                                    <label class="f-label">Marka <span class="req">*</span></label>
                                    <input type="text" name="vehicle_brand" class="f-input veh-req"
                                           value="{{ old('vehicle_brand',$resource->vehicle_brand) }}">
                                    @error('vehicle_brand')<div class="f-error">{{ $message }}</div>@enderror
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="f-group">
                                    <label class="f-label">Model <span class="req">*</span></label>
                                    <input type="text" name="vehicle_model" class="f-input veh-req"
                                           value="{{ old('vehicle_model',$resource->vehicle_model) }}">
                                    @error('vehicle_model')<div class="f-error">{{ $message }}</div>@enderror
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="f-group">
                                    <label class="f-label">Model Yılı</label>
                                    <input type="number" name="vehicle_year" class="f-input"
                                           value="{{ old('vehicle_year',$resource->vehicle_year) }}">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="f-group">
                                    <label class="f-label">Plaka <span class="req">*</span></label>
                                    <input type="text" name="vehicle_plate" class="f-input veh-req"
                                           value="{{ old('vehicle_plate',$resource->vehicle_plate) }}"
                                           style="text-transform:uppercase;letter-spacing:2px;font-weight:700;font-family:monospace">
                                    @error('vehicle_plate')<div class="f-error">{{ $message }}</div>@enderror
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="f-group">
                                    <label class="f-label">Mevcut Kilometre</label>
                                    <div class="f-input-group">
                                        <div class="prefix">KM</div>
                                        <input type="number" name="vehicle_km" class="f-input"
                                               value="{{ old('vehicle_km',$resource->vehicle_km) }}">
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="f-group">
                                    <label class="f-label">Yolcu Kapasitesi</label>
                                    <div class="f-input-group">
                                        <div class="prefix"><i class="fas fa-users"></i></div>
                                        <input type="number" name="vehicle_capacity" class="f-input"
                                               placeholder="örn: 16" value="{{ old('vehicle_capacity',$resource->vehicle_capacity) }}" min="1">
                                    </div>
                                    @error('vehicle_capacity')<div class="f-error">{{ $message }}</div>@enderror
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="f-group">
                                    <label class="f-label">Yakıt Tüketimi</label>
                                    <div class="f-input-group">
                                        <div class="prefix"><i class="fas fa-gas-pump"></i></div>
                                        <input type="number" step="0.1" name="vehicle_fuel_consumption" class="f-input"
                                               placeholder="1 lt ile km (örn: 8.5)" value="{{ old('vehicle_fuel_consumption',$resource->vehicle_fuel_consumption) }}" min="0">
                                    </div>
                                    <div class="f-hint">1 litre yakıt ile gidilen kilometre (km/lt). Maliyet hesabında kullanılır.</div>
                                    @error('vehicle_fuel_consumption')<div class="f-error">{{ $message }}</div>@enderror
                                </div>
                            </div>
                            <div class="col-12">
                                <div class="f-group">
                                    <label class="f-label">Araç Ruhsatı</label>
                                    @if($resource->vehicle_registration_document)
                                        <div class="d-flex align-items-center gap-2 mb-2">
                                            <a href="{{ $resource->vehicle_registration_url }}" target="_blank" class="btn btn-sm" style="background:#eff6ff;color:#2563eb;border:1.5px solid #bfdbfe;border-radius:8px;font-weight:600">
                                                <i class="fas {{ $resource->vehicle_registration_is_pdf ? 'fa-file-pdf' : 'fa-image' }} me-1"></i>Mevcut Ruhsatı Görüntüle
                                            </a>
                                            <span class="f-hint mb-0">Yeni dosya seçerseniz mevcut belge değişir.</span>
                                        </div>
                                    @endif
                                    <input type="file" name="vehicle_registration_document" class="f-input" accept="image/jpeg,image/png,image/webp,application/pdf">
                                    <div class="f-hint">Görsel (jpg, png, webp) veya PDF yükleyebilirsiniz. En fazla 5 MB.</div>
                                    @error('vehicle_registration_document')<div class="f-error">{{ $message }}</div>@enderror
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                {{-- STEP 4 --}}
                <div class="form-section" id="step-4">
                    <div class="section-header">
                        <h3><i class="fas fa-coins me-2 text-warning"></i>Maliyet & Durum</h3>
                    </div>

                    @include('agency.resources._cost-items')
                    <div class="toggle-wrap mt-3">
                        <div class="form-check form-switch mb-0">
                            <input class="form-check-input" type="checkbox" name="is_active" id="is_active" value="1"
                                   {{ old('is_active', $resource->is_active) ? 'checked' : '' }}>
                        </div>
                        <div>
                            <div class="toggle-label">Kaynak Aktif</div>
                            <div class="toggle-sub">Pasif kaynaklar tur atamalarında görünmez.</div>
                        </div>
                    </div>
                </div>

                <div class="step-nav">
                    <button type="button" class="btn-step btn-prev" id="prevBtn" onclick="prevStep()" style="display:none">
                        <i class="fas fa-arrow-left"></i> Geri
                    </button>
                    <div class="ms-auto d-flex gap-2">
                        <button type="button" class="btn-step btn-next" id="nextBtn" onclick="nextStep()">
                            İleri <i class="fas fa-arrow-right"></i>
                        </button>
                        <button type="submit" class="btn-step btn-submit" id="submitBtn" style="display:none">
                            <i class="fas fa-check me-1"></i> Değişiklikleri Kaydet
                        </button>
                    </div>
                </div>

            </div>{{-- /form-card --}}
        </div>
    </form>
</div>
@endsection

@push('scripts')
<script>
let currentStep  = 1;
const totalSteps = 4;
let selectedType   = '{{ old("type",$resource->type) }}';
let selectedSource = '{{ old("source_type",$resource->source_type) }}';
let selectedLangs  = @json(old('languages', $resource->languages ?? []));

function selectType(type, el) {
    selectedType = type;
    document.getElementById('hiddenType').value = type;
    document.querySelectorAll('.type-card').forEach(c => c.classList.remove('selected','guide-sel','vehicle-sel','captain-sel'));
    el.classList.add('selected', type + '-sel');
    applyTypeFields();
}
function applyTypeFields() {
    const isVehicle = selectedType === 'vehicle';
    document.getElementById('user-wrap').style.display     = isVehicle ? 'none' : '';
    document.getElementById('phone-wrap').style.display    = isVehicle ? 'none' : '';
    document.getElementById('email-wrap').style.display    = isVehicle ? 'none' : '';
    document.getElementById('identity-wrap').style.display = isVehicle ? 'none' : '';
    document.getElementById('vehicle-fields').style.display = isVehicle ? 'block' : 'none';
    document.getElementById('guide-fields').style.display   = isVehicle ? 'none'  : 'block';
    document.querySelectorAll('.veh-req').forEach(el => isVehicle ? el.setAttribute('required','') : el.removeAttribute('required'));
    // Tedarikçi seçimi yalnızca araç tipinde (ve dış kaynakta) görünür; rehber/şoför için kaldırılır
    document.getElementById('supplier-wrap').style.display = (isVehicle && selectedSource === 'external') ? '' : 'none';
    if (!isVehicle) {
        const sid = document.getElementById('supplier_id');
        if (sid) sid.value = '';
        const sTxt = document.getElementById('ssTriggerText');
        if (sTxt) { sTxt.textContent = '— Seçin (opsiyonel) —'; sTxt.classList.add('placeholder'); }
    }
    updateSupplierRequired();
    // Ad alanları: araçta tek "name", kişide ad+soyad
    document.getElementById('vehicle-name-wrap').style.display = isVehicle ? '' : 'none';
    document.getElementById('first-name-wrap').style.display   = isVehicle ? 'none' : '';
    document.getElementById('last-name-wrap').style.display    = isVehicle ? 'none' : '';
    const vni = document.getElementById('vehicle-name-input');
    const fni = document.getElementById('first-name-input');
    const lni = document.getElementById('last-name-input');
    if (isVehicle) {
        vni.setAttribute('required',''); fni.removeAttribute('required'); lni.removeAttribute('required');
    } else {
        vni.removeAttribute('required'); fni.setAttribute('required',''); lni.setAttribute('required','');
        document.getElementById('first-name-label').innerHTML =
            (selectedType==='guide' ? 'Rehber Adı' : 'Kaptan Adı') + ' <span class="req">*</span>';
    }
    document.getElementById('lang-wrap').style.display = selectedType==='guide' ? '' : 'none';
    const gpw = document.getElementById('guide-pro-wrap');
    if (gpw) gpw.style.display = selectedType==='guide' ? '' : 'none';
    const ll = document.getElementById('license-label');
    if (ll) ll.textContent = selectedType==='captain' ? 'Sürücü Belgesi Sınıfı' : 'Lisans Numarası';
}
function selectSource(src, el) {
    selectedSource = src;
    document.getElementById('hiddenSource').value = src;
    document.getElementById('src-internal').classList.toggle('active', src==='internal');
    document.getElementById('src-external').classList.toggle('active', src==='external');
    document.getElementById('supplier-wrap').style.display = (src==='external' && selectedType==='vehicle') ? '' : 'none';
    updateSupplierRequired();
}
function updateSupplierRequired() {
    const isReq = (selectedSource === 'external' && selectedType === 'vehicle');
    const badge = document.getElementById('sup-req-badge');
    if (badge) badge.style.display = isReq ? '' : 'none';
    document.getElementById('supplier_id').required = isReq;
}

// Searchable supplier dropdown
function toggleSS() {
    const trigger = document.getElementById('ssTrigger');
    const isOpen = trigger.classList.contains('open');
    if (isOpen) { closeSS(); return; }
    trigger.classList.add('open');
    document.getElementById('ssDropdown').classList.add('open');
    document.getElementById('ssSearch').focus();
}
function closeSS() {
    document.getElementById('ssTrigger').classList.remove('open');
    document.getElementById('ssDropdown').classList.remove('open');
    document.getElementById('ssSearch').value = '';
    filterSS('');
}
function selectSS(val, label, optEl) {
    document.getElementById('supplier_id').value = val;
    const txt = document.getElementById('ssTriggerText');
    txt.textContent = val ? label : '— Seçin (opsiyonel) —';
    txt.classList.toggle('placeholder', !val);
    document.querySelectorAll('#ssList .ss-option').forEach(o => o.classList.remove('selected'));
    if (optEl) optEl.classList.add('selected');
    closeSS();
    updateSupplierRequired();
}
function filterSS(q) {
    const term = q.toLowerCase();
    let visible = 0;
    document.querySelectorAll('#ssList .ss-option:not(:first-child)').forEach(o => {
        const hide = term && !(o.dataset.label||'').toLowerCase().includes(term);
        o.classList.toggle('hidden', hide);
        if (!hide) visible++;
    });
    document.getElementById('ssEmpty').style.display = (term && visible===0) ? '' : 'none';
}
document.addEventListener('click', function(e) {
    const wrap = document.getElementById('supplierDropWrap');
    if (wrap && !wrap.contains(e.target)) closeSS();
});
// ── Diller (aranabilir çoklu seçim) ──
function langSyncHidden() {
    document.getElementById('hiddenLanguages').value = selectedLangs.join(',');
    const c = document.getElementById('langCount');
    if (c) c.textContent = selectedLangs.length ? (selectedLangs.length + ' dil seçili') : 'Henüz dil seçilmedi';
}
function langRenderChips() {
    const chips = document.getElementById('langChips');
    const search = document.getElementById('langSearch');
    chips.querySelectorAll('.ms-chip').forEach(c => c.remove());
    selectedLangs.forEach(lang => {
        const chip = document.createElement('span');
        chip.className = 'ms-chip';
        const txt = document.createElement('span');
        txt.textContent = lang;
        const x = document.createElement('button');
        x.type = 'button'; x.className = 'ms-chip-x'; x.innerHTML = '&times;';
        x.addEventListener('click', function (e) { e.stopPropagation(); langRemove(lang); });
        chip.appendChild(txt); chip.appendChild(x);
        chips.insertBefore(chip, search);
    });
    search.placeholder = selectedLangs.length ? 'Ekle...' : 'Dil ara ve seç...';
}
function langUpdateOptions() {
    document.querySelectorAll('#langList .ms-option').forEach(o => {
        o.classList.toggle('selected', selectedLangs.includes(o.dataset.label));
    });
}
function langToggle(lang) {
    const idx = selectedLangs.indexOf(lang);
    if (idx>-1) selectedLangs.splice(idx,1); else selectedLangs.push(lang);
    langRenderChips(); langUpdateOptions(); langSyncHidden();
}
function langRemove(lang) {
    const idx = selectedLangs.indexOf(lang);
    if (idx>-1) selectedLangs.splice(idx,1);
    langRenderChips(); langUpdateOptions(); langSyncHidden();
}
function langOpen() {
    document.getElementById('langControl').classList.add('open');
    document.getElementById('langDropdown').classList.add('open');
}
function langClose() {
    document.getElementById('langControl').classList.remove('open');
    document.getElementById('langDropdown').classList.remove('open');
}
function langFilter(q) {
    const term = (q || '').toLowerCase().trim();
    let visible = 0;
    document.querySelectorAll('#langList .ms-option').forEach(o => {
        const hide = term && !o.dataset.label.toLowerCase().includes(term);
        o.classList.toggle('hidden', hide);
        if (!hide) visible++;
    });
    document.getElementById('langEmpty').style.display = (term && visible === 0) ? 'block' : 'none';
}
function langInit() {
    const control = document.getElementById('langControl');
    const search = document.getElementById('langSearch');
    if (!control) return;
    control.addEventListener('click', () => { langOpen(); search.focus(); });
    search.addEventListener('input', function () { langFilter(this.value); langOpen(); });
    search.addEventListener('keydown', function (e) {
        if (e.key === 'Backspace' && this.value === '' && selectedLangs.length) {
            langRemove(selectedLangs[selectedLangs.length - 1]);
        }
    });
    document.querySelectorAll('#langList .ms-option').forEach(o => {
        o.addEventListener('click', function (e) {
            e.stopPropagation();
            langToggle(this.dataset.label);
            search.value = ''; langFilter(''); search.focus();
        });
    });
    document.addEventListener('click', function (e) {
        const ms = document.getElementById('langMs');
        if (ms && !ms.contains(e.target)) langClose();
    });
    langRenderChips(); langUpdateOptions(); langSyncHidden();
}
function goStep(n) {
    if (n<1||n>totalSteps) return;
    document.getElementById('step-'+currentStep).classList.remove('active');
    currentStep = n;
    document.getElementById('step-'+currentStep).classList.add('active');
    document.querySelectorAll('.step-item').forEach((el,i) => {
        el.classList.remove('active','done');
        if (i+1<currentStep) el.classList.add('done');
        if (i+1===currentStep) el.classList.add('active');
    });
    document.getElementById('prevBtn').style.display   = currentStep>1        ? '':'none';
    document.getElementById('nextBtn').style.display   = currentStep<totalSteps ? '':'none';
    document.getElementById('submitBtn').style.display = currentStep===totalSteps ? '':'none';
    window.scrollTo({top:0,behavior:'smooth'});
}
function nextStep(){ goStep(currentStep+1); }
function prevStep(){ goStep(currentStep-1); }

document.addEventListener('DOMContentLoaded', function(){
    applyTypeFields();
    selectSource(selectedSource, document.getElementById('src-'+selectedSource));
    goStep(1);
    langInit();
    const tc = document.getElementById('card-'+selectedType);
    if(tc) tc.classList.add('selected',selectedType+'-sel');
});

// ── Hızlı sistem kullanıcısı oluşturma ──
(function () {
    const toggle = document.getElementById('quToggle');
    if (!toggle) return;
    const panel = document.getElementById('quPanel');
    const sel = document.getElementById('userSelect');
    const save = document.getElementById('quSave');
    const CSRF = document.querySelector('meta[name="csrf-token"]')?.content;
    const $v = id => (document.getElementById(id)?.value || '').trim();

    function quNotify(msg, ok) {
        if (window.Swal) Swal.fire({ toast:true, position:'top-end', timer:2800, timerProgressBar:true, showConfirmButton:false, icon: ok ? 'success' : 'error', title: msg });
        else if (typeof toastr !== 'undefined') ok ? toastr.success(msg) : toastr.error(msg);
        else alert(msg);
    }

    toggle.addEventListener('click', () => panel.classList.toggle('open'));
    document.getElementById('quCancel').addEventListener('click', () => panel.classList.remove('open'));

    save.addEventListener('click', function () {
        const data = {
            first_name: $v('quFirst'), last_name: $v('quLast'), email: $v('quEmail'),
            phone: $v('quPhone'), password: document.getElementById('quPass').value, role_id: $v('quRole'),
        };
        if (!data.first_name || !data.last_name || !data.email || !data.password) { quNotify('Ad, soyad, e-posta ve şifre zorunludur.', false); return; }
        if (data.password.length < 6) { quNotify('Şifre en az 6 karakter olmalı.', false); return; }

        const orig = save.innerHTML;
        save.disabled = true; save.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Oluşturuluyor…';

        fetch('{{ route('agency.resources.quick-user') }}', {
            method: 'POST',
            headers: { 'Content-Type':'application/json', 'X-CSRF-TOKEN': CSRF, 'Accept':'application/json' },
            body: JSON.stringify(data)
        }).then(async r => ({ ok: r.ok, d: await r.json().catch(() => ({})) }))
          .then(({ ok, d }) => {
              save.disabled = false; save.innerHTML = orig;
              if (ok && d.success) {
                  const opt = new Option(d.user.full_name, d.user.id, true, true);
                  sel.add(opt); sel.value = d.user.id;
                  panel.classList.remove('open');
                  ['quFirst','quLast','quEmail','quPhone','quPass'].forEach(id => { const el = document.getElementById(id); if (el) el.value = ''; });
                  quNotify(d.message || 'Kullanıcı oluşturuldu ve seçildi.', true);
              } else {
                  let msg = d.message || 'Kullanıcı oluşturulamadı.';
                  if (d.errors) msg = Object.values(d.errors).flat().join(' ');
                  quNotify(msg, false);
              }
          }).catch(() => { save.disabled = false; save.innerHTML = orig; quNotify('Bağlantı hatası.', false); });
    });
})();
</script>
@endpush
