@extends('agency.layouts.app')

@section('title', 'Özel Alan Yönetimi')
@section('page_title', 'Özel Alan Yönetimi')

@push('styles')
<style>
:root { --cp:#6366f1; --border:#f1f5f9; }
.fields-header { display:flex;justify-content:space-between;align-items:center;background:#fff;border-radius:16px;border:1px solid var(--border);padding:1.25rem 1.5rem;margin-bottom:1rem;box-shadow:0 1px 4px rgba(0,0,0,.04); }
.fields-grid { display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:1rem;margin-bottom:1rem; }
.field-card { background:#fff;border-radius:16px;border:1px solid var(--border);box-shadow:0 1px 4px rgba(0,0,0,.04);transition:box-shadow .2s,transform .2s;overflow:hidden; }
.field-card:hover { box-shadow:0 4px 20px rgba(99,102,241,.12);transform:translateY(-2px); }
.field-card.inactive { opacity:.6; }
.field-card-stripe { height:4px;background:linear-gradient(90deg,#6366f1,#8b5cf6); }
.field-card.inactive .field-card-stripe { background:#e2e8f0; }
.fc-body { padding:1.1rem; }
.fc-header { display:flex;justify-content:space-between;align-items:start; }
.fc-label { font-size:.95rem;font-weight:700;color:#0f172a; }
.fc-key { font-size:.68rem;font-family:monospace;background:#f8fafc;color:#6366f1;padding:2px 7px;border-radius:5px;border:1px solid #e0e7ff;margin-top:3px;display:inline-block; }
.fc-type-badge { padding:3px 9px;border-radius:20px;font-size:.7rem;font-weight:700;background:#eef2ff;color:#6366f1;white-space:nowrap; }
.fc-meta { display:flex;gap:.75rem;margin-top:.85rem;padding-top:.75rem;border-top:1px solid #f8fafc;flex-wrap:wrap; }
.fc-meta-item { display:flex;align-items:center;gap:4px;font-size:.72rem;color:#94a3b8; }
.fc-actions { display:flex;gap:6px; }
.fc-btn { width:32px;height:32px;border-radius:8px;border:none;display:flex;align-items:center;justify-content:center;font-size:13px;cursor:pointer;transition:all .15s; }
.fc-btn:hover { transform:scale(1.1); }
.fc-btn.edit   { background:#eef2ff;color:#6366f1; }
.fc-btn.toggle { background:#fef3c7;color:#f59e0b; }
.fc-btn.del    { background:#fee2e2;color:#ef4444; }
.modal-content { border-radius:20px !important;border:none !important;box-shadow:0 20px 60px rgba(0,0,0,.15) !important; }
.mf-label { font-size:.78rem;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.4px;margin-bottom:.4rem;display:block; }
.mf-input { width:100%;border:1.5px solid #e2e8f0;border-radius:10px;padding:.65rem .9rem;font-size:.875rem;background:#f8fafc;transition:all .2s;height:44px; }
.mf-input:focus { outline:none;border-color:#6366f1;box-shadow:0 0 0 3px rgba(99,102,241,.1);background:#fff; }
.mf-mb { margin-bottom:1rem; }
.mf-grid { display:grid;grid-template-columns:1fr 1fr;gap:1rem; }
.option-row { display:flex;align-items:center;gap:.5rem;background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:.5rem .75rem;margin-bottom:.5rem; }
.option-row input { flex:1;border:none;background:transparent;font-size:.875rem; }
.option-row input:focus { outline:none; }
.opt-del { width:28px;height:28px;border:none;border-radius:6px;background:#fee2e2;color:#ef4444;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0; }
.toggle-switch { position:relative;display:inline-block;width:44px;height:24px;flex-shrink:0 }
.toggle-switch input { opacity:0;width:0;height:0 }
.toggle-slider { position:absolute;cursor:pointer;top:0;left:0;right:0;bottom:0;background:#e2e8f0;border-radius:999px;transition:.3s; }
.toggle-slider:before { content:'';position:absolute;width:18px;height:18px;border-radius:50%;left:3px;bottom:3px;background:#fff;transition:.3s;box-shadow:0 1px 4px rgba(0,0,0,.2); }
input:checked+.toggle-slider { background:#6366f1; }
input:checked+.toggle-slider:before { transform:translateX(20px); }
.mcheck-row { display:flex;align-items:center;justify-content:space-between;padding:.6rem 0;border-bottom:1px solid #f1f5f9; }
.mcheck-row:last-child { border-bottom:none; }
.empty-hero { text-align:center;padding:4rem 2rem;background:#fff;border-radius:16px;border:1px solid var(--border); }
</style>
@endpush

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

<div class="fields-header">
    <div>
        <div style="font-size:1.05rem;font-weight:800;color:#0f172a"><i class="fas fa-puzzle-piece me-2" style="color:#6366f1"></i>Özel Alan Tanımları</div>
        <div style="font-size:.8rem;color:#94a3b8;margin-top:2px">Müşterileriniz için acentenize özel alanlar oluşturun</div>
    </div>
    <div class="d-flex gap-2">
        <a href="{{ route('agency.customers.index') }}" class="btn btn-outline-secondary" style="border-radius:10px">
            <i class="fas fa-arrow-left me-1"></i>Müşteriler
        </a>
        <button class="btn text-white" style="background:linear-gradient(135deg,#6366f1,#8b5cf6);border-radius:10px" onclick="openCreateModal()">
            <i class="fas fa-plus me-1"></i>Yeni Alan
        </button>
    </div>
</div>

@if($definitions->isEmpty())
<div class="empty-hero">
    <div style="width:80px;height:80px;border-radius:20px;margin:0 auto 1.25rem;background:linear-gradient(135deg,#eef2ff,#ede9fe);display:flex;align-items:center;justify-content:center;font-size:2rem;color:#6366f1">
        <i class="fas fa-puzzle-piece"></i>
    </div>
    <h5 style="font-weight:800;color:#0f172a">Henüz özel alan yok</h5>
    <p style="color:#94a3b8;font-size:.875rem;max-width:400px;margin:.5rem auto 1.5rem">"Çocuk Sayısı", "Kan Grubu", "Vize Durumu" gibi özel alanlar tanımlayın.</p>
    <button class="btn text-white" style="background:linear-gradient(135deg,#6366f1,#8b5cf6);border-radius:10px" onclick="openCreateModal()">
        <i class="fas fa-plus me-1"></i>İlk Alanı Ekle
    </button>
</div>
@else
<div class="fields-grid">
    @foreach($definitions as $def)
    <div class="field-card {{ !$def->is_active ? 'inactive' : '' }}">
        <div class="field-card-stripe"></div>
        <div class="fc-body">
            <div class="fc-header">
                <div>
                    <div class="fc-label">{{ $def->label }}</div>
                    <span class="fc-key">{{ $def->field_key }}</span>
                </div>
                <div style="display:flex;align-items:center;gap:.5rem">
                    <span class="fc-type-badge">{{ $def->field_type_label }}</span>
                    <div class="fc-actions">
                        <button class="fc-btn edit" onclick="openEditModal({{ $def->id }}, '{{ addslashes(json_encode($def)) }}')"><i class="fas fa-pen"></i></button>
                        <button class="fc-btn toggle" onclick="toggleField({{ $def->id }})"><i class="fas fa-{{ $def->is_active ? 'eye' : 'eye-slash' }}"></i></button>
                        <button class="fc-btn del" onclick="deleteField({{ $def->id }}, '{{ addslashes($def->label) }}')"><i class="fas fa-trash"></i></button>
                    </div>
                </div>
            </div>
            @if($def->help_text)
                <div style="font-size:.78rem;color:#94a3b8;margin-top:.5rem">{{ $def->help_text }}</div>
            @endif
            <div class="fc-meta">
                <div class="fc-meta-item"><i class="fas fa-database"></i><span>{{ $def->values_count ?? 0 }} değer</span></div>
                @if($def->is_required) <div class="fc-meta-item" style="color:#ef4444"><i class="fas fa-asterisk"></i><span>Zorunlu</span></div> @endif
                @if($def->is_filterable) <div class="fc-meta-item" style="color:#6366f1"><i class="fas fa-filter"></i><span>Filtrelenebilir</span></div> @endif
                @if(!$def->is_active) <div class="fc-meta-item" style="color:#94a3b8"><i class="fas fa-eye-slash"></i><span>Pasif</span></div> @endif
            </div>
        </div>
    </div>
    @endforeach
</div>
@endif

</div>

{{-- MODAL --}}
<div class="modal fade" id="fieldModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header" style="border-bottom:1px solid #f1f5f9;padding:1.25rem 1.5rem">
                <h5 class="modal-title" id="modalTitle" style="font-weight:800"><i class="fas fa-plus-circle me-2" style="color:#6366f1"></i>Yeni Alan</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="fieldForm" method="POST">
                @csrf
                <input type="hidden" name="_method" id="formMethod" value="POST">
                <div class="modal-body" style="padding:1.5rem">
                    <div class="mf-grid mf-mb">
                        <div>
                            <label class="mf-label">Etiket *</label>
                            <input type="text" name="label" id="fLabel" class="mf-input" placeholder="Örn: Çocuk Sayısı" required oninput="autoKey()">
                        </div>
                        <div>
                            <label class="mf-label">Alan Anahtarı</label>
                            <input type="text" name="field_key" id="fKey" class="mf-input" placeholder="otomatik" pattern="[a-z0-9_]+" style="font-family:monospace">
                            <div style="font-size:.72rem;color:#94a3b8;margin-top:.25rem">Boş bırakırsanız otomatik oluşturulur</div>
                        </div>
                    </div>
                    <div class="mf-grid mf-mb">
                        <div>
                            <label class="mf-label">Alan Tipi *</label>
                            <select name="field_type" id="fType" class="mf-input" required onchange="onTypeChange(this.value)">
                                <option value="text">📝 Kısa Metin</option>
                                <option value="textarea">📄 Uzun Metin</option>
                                <option value="number">🔢 Tam Sayı</option>
                                <option value="decimal">🔣 Ondalık</option>
                                <option value="boolean">✅ Evet/Hayır</option>
                                <option value="date">📅 Tarih</option>
                                <option value="select">📋 Açılır Liste</option>
                                <option value="multiselect">☑️ Çoklu Seçim</option>
                                <option value="email">📧 E-posta</option>
                                <option value="phone">📞 Telefon</option>
                                <option value="url">🔗 URL</option>
                            </select>
                        </div>
                        <div>
                            <label class="mf-label">Varsayılan Değer</label>
                            <input type="text" name="default_value" id="fDefault" class="mf-input">
                        </div>
                    </div>

                    <div id="optionsSection" class="mf-mb" style="display:none">
                        <label class="mf-label">Seçenekler *</label>
                        <div id="optionsList"></div>
                        <button type="button" style="border:1px dashed #6366f1;color:#6366f1;border-radius:8px;background:transparent;width:100%;padding:.5rem;font-size:.85rem" onclick="addOption()">
                            <i class="fas fa-plus me-1"></i>Seçenek Ekle
                        </button>
                    </div>

                    <div class="mf-mb">
                        <label class="mf-label">Yardım Metni</label>
                        <input type="text" name="help_text" id="fHelp" class="mf-input" placeholder="Form altında görünür">
                    </div>

                    <div style="background:#f8fafc;border-radius:12px;padding:.75rem 1rem;border:1px solid #f1f5f9">
                        @foreach([
                            ['is_required','fieldRequired','Zorunlu Alan','asterisk','#ef4444'],
                            ['is_searchable','fieldSearchable','Aranabilir','search','#10b981'],
                            ['is_filterable','fieldFilterable','Filtrelenebilir','filter','#6366f1'],
                            ['is_visible_in_list','fieldVisible','Listede Göster','table','#8b5cf6'],
                        ] as [$name,$id,$label,$icon,$clr])
                        <div class="mcheck-row">
                            <span style="font-size:.84rem;font-weight:500;color:#0f172a">
                                <i class="fas fa-{{ $icon }} me-2" style="color:{{ $clr }}"></i>{{ $label }}
                            </span>
                            <label class="toggle-switch">
                                <input type="hidden" name="{{ $name }}" value="0">
                                <input type="checkbox" name="{{ $name }}" id="{{ $id }}" value="1">
                                <span class="toggle-slider"></span>
                            </label>
                        </div>
                        @endforeach
                    </div>
                </div>
                <div class="modal-footer" style="border-top:1px solid #f1f5f9;padding:1rem 1.5rem">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal" style="border-radius:10px">İptal</button>
                    <button type="submit" class="btn text-white" style="background:linear-gradient(135deg,#6366f1,#8b5cf6);border-radius:10px;min-width:120px">
                        <i class="fas fa-check me-1"></i>Kaydet
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<form id="deleteForm" method="POST" style="display:none">@csrf @method('DELETE')</form>
@endsection

@push('scripts')
<script>
let editingId = null, optN = 0;

function autoKey() {
    if (editingId) return;
    const v = document.getElementById('fLabel').value.toLowerCase()
        .replace(/[ğ]/g,'g').replace(/[ü]/g,'u').replace(/[ş]/g,'s')
        .replace(/[ı]/g,'i').replace(/[ö]/g,'o').replace(/[ç]/g,'c')
        .replace(/[^a-z0-9]+/g,'_').replace(/^_+|_+$/g,'');
    document.getElementById('fKey').value = v;
}

function onTypeChange(t) {
    document.getElementById('optionsSection').style.display =
        ['select','multiselect'].includes(t) ? '' : 'none';
}

function addOption(val='', lbl='') {
    optN++;
    const d = document.createElement('div');
    d.className = 'option-row';
    d.innerHTML = `<input type="text" name="options[${optN}][value]" value="${val}" placeholder="Değer" required>
                   <span style="color:#cbd5e1">|</span>
                   <input type="text" name="options[${optN}][label]" value="${lbl}" placeholder="Etiket">
                   <button type="button" class="opt-del" onclick="this.closest('.option-row').remove()"><i class="fas fa-times"></i></button>`;
    document.getElementById('optionsList').appendChild(d);
}

function resetModal() {
    ['fLabel','fKey','fDefault','fHelp'].forEach(id => { const e=document.getElementById(id); if(e) e.value=''; });
    document.getElementById('fType').value = 'text';
    ['fieldRequired','fieldSearchable','fieldFilterable','fieldVisible'].forEach(id => { document.getElementById(id).checked = false; });
    document.getElementById('optionsList').innerHTML = '';
    document.getElementById('optionsSection').style.display = 'none';
    optN = 0;
}

function openCreateModal() {
    editingId = null;
    resetModal();
    document.getElementById('modalTitle').innerHTML = '<i class="fas fa-plus-circle me-2" style="color:#6366f1"></i>Yeni Alan';
    document.getElementById('fieldForm').action = '{{ route("agency.customers.fields.store") }}';
    document.getElementById('formMethod').value = 'POST';
    new bootstrap.Modal(document.getElementById('fieldModal')).show();
}

function openEditModal(id, raw) {
    editingId = id;
    resetModal();
    const data = JSON.parse(raw);
    document.getElementById('modalTitle').innerHTML = '<i class="fas fa-pen me-2" style="color:#6366f1"></i>Alanı Düzenle';
    document.getElementById('fieldForm').action = `/agency/customer-fields/${id}`;
    document.getElementById('formMethod').value = 'PUT';
    document.getElementById('fLabel').value   = data.label || '';
    document.getElementById('fKey').value     = data.field_key || '';
    document.getElementById('fType').value    = data.field_type || 'text';
    document.getElementById('fDefault').value = data.default_value || '';
    document.getElementById('fHelp').value    = data.help_text || '';
    document.getElementById('fieldRequired').checked   = !!data.is_required;
    document.getElementById('fieldSearchable').checked = !!data.is_searchable;
    document.getElementById('fieldFilterable').checked = !!data.is_filterable;
    document.getElementById('fieldVisible').checked    = !!data.is_visible_in_list;
    onTypeChange(data.field_type);
    if (data.options) {
        (Array.isArray(data.options) ? data.options : Object.values(data.options))
            .forEach(o => addOption(o.value||'', o.label||''));
    }
    new bootstrap.Modal(document.getElementById('fieldModal')).show();
}

function toggleField(id) {
    fetch(`/agency/customer-fields/${id}/toggle`, {
        method:'POST', headers:{'X-CSRF-TOKEN':'{{ csrf_token() }}'}
    }).then(() => location.reload());
}

function deleteField(id, label) {
    if (!confirm(`"${label}" alanını silmek isteniyor. Emin misiniz?`)) return;
    const f = document.getElementById('deleteForm');
    f.action = `/agency/customer-fields/${id}`;
    f.submit();
}
</script>
@endpush
