@extends('agency.layouts.app')

@section('title', 'Ekstra Hizmetler')
@section('page_title', 'Ekstra Hizmetler')

@php
    $breadcrumbs = [
        ['title' => 'Ana Sayfa', 'url' => route('agency.dashboard')],
        ['title' => 'Ürünler', 'url' => '#'],
        ['title' => 'Ekstra Hizmetler', 'url' => ''],
    ];

    // Liste kategoriye göre gruplanır; kategorisizler her zaman en sonda toplanır
    $grouped = $services->groupBy(fn ($s) => $s->category_id ?? 0);
    $orderedGroups = collect();
    foreach ($categories as $cat) {
        if ($grouped->has($cat->id)) {
            $orderedGroups->push(['category' => $cat, 'items' => $grouped[$cat->id]]);
        }
    }
    if ($grouped->has(0)) {
        $orderedGroups->push(['category' => null, 'items' => $grouped[0]]);
    }

    $currencyOptions = $currencies->pluck('code')->all() ?: ['TRY'];
    $defaultCurrency = $currencies->firstWhere('is_base', true)?->code ?? ($currencyOptions[0] ?? 'TRY');

    // Inline düzenleme seçenekleri (quick-view motoru [{value,label}] bekler)
    $taxOptions = collect([['value' => '', 'label' => 'Vergisiz']])
        ->merge($taxRates->map(fn ($t) => [
            'value' => (string) (float) $t->rate,
            'label' => $t->name . ' %' . rtrim(rtrim(number_format((float) $t->rate, 2, ',', '.'), '0'), ','),
        ]))->values();

    $unitOptions = collect([['value' => '', 'label' => 'Birimsiz']])
        ->merge(collect($units)->map(fn ($l, $v) => ['value' => $v, 'label' => $l])->values())->values();

    $currencyInlineOptions = collect($currencyOptions)->map(fn ($c) => ['value' => $c, 'label' => $c])->values();

    $ufBase = 'agency.products.extra-services';
@endphp

@push('styles')
<style>
    /* ══════════════════════════════════════════════════════════════
       EKSTRA HİZMETLER — "fiyat cetveli" arayüzü
       Solda kategori rayı, sağda gruplanmış hizmet satırları.
       Fiyatlar tabular-nums ile hizalanır; satırlar ince çizgi ritminde.
       ══════════════════════════════════════════════════════════════ */

    .es-page { --es-ink:#0f172a; --es-mute:#94a3b8; --es-line:#eef2f7; --es-accent:#4f46e5; --es-money:#047857;
        font-feature-settings:"cv02","cv03","cv04"; }

    /* ── Başlık ── */
    .es-head { display:flex; align-items:center; justify-content:space-between; gap:1.5rem; flex-wrap:wrap;
        padding:1.4rem 1.6rem; margin-bottom:1.15rem; border-radius:20px; position:relative; overflow:hidden;
        background:linear-gradient(120deg,#111827 0%,#1e1b4b 55%,#312e81 100%); color:#fff;
        box-shadow:0 18px 40px -22px rgba(30,27,75,.75); }
    .es-head::after { content:''; position:absolute; inset:0; pointer-events:none; opacity:.5;
        background:radial-gradient(720px 180px at 88% -30%, rgba(129,140,248,.42), transparent 70%); }
    .es-head > * { position:relative; z-index:1; }
    .es-head-id { display:flex; align-items:center; gap:1rem; min-width:0; }
    .es-head-ic { width:52px; height:52px; flex:none; border-radius:16px; display:grid; place-items:center; font-size:1.25rem;
        background:rgba(255,255,255,.1); border:1px solid rgba(255,255,255,.16); color:#c7d2fe;
        backdrop-filter:blur(6px); }
    .es-head h1 { font-size:1.4rem; font-weight:800; letter-spacing:-.03em; margin:0; }
    .es-head p { margin:.15rem 0 0; font-size:.82rem; color:rgba(226,232,240,.72); }

    .es-stats { display:flex; align-items:stretch; gap:0; margin-left:auto; }
    .es-stat { padding:0 1.25rem; text-align:right; border-left:1px solid rgba(255,255,255,.12); }
    .es-stat:first-child { border-left:none; }
    .es-stat b { display:block; font-size:1.4rem; font-weight:800; letter-spacing:-.03em; line-height:1.1;
        font-variant-numeric:tabular-nums; }
    .es-stat span { font-size:.63rem; font-weight:700; text-transform:uppercase; letter-spacing:.09em; color:rgba(199,210,254,.7); }

    .es-cta { display:inline-flex; align-items:center; gap:.55rem; border:none; cursor:pointer;
        background:#fff; color:#312e81; font-size:.85rem; font-weight:750; padding:.72rem 1.25rem; border-radius:13px;
        box-shadow:0 10px 24px -12px rgba(0,0,0,.6); transition:transform .16s cubic-bezier(.34,1.4,.6,1), box-shadow .16s; }
    .es-cta:hover { transform:translateY(-2px); box-shadow:0 16px 30px -14px rgba(0,0,0,.65); }
    .es-cta i { transition:transform .25s; }
    .es-cta.is-open i { transform:rotate(135deg); }

    /* ── Kapsam uyarısı ── */
    .es-notice { display:flex; gap:.85rem; align-items:flex-start; margin-bottom:1.15rem; padding:.95rem 1.15rem;
        border-radius:16px; background:linear-gradient(100deg,#faf5ff,#f5f3ff 55%,#eef2ff);
        border:1px solid #e9d5ff; box-shadow:0 1px 3px rgba(109,40,217,.05); }
    .es-notice-ic { flex:none; width:32px; height:32px; border-radius:10px; display:grid; place-items:center;
        font-size:.85rem; color:#fff; background:linear-gradient(135deg,#8b5cf6,#6d28d9);
        box-shadow:0 6px 14px -6px rgba(109,40,217,.65); }
    .es-notice-txt { font-size:.83rem; line-height:1.65; color:#5b4a80; }
    .es-notice-txt b { color:#4c1d95; font-weight:800; }
    .es-notice-txt strong { color:#5b21b6; font-weight:750; }
    .es-notice-txt em { font-style:normal; font-weight:700; color:#6d28d9;
        background:#ede9fe; border-radius:6px; padding:.05rem .4rem; }
    .es-notice-sub { display:block; margin-top:.3rem; font-size:.78rem; color:#8b7aa8; }
    .es-notice-sub b { color:#6d28d9; font-weight:750; }

    /* ── Gövde: ray + içerik ── */
    .es-body { display:grid; grid-template-columns:246px minmax(0,1fr); gap:1.15rem; align-items:start; }
    @media (max-width:991px){ .es-body { grid-template-columns:1fr; } }

    /* ── Kategori rayı ── */
    .es-rail { position:sticky; top:14px; background:#fff; border:1px solid var(--es-line); border-radius:18px;
        padding:.75rem; box-shadow:0 1px 3px rgba(15,23,42,.04); }
    .es-rail-h { display:flex; align-items:center; justify-content:space-between; padding:.35rem .55rem .6rem;
        font-size:.66rem; font-weight:800; letter-spacing:.1em; text-transform:uppercase; color:var(--es-mute); }
    .es-cat { position:relative; display:flex; align-items:center; gap:.6rem; width:100%; padding:.55rem .65rem;
        border-radius:11px; font-size:.85rem; font-weight:600; color:#475569; text-decoration:none; transition:.14s; }
    .es-cat:hover { background:#f6f7fb; color:var(--es-ink); }
    .es-cat.on { background:linear-gradient(135deg,#eef2ff,#f5f3ff); color:#3730a3; font-weight:750;
        box-shadow:inset 0 0 0 1px #ddd6fe; }
    .es-cat.on::before { content:''; position:absolute; left:0; top:50%; transform:translateY(-50%);
        width:3px; height:18px; border-radius:0 3px 3px 0; background:linear-gradient(180deg,#6366f1,#8b5cf6); }
    .es-dot { width:9px; height:9px; flex:none; border-radius:50%; background:var(--c,#cbd5e1); box-shadow:0 0 0 3px color-mix(in srgb, var(--c,#cbd5e1) 18%, transparent); }
    .es-cat-name { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;
        color:inherit; text-decoration:none; }
    .es-cat-n { font-size:.72rem; font-weight:750; color:#94a3b8; font-variant-numeric:tabular-nums; }
    .es-cat.on .es-cat-n { color:#6366f1; }
    .es-cat-act { display:none; gap:2px; }
    .es-cat:hover .es-cat-act { display:inline-flex; }
    .es-cat:hover .es-cat-n { display:none; }
    .es-cat-act button { width:22px; height:22px; display:grid; place-items:center; border:none; background:transparent;
        border-radius:6px; color:#94a3b8; font-size:.68rem; cursor:pointer; transition:.13s; }
    .es-cat-act button:hover { background:#e0e7ff; color:#4338ca; }
    .es-cat-act button.del:hover { background:#fee2e2; color:#dc2626; }
    .es-rail-sep { height:1px; background:var(--es-line); margin:.5rem .3rem; }

    .es-catadd { display:flex; gap:.35rem; padding:.3rem; }
    .es-catadd input { flex:1; min-width:0; border:1.5px dashed #dbe1ec; background:#fbfcfe; border-radius:10px;
        padding:.5rem .65rem; font-size:.8rem; color:var(--es-ink); transition:.14s; }
    .es-catadd input:focus { outline:none; border-style:solid; border-color:var(--es-accent); background:#fff;
        box-shadow:0 0 0 3px rgba(79,70,229,.1); }
    .es-catadd button { width:34px; flex:none; border:none; border-radius:10px; cursor:pointer; color:#fff;
        background:linear-gradient(135deg,#4f46e5,#6d28d9); font-size:.78rem; transition:.15s; }
    .es-catadd button:hover { filter:brightness(1.08); }

    /* ── Araç çubuğu ── */
    .es-tools { display:flex; align-items:center; gap:.6rem; flex-wrap:wrap; margin-bottom:.9rem; }
    .es-search { position:relative; flex:1; min-width:220px; }
    .es-search i { position:absolute; left:.9rem; top:50%; transform:translateY(-50%); color:#a5aec2; font-size:.8rem; }
    .es-search input { width:100%; border:1px solid var(--es-line); background:#fff; border-radius:13px;
        padding:.68rem .9rem .68rem 2.3rem; font-size:.86rem; color:var(--es-ink); transition:.15s; }
    .es-search input:focus { outline:none; border-color:#c7d2fe; box-shadow:0 0 0 3px rgba(79,70,229,.09); }
    .es-seg { display:inline-flex; background:#fff; border:1px solid var(--es-line); border-radius:12px; padding:3px; }
    .es-seg a { padding:.42rem .85rem; border-radius:9px; font-size:.78rem; font-weight:700; color:#64748b;
        text-decoration:none; transition:.14s; }
    .es-seg a:hover { color:var(--es-ink); }
    .es-seg a.on { background:var(--es-ink); color:#fff; }

    /* ── Hızlı ekleme paneli ── */
    .es-add { display:none; background:#fff; border:1px solid #ddd6fe; border-radius:18px; padding:1.05rem 1.15rem;
        margin-bottom:1rem; box-shadow:0 14px 34px -24px rgba(79,70,229,.6); }
    .es-add.open { display:block; animation:esDrop .24s cubic-bezier(.2,.8,.3,1); }
    @keyframes esDrop { from { opacity:0; transform:translateY(-8px); } to { opacity:1; transform:none; } }
    .es-add-t { font-size:.68rem; font-weight:800; letter-spacing:.09em; text-transform:uppercase; color:#6d28d9;
        margin-bottom:.8rem; display:flex; align-items:center; gap:.45rem; }
    .es-add-grid { display:grid; grid-template-columns:1.1fr 1.9fr .85fr .7fr .9fr 1.05fr auto; gap:.6rem; align-items:end; }
    @media (max-width:1200px){ .es-add-grid { grid-template-columns:repeat(3,1fr); } }
    @media (max-width:640px){ .es-add-grid { grid-template-columns:1fr 1fr; } }
    .es-f { display:flex; flex-direction:column; gap:.3rem; min-width:0; }
    .es-f > label { font-size:.66rem; font-weight:750; text-transform:uppercase; letter-spacing:.05em; color:#94a3b8; }
    .es-f input, .es-f select { width:100%; border:1.5px solid #e6eaf2; background:#fbfcfe; border-radius:10px;
        padding:.55rem .7rem; font-size:.85rem; color:var(--es-ink); transition:.14s; }
    .es-f input:focus, .es-f select:focus { outline:none; border-color:var(--es-accent); background:#fff;
        box-shadow:0 0 0 3px rgba(79,70,229,.1); }
    .es-f input[type="number"] { font-variant-numeric:tabular-nums; text-align:right; }
    .es-add-btn { display:inline-flex; align-items:center; gap:.45rem; border:none; cursor:pointer; white-space:nowrap;
        background:linear-gradient(135deg,#4f46e5,#7c3aed); color:#fff; font-size:.84rem; font-weight:750;
        padding:.62rem 1.1rem; border-radius:11px; transition:.16s; box-shadow:0 8px 18px -10px rgba(79,70,229,.9); }
    .es-add-btn:hover { transform:translateY(-1px); filter:brightness(1.06); }
    .es-add-btn:disabled { opacity:.6; cursor:default; transform:none; }
    .es-add-hint { margin:.7rem 0 0; font-size:.74rem; color:#94a3b8; }

    /* ── Gruplar ── */
    .es-group { background:#fff; border:1px solid var(--es-line); border-radius:18px; margin-bottom:.95rem;
        overflow:hidden; box-shadow:0 1px 3px rgba(15,23,42,.035); }
    .es-group-h { display:flex; align-items:center; gap:.6rem; padding:.72rem 1.1rem; background:#fbfcfe;
        border-bottom:1px solid var(--es-line); }
    .es-group-h b { font-size:.83rem; font-weight:800; color:var(--es-ink); letter-spacing:-.01em; }
    .es-group-h .n { margin-left:auto; font-size:.7rem; font-weight:750; color:#94a3b8; background:#fff;
        border:1px solid var(--es-line); border-radius:999px; padding:.15rem .6rem; font-variant-numeric:tabular-nums; }

    /* ── Satır ── */
    .es-row { display:grid; grid-template-columns:46px minmax(0,1fr) 132px 118px 150px 104px; gap:.85rem;
        align-items:center; padding:.72rem 1.1rem; border-bottom:1px solid var(--es-line);
        transition:background .13s; animation:esIn .32s both; animation-delay:calc(var(--i,0) * 22ms); }
    @keyframes esIn { from { opacity:0; transform:translateY(5px); } to { opacity:1; transform:none; } }
    .es-row:last-child { border-bottom:none; }
    .es-row:hover { background:#fafbff; }
    .es-row.off { opacity:.5; }
    @media (max-width:900px){
        .es-row { grid-template-columns:minmax(0,1fr) auto; row-gap:.5rem; }
        .es-row > .es-code, .es-row > .es-gross { display:none; }
    }

    .es-code { font-size:.7rem; font-weight:750; color:#c0c8d8; font-variant-numeric:tabular-nums;
        background:#f7f9fc; border-radius:7px; padding:.22rem 0; text-align:center; }
    .es-name { font-size:.92rem; font-weight:650; color:var(--es-ink); letter-spacing:-.01em; }
    .es-sub { display:flex; align-items:center; gap:.4rem; margin-top:.18rem; flex-wrap:wrap; }
    .es-chip { font-size:.68rem; font-weight:700; color:#64748b; background:#f1f5f9; border-radius:6px; padding:.1rem .45rem; }
    .es-desc { font-size:.72rem; color:#a3adc0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; max-width:340px; }

    .es-catsel { width:100%; border:1px solid transparent; background:transparent; border-radius:8px; cursor:pointer;
        padding:.28rem .4rem; font-size:.76rem; font-weight:650; color:#64748b; transition:.14s; }
    .es-catsel:hover { background:#f1f5f9; border-color:#e2e8f0; }
    .es-catsel:focus { outline:none; background:#fff; border-color:var(--es-accent); box-shadow:0 0 0 3px rgba(79,70,229,.1); }

    .es-taxcell .inline-editable { display:inline-flex; align-items:center; font-size:.72rem; font-weight:750;
        border-radius:7px; padding:.24rem .6rem; }
    .es-taxcell.taxed .inline-editable { background:#fff7ed; color:#9a3412; box-shadow:inset 0 0 0 1px #fed7aa; }
    .es-taxcell.free .inline-editable { color:#94a3b8; box-shadow:inset 0 0 0 1px #e2e8f0; border-style:dashed; }

    .es-pricecell { text-align:right; }
    .es-price { font-size:1rem; font-weight:800; color:var(--es-money); letter-spacing:-.02em;
        font-variant-numeric:tabular-nums; }
    .es-cur { font-size:.7rem; font-weight:750; color:#94a3b8; margin-left:.25rem; }
    .es-gross { display:block; margin-top:.1rem; font-size:.68rem; color:#a3adc0; font-variant-numeric:tabular-nums; }

    .es-acts { display:flex; justify-content:flex-end; gap:.3rem; }
    .es-ib { width:29px; height:29px; display:grid; place-items:center; border-radius:9px; cursor:pointer;
        border:1px solid var(--es-line); background:#fff; color:#94a3b8; font-size:.74rem; transition:.14s; }
    .es-ib:hover { border-color:#c7d2fe; color:var(--es-accent); background:#eef2ff; }
    .es-ib.on { color:#059669; border-color:#a7f3d0; background:#ecfdf5; }
    .es-ib.del:hover { border-color:#fecaca; color:#dc2626; background:#fef2f2; }

    /* ── Boş durum ── */
    .es-empty { background:#fff; border:1px dashed #dbe1ec; border-radius:20px; padding:3.5rem 1.5rem; text-align:center; }
    .es-empty-ic { width:64px; height:64px; margin:0 auto 1rem; border-radius:20px; display:grid; place-items:center;
        font-size:1.5rem; color:#818cf8; background:linear-gradient(135deg,#eef2ff,#f5f3ff); }
    .es-empty h4 { font-size:1.05rem; font-weight:800; color:var(--es-ink); margin-bottom:.35rem; }
    .es-empty p { font-size:.85rem; color:#94a3b8; max-width:430px; margin:0 auto; }
    .es-empty-eg { display:inline-flex; flex-wrap:wrap; gap:.4rem; justify-content:center; margin-top:1.1rem; }
    .es-empty-eg span { font-size:.72rem; font-weight:650; color:#6366f1; background:#eef2ff; border-radius:999px; padding:.3rem .8rem; }
</style>
@endpush

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

    {{-- ══ Başlık ══ --}}
    <div class="es-head">
        <div class="es-head-id">
            <div class="es-head-ic"><i class="fas fa-tags"></i></div>
            <div>
                <h1>Ekstra Hizmetler</h1>
                <p>Tur ve ürünlerden bağımsız hizmet kalemleri — satışa ek olarak eklenir</p>
            </div>
        </div>

        <div class="es-stats">
            <div class="es-stat"><b>{{ $stats['total'] }}</b><span>Hizmet</span></div>
            <div class="es-stat"><b>{{ $stats['active'] }}</b><span>Aktif</span></div>
            <div class="es-stat"><b>{{ $stats['categories'] }}</b><span>Kategori</span></div>
        </div>

        <button type="button" class="es-cta" id="esAddToggle">
            <i class="fas fa-plus"></i> Yeni Hizmet
        </button>
    </div>

    {{-- ══ Kapsam uyarısı ══
         Bu modül diğer ürün tipleri gibi görünüyor ama bir satış kanalı değil;
         karışıklığı önlemek için nerede çıkıp nerede çıkmadığı burada yazılı. --}}
    <div class="es-notice">
        <span class="es-notice-ic"><i class="fas fa-circle-info"></i></span>
        <div class="es-notice-txt">
            <b>Ekstra hizmetler bir satış kanalı değildir.</b>
            Buradaki kalemler tek başına satılmaz; <strong>mevcut bir satışın üzerine ek kalem</strong> olarak eklenir
            (satış kartı → <em>Ürün &amp; Hizmet Kataloğu</em> → <em>Ekstra Hizmetler</em> sekmesi).
            <span class="es-notice-sub">
                Bu nedenle <b>Yeni Satış Oluştur</b> ekranında satış kanalı olarak,
                satış/fatura filtrelerinde ve <b>satış hedeflerinde</b> görünmezler.
            </span>
        </div>
    </div>

    <div class="es-body">

        {{-- ══ Kategori rayı ══ --}}
        <aside class="es-rail">
            <div class="es-rail-h"><span>Kategoriler</span></div>

            @php $qs = fn ($c) => request()->fullUrlWithQuery(['category' => $c]); @endphp

            <a href="{{ $qs(null) }}" class="es-cat {{ $activeCategory === null ? 'on' : '' }}">
                <span class="es-dot" style="--c:#6366f1"></span>
                <span class="es-cat-name">Tümü</span>
                <span class="es-cat-n">{{ $stats['total'] }}</span>
            </a>
            <a href="{{ $qs('uncategorized') }}" class="es-cat {{ $activeCategory === 'uncategorized' ? 'on' : '' }}">
                <span class="es-dot" style="--c:#cbd5e1"></span>
                <span class="es-cat-name">Kategorisiz</span>
                <span class="es-cat-n">{{ $counts[null] ?? 0 }}</span>
            </a>

            @if($categories->count())
                <div class="es-rail-sep"></div>
            @endif

            @foreach($categories as $cat)
                <div class="es-cat {{ (string) $activeCategory === (string) $cat->id ? 'on' : '' }}">
                    <span class="es-dot" style="--c:{{ $cat->color_code ?: '#8b5cf6' }}"></span>
                    <a class="es-cat-name" href="{{ $qs($cat->id) }}" title="{{ $cat->name }}">{{ $cat->name }}</a>
                    <span class="es-cat-n">{{ $counts[$cat->id] ?? 0 }}</span>
                    <span class="es-cat-act">
                        <button type="button" title="Yeniden adlandır"
                                onclick="esRenameCategory({{ $cat->id }}, @js($cat->name))"><i class="fas fa-pen"></i></button>
                        <button type="button" class="del" title="Sil"
                                onclick="esDeleteCategory({{ $cat->id }}, @js($cat->name))"><i class="fas fa-trash"></i></button>
                    </span>
                </div>
            @endforeach

            <div class="es-rail-sep"></div>

            <form class="es-catadd" onsubmit="return esCreateCategory(event)">
                <input type="text" name="name" placeholder="Yeni kategori…" maxlength="255" autocomplete="off" required>
                <button type="submit" title="Kategori ekle"><i class="fas fa-plus"></i></button>
            </form>
        </aside>

        {{-- ══ İçerik ══ --}}
        <main class="es-main">

            {{-- Araç çubuğu --}}
            <form method="GET" class="es-tools">
                @if($activeCategory !== null)<input type="hidden" name="category" value="{{ $activeCategory }}">@endif
                <div class="es-search">
                    <i class="fas fa-magnifying-glass"></i>
                    <input type="text" name="search" value="{{ request('search') }}"
                           placeholder="Hizmet adı, kod veya açıklama ara…" autocomplete="off">
                </div>
                <div class="es-seg">
                    <a href="{{ request()->fullUrlWithQuery(['status' => null]) }}" class="{{ !request('status') ? 'on' : '' }}">Tümü</a>
                    <a href="{{ request()->fullUrlWithQuery(['status' => 'active']) }}" class="{{ request('status') === 'active' ? 'on' : '' }}">Aktif</a>
                    <a href="{{ request()->fullUrlWithQuery(['status' => 'inactive']) }}" class="{{ request('status') === 'inactive' ? 'on' : '' }}">Pasif</a>
                </div>
            </form>

            {{-- Hızlı ekleme --}}
            <form class="es-add" id="esAddForm" onsubmit="return esCreateService(event)">
                <div class="es-add-t"><i class="fas fa-bolt"></i> Hızlı Ekle</div>
                <div class="es-add-grid">
                    <div class="es-f">
                        <label>Kategori</label>
                        <select name="category_id">
                            <option value="">Kategorisiz</option>
                            @foreach($categories as $cat)
                                <option value="{{ $cat->id }}" @selected((string) $activeCategory === (string) $cat->id)>{{ $cat->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="es-f">
                        <label>Hizmet Adı</label>
                        <input type="text" name="name" placeholder="Örn: VQ Alan Vergisi" maxlength="255" required>
                    </div>
                    <div class="es-f">
                        <label>Fiyat</label>
                        <input type="number" name="price" step="0.01" min="0" value="0" required>
                    </div>
                    <div class="es-f">
                        <label>Para Birimi</label>
                        <select name="currency">
                            @foreach($currencyOptions as $code)
                                <option value="{{ $code }}" @selected($code === $defaultCurrency)>{{ $code }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="es-f">
                        <label>Birim</label>
                        <select name="unit">
                            <option value="">Birimsiz</option>
                            @foreach($units as $key => $label)
                                <option value="{{ $key }}">{{ $label }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="es-f">
                        <label>Vergi</label>
                        <select name="tax_rate">
                            <option value="">Vergisiz</option>
                            @foreach($taxRates as $tr)
                                <option value="{{ (float) $tr->rate }}">{{ $tr->name }} %{{ rtrim(rtrim(number_format((float) $tr->rate, 2, ',', '.'), '0'), ',') }}</option>
                            @endforeach
                        </select>
                    </div>
                    <button type="submit" class="es-add-btn"><i class="fas fa-check"></i> Ekle</button>
                </div>
                <p class="es-add-hint">
                    <i class="fas fa-circle-info"></i>
                    Vergi seçmezseniz hizmet vergisiz kaydedilir. Açıklama, vergiye dahil mi gibi ayrıntıları
                    ekledikten sonra satıra tıklayarak düzenleyebilirsiniz.
                </p>
            </form>

            {{-- Liste --}}
            @forelse($orderedGroups as $group)
                @php $cat = $group['category']; @endphp
                <section class="es-group">
                    <div class="es-group-h">
                        <span class="es-dot" style="--c:{{ $cat?->color_code ?: ($cat ? '#8b5cf6' : '#cbd5e1') }}"></span>
                        <b>{{ $cat?->name ?? 'Kategorisiz' }}</b>
                        <span class="n">{{ $group['items']->count() }}</span>
                    </div>

                    @foreach($group['items'] as $service)
                        @php
                            $uf = route("$ufBase.update-field", $service);
                            $showGross = $service->tax_rate !== null && !$service->tax_included;
                        @endphp
                        <div class="es-row {{ $service->is_active ? '' : 'off' }}" data-es-row="{{ $service->id }}"
                             data-es-tax-included="{{ $service->tax_included ? '1' : '0' }}" style="--i:{{ $loop->index }}">

                            <span class="es-code">#{{ $service->code ?? '—' }}</span>

                            <div>
                                <div class="es-name inline-editable"
                                     data-id="{{ $service->id }}" data-url="{{ $uf }}" data-field="name" data-type="text"
                                     title="Adı düzenlemek için tıklayın">{{ $service->name }}</div>
                                <div class="es-sub">
                                    <span class="es-chip inline-editable"
                                          data-id="{{ $service->id }}" data-url="{{ $uf }}" data-field="unit" data-type="select"
                                          data-options='@json($unitOptions)' data-value="{{ $service->unit }}"
                                          title="Fiyat birimi">{{ $service->unit_label ?? 'Birimsiz' }}</span>
                                    @if($service->tax_included && $service->tax_rate !== null)
                                        <span class="es-chip" style="background:#ecfdf5;color:#047857">Vergi dahil</span>
                                    @endif
                                    @if($service->description)
                                        <span class="es-desc">{{ $service->description }}</span>
                                    @endif
                                </div>
                            </div>

                            <div>
                                <select class="es-catsel" data-es-cat="{{ $uf }}" title="Kategori">
                                    <option value="" @selected(!$service->category_id)>Kategorisiz</option>
                                    @foreach($categories as $c)
                                        <option value="{{ $c->id }}" @selected($service->category_id === $c->id)>{{ $c->name }}</option>
                                    @endforeach
                                </select>
                            </div>

                            <div class="es-taxcell {{ $service->tax_rate === null ? 'free' : 'taxed' }}">
                                <span class="inline-editable"
                                      data-id="{{ $service->id }}" data-url="{{ $uf }}" data-field="tax_rate" data-type="select"
                                      data-options='@json($taxOptions)' data-value="{{ $service->tax_rate !== null ? (float) $service->tax_rate : '' }}"
                                      title="Vergi oranı">{{ $service->tax_label }}</span>
                            </div>

                            <div class="es-pricecell">
                                <span class="es-price inline-editable"
                                      data-id="{{ $service->id }}" data-url="{{ $uf }}" data-field="price" data-type="number"
                                      data-value="{{ $service->price }}"
                                      title="Fiyatı düzenlemek için tıklayın">{{ number_format((float) $service->price, 2, ',', '.') }}</span>
                                <span class="es-cur inline-editable"
                                      data-id="{{ $service->id }}" data-url="{{ $uf }}" data-field="currency" data-type="select"
                                      data-options='@json($currencyInlineOptions)' data-value="{{ $service->currency }}"
                                      title="Para birimi">{{ $service->currency }}</span>
                                {{-- Satır içi düzenleme sonrası JS ile tazelenir; bu yüzden koşulsuz basılır --}}
                                <span class="es-gross">{{ $showGross ? 'Brüt ' . number_format($service->gross_price, 2, ',', '.') : '' }}</span>
                            </div>

                            <div class="es-acts">
                                <button type="button" class="es-ib" title="Ayrıntılar"
                                        onclick="openQuickView('{{ route("$ufBase.quick-view", $service) }}')"><i class="fas fa-up-right-and-down-left-from-center"></i></button>
                                <button type="button" class="es-ib {{ $service->is_active ? 'on' : '' }}"
                                        title="{{ $service->is_active ? 'Pasif et' : 'Aktif et' }}"
                                        onclick="esToggle({{ $service->id }}, '{{ route("$ufBase.toggle-status", $service) }}', this)">
                                    <i class="fas {{ $service->is_active ? 'fa-toggle-on' : 'fa-toggle-off' }}"></i>
                                </button>
                                <button type="button" class="es-ib del" title="Sil"
                                        onclick="esDelete({{ $service->id }}, @js($service->name), '{{ route("$ufBase.destroy", $service) }}')"><i class="fas fa-trash"></i></button>
                            </div>
                        </div>
                    @endforeach
                </section>
            @empty
                <div class="es-empty">
                    <div class="es-empty-ic"><i class="fas fa-tags"></i></div>
                    @if(request('search') || request('status') || $activeCategory !== null)
                        <h4>Bu filtreye uyan hizmet yok</h4>
                        <p>Arama veya kategori filtresini değiştirip yeniden deneyin.</p>
                    @else
                        <h4>Henüz ekstra hizmet tanımlamadınız</h4>
                        <p>Satışlara ek olarak eklediğiniz küçük hizmet kalemlerini burada tanımlayın.
                           İsterseniz kategorilere ayırın, isterseniz kategorisiz bırakın.</p>
                        <div class="es-empty-eg">
                            <span>VQ Alan Vergisi</span><span>Vize Harcı</span><span>Ekstra Bagaj</span>
                            <span>Öğle Yemeği</span><span>Rehberlik Ücreti</span>
                        </div>
                    @endif
                </div>
            @endforelse
        </main>
    </div>
</div>
@endsection

@push('scripts')
<script>
(function () {
    const ROUTES = {
        store: @js(route("$ufBase.store")),
        catStore: @js(route("$ufBase.categories.store")),
        catUpdate: @js(route("$ufBase.categories.update", ['category' => '__ID__'])),
        catDestroy: @js(route("$ufBase.categories.destroy", ['category' => '__ID__'])),
    };
    const csrf = () => document.querySelector('meta[name="csrf-token"]').content;

    function toast(msg, icon = 'success') {
        if (typeof Swal === 'undefined') return;
        Swal.mixin({ toast: true, position: 'top-end', showConfirmButton: false, timer: 2200, timerProgressBar: true })
            .fire({ icon, title: msg });
    }

    function send(url, method, body) {
        return fetch(url, {
            method,
            headers: { 'X-CSRF-TOKEN': csrf(), 'Content-Type': 'application/json', 'Accept': 'application/json' },
            body: body ? JSON.stringify(body) : undefined,
        }).then(async r => {
            let d = {};
            try { d = await r.json(); } catch (e) {}
            return { ok: r.ok, data: d };
        });
    }

    // ── Hızlı ekleme panelini aç/kapa ──
    const toggleBtn = document.getElementById('esAddToggle');
    const addForm = document.getElementById('esAddForm');
    toggleBtn?.addEventListener('click', () => {
        addForm.classList.toggle('open');
        toggleBtn.classList.toggle('is-open', addForm.classList.contains('open'));
        if (addForm.classList.contains('open')) addForm.querySelector('[name="name"]').focus();
    });

    // ── Hizmet ekle ──
    window.esCreateService = function (e) {
        e.preventDefault();
        const form = e.target;
        const btn = form.querySelector('[type="submit"]');
        const data = Object.fromEntries(new FormData(form).entries());
        btn.disabled = true;
        const orig = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';

        send(ROUTES.store, 'POST', data).then(res => {
            if (res.ok && res.data.success) {
                toast(res.data.message || 'Eklendi');
                location.reload();
            } else {
                const msg = res.data.errors ? Object.values(res.data.errors).flat().join(' ') : (res.data.message || 'Eklenemedi');
                toast(msg, 'error');
                btn.disabled = false;
                btn.innerHTML = orig;
            }
        });
        return false;
    };

    // ── Satır içi düzenleme sonrası türetilen değerleri tazele ──
    // Inline motoru (quick-view-drawer) kaydettiğinde hücrenin data-value'sunu
    // günceller; bunu izleyip brüt tutarı ve vergi rozetini yeniden hesaplarız
    // — sayfa yenilemeden satır tutarlı kalsın.
    const fmt = (n) => n.toLocaleString('tr-TR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

    function refreshRow(row) {
        const priceEl = row.querySelector('[data-field="price"]');
        const taxEl = row.querySelector('[data-field="tax_rate"]');
        const cell = row.querySelector('.es-taxcell');
        const gross = row.querySelector('.es-gross');

        const rawRate = taxEl ? taxEl.dataset.value : '';
        const rate = (rawRate === '' || rawRate == null) ? null : parseFloat(rawRate);
        const price = parseFloat(priceEl?.dataset.value || '0') || 0;
        const included = row.dataset.esTaxIncluded === '1';

        if (cell) {
            cell.classList.toggle('taxed', rate !== null);
            cell.classList.toggle('free', rate === null);
        }
        if (gross) {
            gross.textContent = (rate === null || included) ? '' : 'Brüt ' + fmt(price * (1 + rate / 100));
        }
    }

    const rowObserver = new MutationObserver(muts => {
        const rows = new Set();
        muts.forEach(m => {
            const row = m.target.closest?.('.es-row');
            if (row) rows.add(row);
        });
        rows.forEach(refreshRow);
    });
    document.querySelectorAll('.es-row [data-field="price"], .es-row [data-field="tax_rate"]').forEach(el => {
        rowObserver.observe(el, { attributes: true, attributeFilter: ['data-value'] });
    });

    // ── Satır: kategori değiştir (gruplama değiştiği için yeniden yüklenir) ──
    document.addEventListener('change', function (e) {
        const sel = e.target.closest('[data-es-cat]');
        if (!sel) return;
        send(sel.dataset.esCat, 'PATCH', { field: 'category_id', value: sel.value }).then(res => {
            if (res.ok && res.data.success) { toast('Kategori güncellendi'); location.reload(); }
            else toast(res.data.message || 'Güncellenemedi', 'error');
        });
    });

    // ── Satır: aktif/pasif ──
    window.esToggle = function (id, url, btn) {
        send(url, 'POST', {}).then(res => {
            if (!res.ok || !res.data.success) return toast(res.data.message || 'İşlem başarısız', 'error');
            const row = document.querySelector(`[data-es-row="${id}"]`);
            row?.classList.toggle('off', !res.data.is_active);
            btn.classList.toggle('on', res.data.is_active);
            btn.querySelector('i').className = 'fas ' + (res.data.is_active ? 'fa-toggle-on' : 'fa-toggle-off');
            btn.title = res.data.is_active ? 'Pasif et' : 'Aktif et';
            toast(res.data.message);
        });
    };

    // ── Satır: sil ──
    window.esDelete = function (id, name, url) {
        const run = () => send(url, 'DELETE').then(res => {
            if (!res.ok || !res.data.success) return toast(res.data.message || 'Silinemedi', 'error');
            const row = document.querySelector(`[data-es-row="${id}"]`);
            if (row) {
                row.style.transition = 'opacity .2s, transform .2s';
                row.style.opacity = '0';
                row.style.transform = 'translateX(-12px)';
                setTimeout(() => location.reload(), 220);
            } else location.reload();
            toast(res.data.message);
        });

        if (typeof Swal !== 'undefined') {
            Swal.fire({
                title: 'Hizmet silinsin mi?', text: name, icon: 'warning', showCancelButton: true,
                confirmButtonColor: '#ef4444', confirmButtonText: 'Evet, sil', cancelButtonText: 'Vazgeç',
            }).then(r => r.isConfirmed && run());
        } else if (confirm(name + ' silinsin mi?')) run();
    };

    // ── Kategori ekle ──
    window.esCreateCategory = function (e) {
        e.preventDefault();
        const form = e.target;
        const name = form.name.value.trim();
        if (!name) return false;
        send(ROUTES.catStore, 'POST', { name }).then(res => {
            if (res.ok && res.data.success) { toast(res.data.message); location.reload(); }
            else toast(res.data.message || 'Kategori eklenemedi', 'error');
        });
        return false;
    };

    // ── Kategori yeniden adlandır ──
    window.esRenameCategory = function (id, current) {
        const apply = (name) => send(ROUTES.catUpdate.replace('__ID__', id), 'PUT', { name }).then(res => {
            if (res.ok && res.data.success) { toast(res.data.message); location.reload(); }
            else toast(res.data.message || 'Güncellenemedi', 'error');
        });

        if (typeof Swal !== 'undefined') {
            Swal.fire({
                title: 'Kategori adı', input: 'text', inputValue: current, showCancelButton: true,
                confirmButtonText: 'Kaydet', cancelButtonText: 'Vazgeç', confirmButtonColor: '#4f46e5',
                inputValidator: (v) => !v?.trim() && 'Ad boş bırakılamaz',
            }).then(r => r.isConfirmed && apply(r.value.trim()));
        } else {
            const v = prompt('Kategori adı', current);
            if (v && v.trim()) apply(v.trim());
        }
    };

    // ── Kategori sil ──
    window.esDeleteCategory = function (id, name) {
        const run = () => send(ROUTES.catDestroy.replace('__ID__', id), 'DELETE').then(res => {
            if (res.ok && res.data.success) { toast(res.data.message); location.reload(); }
            else toast(res.data.message || 'Silinemedi', 'error');
        });

        if (typeof Swal !== 'undefined') {
            Swal.fire({
                title: 'Kategori silinsin mi?',
                text: name + ' — içindeki hizmetler silinmez, Kategorisiz\'e taşınır.',
                icon: 'warning', showCancelButton: true, confirmButtonColor: '#ef4444',
                confirmButtonText: 'Evet, sil', cancelButtonText: 'Vazgeç',
            }).then(r => r.isConfirmed && run());
        } else if (confirm(name + ' kategorisi silinsin mi?')) run();
    };
})();
</script>
@endpush
