@extends('layouts.app')
@section('title', 'SOAP Options — Settings')

@section('css')
<style>
.so-tabs { display:flex; gap:4px; margin-bottom:0; border-bottom:2px solid #e2e8f0; }
.so-tab {
    padding:8px 18px; font-size:12px; font-weight:700; cursor:pointer;
    border-radius:6px 6px 0 0; border:1px solid transparent; border-bottom:none;
    color:#64748b; background:transparent; transition:all .15s;
}
.so-tab:hover { background:#f1f5f9; color:#1e293b; }
.so-tab.active { background:#fff; border-color:#e2e8f0; color:#2563eb; border-bottom-color:#fff; margin-bottom:-2px; }

.so-pane { display:none; padding:20px 0 0; }
.so-pane.active { display:block; }

.so-species-row { display:flex; gap:5px; margin-bottom:14px; flex-wrap:wrap; }
.sp-chip {
    padding:3px 12px; border-radius:20px; font-size:11.5px; font-weight:600; cursor:pointer;
    border:1.5px solid #cbd5e1; background:#fff; color:#475569; transition:all .13s;
}
.sp-chip:hover { border-color:#3b82f6; color:#2563eb; }
.sp-chip.active { background:#2563eb; border-color:#2563eb; color:#fff; }

/* Body system groups in settings */
.bsys-group-block { margin-bottom:18px; }
.bsys-group-header {
    display:flex; align-items:center; gap:8px;
    padding:7px 12px; border-radius:8px 8px 0 0;
    font-size:11.5px; font-weight:800; letter-spacing:.3px;
    border-left:4px solid var(--gc); background:var(--gbg); color:var(--gc);
}
.bsys-group-header .bsys-gh-icon { font-size:14px; }
.bsys-group-header .bsys-gh-count { margin-left:auto; font-size:10px; font-weight:600; opacity:.7; }
.bsys-gh-edit {
    margin-left:6px; padding:2px 7px; border-radius:5px; font-size:10px; font-weight:600;
    border:1px solid rgba(0,0,0,.12); background:rgba(255,255,255,.45); color:inherit;
    cursor:pointer; transition:all .13s; flex-shrink:0;
}
.bsys-gh-edit:hover { background:rgba(255,255,255,.75); }
.bsys-group-list {
    border:1px solid #e2e8f0; border-top:none; border-radius:0 0 8px 8px;
    overflow:hidden;
}
.bsys-group-list .opt-row { border-radius:0; border:none; border-bottom:1px solid #f0f4f8; }
.bsys-group-list .opt-row:last-child { border-bottom:none; }
.bsys-ungrouped { margin-bottom:12px; }

.opt-list { display:flex; flex-direction:column; gap:6px; max-height:520px; overflow-y:auto; }
.opt-row {
    display:flex; align-items:center; gap:8px;
    background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; padding:8px 12px;
    transition:box-shadow .15s;
}
.opt-row:hover { box-shadow:0 2px 8px rgba(0,0,0,.07); }
.opt-row.inactive { opacity:.5; }
.opt-label { flex:1; font-size:13px; font-weight:600; color:#1e293b; }
.opt-meta { font-size:10.5px; color:#94a3b8; margin-left:4px; }
.opt-sys-badge { font-size:10px; padding:1px 7px; border-radius:10px; background:#dbeafe; color:#1e40af; font-weight:600; }
.opt-grp-badge { font-size:10px; padding:2px 8px; border-radius:10px; font-weight:700; }
.opt-actions { display:flex; gap:4px; flex-shrink:0; }

/* Icon picker */
.icon-picker-grid {
    display:flex; flex-wrap:wrap; gap:4px; margin-top:4px;
}
.icon-opt {
    width:30px; height:30px; border-radius:6px; font-size:13px;
    border:1.5px solid #e2e8f0; background:#fff; color:#64748b;
    cursor:pointer; display:flex; align-items:center; justify-content:center;
    transition:all .13s; flex-shrink:0;
}
.icon-opt:hover { border-color:#6366f1; color:#6366f1; background:#eef2ff; }
.icon-opt.selected { border-color:#6366f1; background:#6366f1; color:#fff; }
.icon-preview {
    width:30px; height:30px; border-radius:6px; font-size:13px;
    border:1.5px solid #6366f1; background:#6366f1; color:#fff;
    display:flex; align-items:center; justify-content:center; flex-shrink:0;
}

.add-form { background:#f1f5f9; border:1px solid #e2e8f0; border-radius:10px; padding:14px 16px; margin-bottom:16px; }
.af-row { display:flex; gap:10px; align-items:flex-end; flex-wrap:wrap; }
.af-field { display:flex; flex-direction:column; min-width:0; flex:1; }
.af-field label { font-size:10.5px; font-weight:700; text-transform:uppercase; letter-spacing:.4px; color:#64748b; margin-bottom:4px; }
.af-field .form-control { height:32px; font-size:12px; width:100%; box-sizing:border-box; }
.af-narrow { flex:0 0 72px; }
.af-btn    { flex:0 0 auto; align-self:flex-end; }
</style>
@endsection

@section('content')
<section class="content-header">
    <h1><i class="fas fa-sliders-h"></i> SOAP Options
        <small>Manage chip options shown during consultations</small>
    </h1>
    <ol class="breadcrumb">
        <li><a href="{{ route('vc.settings.index') }}">Settings</a></li>
        <li class="active">SOAP Options</li>
    </ol>
</section>

<section class="content">
<div class="row">
<div class="col-md-10 col-md-offset-1">

@component('components.widget', ['class' => 'box-primary'])

    {{-- Section Tabs --}}
    <div class="so-tabs" id="soTabs">
        <div class="so-tab active" data-pane="complaint">💬 Complaints (S)</div>
        <div class="so-tab" data-pane="lab_test">🧪 Lab Tests (I)</div>
        <div class="so-tab" data-pane="exam_test">🔭 Physical Exams (I)</div>
        <div class="so-tab" data-pane="frequency">⏱ Frequencies (P)</div>
        <div class="so-tab" data-pane="body_system">🫀 Body Systems (O)</div>
    </div>

    @php
    $sections = [
        'complaint'   => ['label' => 'Chief Complaints', 'color' => '#3b82f6', 'has_species' => true,  'has_group' => false],
        'lab_test'    => ['label' => 'Lab Tests',        'color' => '#16a085', 'has_species' => true,  'has_group' => false],
        'exam_test'   => ['label' => 'Physical Exams',   'color' => '#16a085', 'has_species' => true,  'has_group' => false],
        'frequency'   => ['label' => 'Frequencies',      'color' => '#8b5cf6', 'has_species' => false, 'has_group' => false],
        'body_system' => ['label' => 'Body Systems',     'color' => '#22c55e', 'has_species' => false, 'has_group' => true],
    ];
    $speciesLabels = ['all' => '🌐 All Species', 'dog' => '🐕 Dog', 'cat' => '🐈 Cat', 'rabbit' => '🐇 Rabbit', 'bird' => '🦜 Bird'];

    $bodyGroups = [
        'Cardio-Respiratory'      => ['color' => '#ef4444', 'bg' => '#fee2e2', 'icon' => 'fa-heartbeat'],
        'Digestive & Metabolic'   => ['color' => '#f59e0b', 'bg' => '#fef3c7', 'icon' => 'fa-procedures'],
        'Musculo-Neurological'    => ['color' => '#6366f1', 'bg' => '#e0e7ff', 'icon' => 'fa-brain'],
        'Integumentary & Sensory' => ['color' => '#8b5cf6', 'bg' => '#ede9fe', 'icon' => 'fa-eye'],
        'Urogenital & Lymphatic'  => ['color' => '#14b8a6', 'bg' => '#ccfbf1', 'icon' => 'fa-tint'],
    ];
    @endphp

    {{-- ── Non-body-system sections ──────────────────────────────────────── --}}
    @foreach($sections as $sectionKey => $sectionMeta)
    @if($sectionKey === 'body_system') @continue @endif

    <div class="so-pane {{ $sectionKey === 'complaint' ? 'active' : '' }}" id="pane_{{ $sectionKey }}">

        {{-- Add form --}}
        @can('vet_clinic.access_settings')
        <div class="add-form">
            <div class="af-row">
                @if($sectionMeta['has_species'])
                <div class="af-field">
                    <label>Species</label>
                    <select class="form-control so-add-species" data-section="{{ $sectionKey }}">
                        @foreach($speciesLabels as $sp => $spLabel)
                        <option value="{{ $sp }}">{{ $spLabel }}</option>
                        @endforeach
                    </select>
                </div>
                @endif
                <div class="af-field">
                    <label>Label</label>
                    <input type="text" class="form-control so-add-label" data-section="{{ $sectionKey }}" placeholder="New option label…">
                </div>
                <div class="af-field af-narrow">
                    <label>Order</label>
                    <input type="number" class="form-control so-add-order" data-section="{{ $sectionKey }}" value="0" min="0">
                </div>
                <div class="af-btn">
                    <button class="btn btn-primary btn-so-add" data-section="{{ $sectionKey }}" style="height:32px;padding:0 14px;font-size:12px;">
                        <i class="fa fa-plus"></i> Add
                    </button>
                </div>
            </div>
        </div>
        @endcan

        {{-- Species filter chips --}}
        @if($sectionMeta['has_species'])
        <div class="so-species-row" data-section="{{ $sectionKey }}">
            @foreach($speciesLabels as $sp => $spLabel)
            <span class="sp-chip {{ $sp === 'all' ? 'active' : '' }}" data-sp="{{ $sp }}" data-section="{{ $sectionKey }}">{{ $spLabel }}</span>
            @endforeach
        </div>
        @endif

        {{-- Options list --}}
        <div class="opt-list" id="list_{{ $sectionKey }}">
        @php $sectionOptions = $options[$sectionKey] ?? collect(); @endphp
        @forelse($sectionOptions as $opt)
        <div class="opt-row {{ $opt->status === 'inactive' ? 'inactive' : '' }}"
             id="opt_row_{{ $opt->id }}"
             data-sp="{{ $opt->species }}"
             data-section="{{ $sectionKey }}"
             style="{{ $sectionMeta['has_species'] && $opt->species !== 'all' ? 'display:none;' : '' }}">
            <div class="opt-label">
                {{ $opt->label }}
                @if($opt->species !== 'all')
                <span class="opt-sys-badge">{{ $speciesLabels[$opt->species] ?? $opt->species }}</span>
                @endif
                @if(is_null($opt->business_id))
                <span class="opt-meta">(system default)</span>
                @endif
            </div>
            @if(in_array($sectionKey, ['lab_test', 'exam_test']))
                @if(!empty($opt->product_id))
                    <span class="label label-success" style="font-size:10px;" title="Linked to ERP product (POS pricing enabled)">
                        <i class="fa fa-link"></i> Linked
                    </span>
                @else
                    <span class="label label-warning" style="font-size:10px;" title="No ERP product linked — won't auto-bill in POS">
                        <i class="fa fa-chain-broken"></i> Not linked
                    </span>
                @endif
            @endif
            <span class="label label-{{ $opt->status === 'active' ? 'success' : 'default' }} opt-status-badge" style="font-size:10px;">
                {{ $opt->status === 'active' ? 'Active' : 'Inactive' }}
            </span>
            <div class="opt-actions">
                @if(!is_null($opt->business_id))
                <button class="btn btn-xs btn-warning btn-so-edit"
                        data-id="{{ $opt->id }}"
                        data-section="{{ $sectionKey }}"
                        data-product-id="{{ $opt->product_id ?? '' }}"
                        title="Edit"><i class="fa fa-edit"></i></button>
                <button class="btn btn-xs btn-danger btn-so-delete" data-id="{{ $opt->id }}" title="Delete"><i class="fa fa-trash"></i></button>
                @else
                {{-- System default: edit auto-promotes to a business override --}}
                <button class="btn btn-xs btn-warning btn-so-edit"
                        data-id="{{ $opt->id }}"
                        data-section="{{ $sectionKey }}"
                        data-product-id=""
                        title="Override (creates a business copy)"><i class="fa fa-edit"></i></button>
                <button class="btn btn-xs btn-{{ $opt->status === 'active' ? 'default' : 'success' }} btn-so-toggle"
                        data-id="{{ $opt->id }}" title="{{ $opt->status === 'active' ? 'Disable' : 'Enable' }}">
                    <i class="fa fa-{{ $opt->status === 'active' ? 'eye-slash' : 'eye' }}"></i>
                </button>
                @endif
            </div>
        </div>
        @empty
        <div class="text-muted text-center" style="padding:20px;font-size:13px;">No options yet. Add one above.</div>
        @endforelse
        </div>

    </div>{{-- /pane --}}
    @endforeach

    {{-- ── Body Systems tab — grouped view ──────────────────────────────── --}}
    <div class="so-pane" id="pane_body_system">

        @can('vet_clinic.access_settings')
        <div class="add-form">
            <div class="af-row">
                <div class="af-field">
                    <label>System Name</label>
                    <input type="text" class="form-control so-add-label" data-section="body_system" placeholder="e.g. Reproductive">
                </div>
                <div class="af-field">
                    <label>Group <small class="text-muted" style="text-transform:none;letter-spacing:0;font-weight:400;">(or type new)</small></label>
                    <input type="text" class="form-control so-add-group" data-section="body_system"
                           list="bodyGroupsList" placeholder="Select or type new group…">
                    <datalist id="bodyGroupsList">
                        @foreach($bodyGroups as $grpName => $grpMeta)
                        <option value="{{ $grpName }}">
                        @endforeach
                    </datalist>
                </div>
                <div class="af-field" style="flex:0 0 auto;">
                    <label>Group Icon <small class="text-muted" style="text-transform:none;letter-spacing:0;font-weight:400;">(for new groups)</small></label>
                    <div style="display:flex;align-items:center;gap:6px;">
                        <div id="bs_icon_preview" class="icon-preview" title="Selected icon">
                            <i class="fa fa-circle" id="bs_icon_preview_i"></i>
                        </div>
                        <div class="icon-picker-grid" id="bs_icon_grid">
                            @php
                            $iconOptions = [
                                'fa-heartbeat'      => 'Cardio / Heart',
                                'fa-lungs'          => 'Lungs / Respiratory',
                                'fa-brain'          => 'Brain / Neurological',
                                'fa-eye'            => 'Eye / Ophthalmology',
                                'fa-tooth'          => 'Dental / Oral',
                                'fa-bone'           => 'Bone / Musculoskeletal',
                                'fa-hand-paper'     => 'Skin / Dermatology',
                                'fa-deaf'           => 'Ear / ENT',
                                'fa-tint'           => 'Urinary / Lymphatic',
                                'fa-flask'          => 'Endocrine / Lab',
                                'fa-procedures'     => 'GI / Abdominal',
                                'fa-venus-mars'     => 'Reproductive',
                                'fa-stethoscope'    => 'General',
                                'fa-thermometer-half' => 'Vital Signs',
                                'fa-user-md'        => 'Clinical',
                                'fa-circle'         => 'Other',
                            ];
                            @endphp
                            @foreach($iconOptions as $iconCls => $iconTitle)
                            <button type="button" class="icon-opt" data-icon="{{ $iconCls }}" title="{{ $iconTitle }}">
                                <i class="fa {{ $iconCls }}"></i>
                            </button>
                            @endforeach
                        </div>
                        <input type="hidden" id="so_bs_icon" value="fa-circle">
                    </div>
                </div>
                <div class="af-field af-narrow">
                    <label>Order</label>
                    <input type="number" class="form-control so-add-order" data-section="body_system" value="0" min="0">
                </div>
                <div class="af-btn">
                    <button class="btn btn-primary btn-so-add" data-section="body_system" style="height:32px;padding:0 14px;font-size:12px;">
                        <i class="fa fa-plus"></i> Add
                    </button>
                </div>
            </div>
        </div>
        @endcan

        @php
        $bsOptions = $options['body_system'] ?? collect();
        $grouped   = $bsOptions->groupBy('group_name');
        $orderedGroups = collect(array_keys($bodyGroups));
        // Any group in DB not in our predefined list goes at the end
        $extraGroups = $grouped->keys()->filter(fn($k) => !is_null($k) && $k !== '' && !$orderedGroups->contains($k));
        $allGroups   = $orderedGroups->merge($extraGroups);
        $ungrouped   = $grouped->get('') ?? $grouped->get(null, collect());
        @endphp

        {{-- Grouped sections --}}
        @foreach($allGroups as $grpName)
        @php
        $grpOpts    = $grouped->get($grpName, collect());
        $grpMeta    = $bodyGroups[$grpName] ?? ['color' => '#64748b', 'bg' => '#f1f5f9', 'icon' => 'fa-circle'];
        $savedIcon  = $savedGroupIcons[$grpName]['icon'] ?? null;
        $activeIcon = $savedIcon ?: $grpMeta['icon'];
        @endphp
        @if($grpOpts->isNotEmpty())
        <div class="bsys-group-block">
            <div class="bsys-group-header" style="--gc:{{ $grpMeta['color'] }};--gbg:{{ $grpMeta['bg'] }};">
                <i class="fa {{ $activeIcon }} bsys-gh-icon fa-fw"></i>
                <span>{{ $grpName }}</span>
                <span class="bsys-gh-count">{{ $grpOpts->count() }} system{{ $grpOpts->count() !== 1 ? 's' : '' }}</span>
                @can('vet_clinic.access_settings')
                <button type="button" class="bsys-gh-edit btn-edit-group"
                        data-name="{{ $grpName }}"
                        data-icon="{{ $activeIcon }}">
                    <i class="fa fa-pencil-alt fa-fw"></i> Edit Group
                </button>
                @endcan
            </div>
            <div class="bsys-group-list">
            @foreach($grpOpts as $opt)
            <div class="opt-row {{ $opt->status === 'inactive' ? 'inactive' : '' }}"
                 id="opt_row_{{ $opt->id }}"
                 data-section="body_system"
                 data-group="{{ $opt->group_name }}">
                <div class="opt-label">
                    {{ $opt->label }}
                    @if(is_null($opt->business_id))
                    <span class="opt-meta">(system default)</span>
                    @endif
                </div>
                <span class="label label-{{ $opt->status === 'active' ? 'success' : 'default' }} opt-status-badge" style="font-size:10px;">
                    {{ $opt->status === 'active' ? 'Active' : 'Inactive' }}
                </span>
                <div class="opt-actions">
                    @if(!is_null($opt->business_id))
                    <button class="btn btn-xs btn-warning btn-so-edit" data-id="{{ $opt->id }}" data-section="body_system" data-group="{{ $opt->group_name }}" title="Edit"><i class="fa fa-edit"></i></button>
                    <button class="btn btn-xs btn-danger btn-so-delete" data-id="{{ $opt->id }}" title="Delete"><i class="fa fa-trash"></i></button>
                    @else
                    <button class="btn btn-xs btn-{{ $opt->status === 'active' ? 'default' : 'success' }} btn-so-toggle"
                            data-id="{{ $opt->id }}" title="{{ $opt->status === 'active' ? 'Disable' : 'Enable' }}">
                        <i class="fa fa-{{ $opt->status === 'active' ? 'eye-slash' : 'eye' }}"></i>
                    </button>
                    @endif
                </div>
            </div>
            @endforeach
            </div>
        </div>
        @endif
        @endforeach

        {{-- Ungrouped systems --}}
        @if($ungrouped->isNotEmpty())
        <div class="bsys-ungrouped">
            <p class="text-muted" style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.4px;margin-bottom:6px;">
                <i class="fa fa-circle fa-fw"></i> Ungrouped Systems
            </p>
            <div class="opt-list">
            @foreach($ungrouped as $opt)
            <div class="opt-row {{ $opt->status === 'inactive' ? 'inactive' : '' }}"
                 id="opt_row_{{ $opt->id }}"
                 data-section="body_system"
                 data-group="">
                <div class="opt-label">
                    {{ $opt->label }}
                    @if(is_null($opt->business_id))
                    <span class="opt-meta">(system default)</span>
                    @endif
                </div>
                <span class="label label-{{ $opt->status === 'active' ? 'success' : 'default' }} opt-status-badge" style="font-size:10px;">
                    {{ $opt->status === 'active' ? 'Active' : 'Inactive' }}
                </span>
                <div class="opt-actions">
                    @if(!is_null($opt->business_id))
                    <button class="btn btn-xs btn-warning btn-so-edit" data-id="{{ $opt->id }}" data-section="body_system" data-group="" title="Edit"><i class="fa fa-edit"></i></button>
                    <button class="btn btn-xs btn-danger btn-so-delete" data-id="{{ $opt->id }}" title="Delete"><i class="fa fa-trash"></i></button>
                    @else
                    <button class="btn btn-xs btn-{{ $opt->status === 'active' ? 'default' : 'success' }} btn-so-toggle"
                            data-id="{{ $opt->id }}" title="{{ $opt->status === 'active' ? 'Disable' : 'Enable' }}">
                        <i class="fa fa-{{ $opt->status === 'active' ? 'eye-slash' : 'eye' }}"></i>
                    </button>
                    @endif
                </div>
            </div>
            @endforeach
            </div>
        </div>
        @endif

        @if($bsOptions->isEmpty())
        <div class="text-muted text-center" style="padding:30px;font-size:13px;">No body systems yet. Add one above.</div>
        @endif

    </div>{{-- /pane body_system --}}

@endcomponent

</div>
</div>
</section>

{{-- Edit Group Modal --}}
<div class="modal fade" id="editGroupModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header" style="background:#f8fafc;border-bottom:1px solid #e2e8f0;">
                <button type="button" class="close" data-dismiss="modal" style="font-size:15px;">&times;</button>
                <h4 class="modal-title" style="font-size:15px;font-weight:700;">
                    <i class="fa fa-object-group fa-fw" style="color:#6366f1;"></i> Edit Body System Group
                </h4>
            </div>
            <div class="modal-body">
                <input type="hidden" id="eg_old_name">
                <div class="form-group">
                    <label style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.4px;color:#64748b;">Group Name</label>
                    <input type="text" id="eg_name" class="form-control" placeholder="e.g. Cardio-Respiratory">
                    <p class="text-muted" style="font-size:11px;margin-top:4px;">
                        <i class="fa fa-info-circle"></i>
                        Renaming only affects systems you added — system defaults keep their original group name.
                    </p>
                </div>
                <div class="form-group">
                    <label style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.4px;color:#64748b;">Group Icon</label>
                    <div style="display:flex;align-items:center;gap:10px;margin-top:6px;">
                        <div id="eg_icon_preview" style="width:36px;height:36px;border-radius:8px;background:#6366f1;color:#fff;display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0;">
                            <i class="fa fa-circle" id="eg_icon_preview_i"></i>
                        </div>
                        <div class="icon-picker-grid" id="eg_icon_grid">
                            @php
                            $iconOptions = [
                                'fa-heartbeat'        => 'Cardio / Heart',
                                'fa-lungs'            => 'Lungs / Respiratory',
                                'fa-brain'            => 'Brain / Neurological',
                                'fa-eye'              => 'Eye / Ophthalmology',
                                'fa-tooth'            => 'Dental / Oral',
                                'fa-bone'             => 'Bone / Musculoskeletal',
                                'fa-hand-paper'       => 'Skin / Dermatology',
                                'fa-deaf'             => 'Ear / ENT',
                                'fa-tint'             => 'Urinary / Lymphatic',
                                'fa-flask'            => 'Endocrine / Lab',
                                'fa-procedures'       => 'GI / Abdominal',
                                'fa-venus-mars'       => 'Reproductive',
                                'fa-stethoscope'      => 'General',
                                'fa-thermometer-half' => 'Vital Signs',
                                'fa-user-md'          => 'Clinical',
                                'fa-circle'           => 'Other',
                            ];
                            @endphp
                            @foreach($iconOptions as $iconCls => $iconTitle)
                            <button type="button" class="icon-opt eg-icon-opt" data-icon="{{ $iconCls }}" title="{{ $iconTitle }}">
                                <i class="fa {{ $iconCls }}"></i>
                            </button>
                            @endforeach
                        </div>
                    </div>
                    <input type="hidden" id="eg_icon" value="">
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button class="btn btn-primary" id="btn_eg_save">
                    <i class="fa fa-save"></i> Save Group
                </button>
            </div>
        </div>
    </div>
</div>

{{-- Edit Option Modal --}}
<div class="modal fade" id="editOptModal" tabindex="-1">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header"><h4 class="modal-title">Edit Option</h4></div>
            <div class="modal-body">
                <input type="hidden" id="edit_opt_id">
                <input type="hidden" id="edit_opt_section">
                <div class="form-group">
                    <label style="font-size:11px;">Label</label>
                    <input type="text" id="edit_opt_label" class="form-control">
                </div>
                <div class="form-group" id="edit_group_wrap" style="display:none;">
                    <label style="font-size:11px;">Group <span style="font-weight:400;color:#94a3b8;">(select or type new)</span></label>
                    <input type="text" id="edit_opt_group" class="form-control"
                           list="editBodyGroupsList" placeholder="e.g. Cardio-Respiratory">
                    <datalist id="editBodyGroupsList">
                        @foreach($bodyGroups as $grpName => $grpMeta)
                        <option value="{{ $grpName }}">
                        @endforeach
                    </datalist>
                </div>
                <div class="form-group" id="edit_product_wrap" style="display:none;">
                    <label style="font-size:11px;"><i class="fa fa-link"></i> Linked Product <span style="font-weight:400;color:#94a3b8;">(for POS pricing)</span></label>
                    <select id="edit_opt_product_id" class="form-control" style="width:100%;"></select>
                    <small class="text-muted" style="font-size:10.5px;">Pick an ERP product so this item flows into the invoice when the exam is marked "done".</small>
                </div>
                <div class="form-group">
                    <label style="font-size:11px;">Sort Order</label>
                    <input type="number" id="edit_opt_order" class="form-control" min="0">
                </div>
                <div class="form-group">
                    <label style="font-size:11px;">Status</label>
                    <select id="edit_opt_status" class="form-control">
                        <option value="active">Active</option>
                        <option value="inactive">Inactive</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button class="btn btn-primary" id="btn_edit_opt_save">Save</button>
            </div>
        </div>
    </div>
</div>
@endsection

@section('javascript')
<script>
var csrfToken  = '{{ csrf_token() }}';
var storeUrl   = '{{ route('vc.soap-options.store') }}';
var updateBase = '{{ url('vet-clinic/soap-options') }}';

var bodyGroupColors = @json(collect($bodyGroups)->map(fn($m) => ['color' => $m['color'], 'bg' => $m['bg']]));

// ── Icon picker (add form) ────────────────────────────────
$(document).on('click', '#bs_icon_grid .icon-opt', function () {
    var icon = $(this).data('icon');
    $('#bs_icon_grid .icon-opt').removeClass('selected');
    $(this).addClass('selected');
    $('#so_bs_icon').val(icon);
    $('#bs_icon_preview_i').attr('class', 'fa ' + icon);
});

// ── Edit Group modal — open ───────────────────────────────
$(document).on('click', '.btn-edit-group', function (e) {
    e.stopPropagation();
    var name = $(this).data('name');
    var icon = $(this).data('icon') || 'fa-circle';

    $('#eg_old_name').val(name);
    $('#eg_name').val(name);
    $('#eg_icon').val(icon);
    $('#eg_icon_preview_i').attr('class', 'fa ' + icon);
    $('#eg_icon_grid .eg-icon-opt').removeClass('selected');
    $('#eg_icon_grid .eg-icon-opt[data-icon="' + icon + '"]').addClass('selected');

    $('#editGroupModal').modal('show');
});

// ── Edit Group modal — icon picker ────────────────────────
$(document).on('click', '#eg_icon_grid .eg-icon-opt', function () {
    var icon = $(this).data('icon');
    $('#eg_icon_grid .eg-icon-opt').removeClass('selected');
    $(this).addClass('selected');
    $('#eg_icon').val(icon);
    $('#eg_icon_preview_i').attr('class', 'fa ' + icon);
});

// ── Edit Group modal — save ───────────────────────────────
$('#btn_eg_save').on('click', function () {
    var $btn    = $(this).prop('disabled', true);
    var oldName = $('#eg_old_name').val().trim();
    var newName = $('#eg_name').val().trim();
    var icon    = $('#eg_icon').val() || '';

    if (!newName) { toastr.warning('Group name is required.'); $btn.prop('disabled', false); return; }

    $.post('{{ route('vc.soap-options.group.update') }}', {
        _token:     csrfToken,
        old_name:   oldName,
        new_name:   newName,
        group_icon: icon,
    }, function (res) {
        if (!res.success) { toastr.error(res.msg || 'Error'); return; }
        toastr.success(res.msg);
        $('#editGroupModal').modal('hide');
        // Reload to reflect renamed group and updated icon
        setTimeout(function () { location.reload(); }, 600);
    }).fail(function (xhr) {
        var msg = xhr.responseJSON?.errors
            ? Object.values(xhr.responseJSON.errors)[0][0]
            : (xhr.responseJSON?.message || 'Update failed.');
        toastr.error(msg);
    }).always(function () { $btn.prop('disabled', false); });
});

// ── Tab switching ─────────────────────────────────────────
$('#soTabs .so-tab').on('click', function () {
    $('#soTabs .so-tab').removeClass('active');
    $(this).addClass('active');
    $('.so-pane').removeClass('active');
    $('#pane_' + $(this).data('pane')).addClass('active');
});

// ── Species chip filter ───────────────────────────────────
$(document).on('click', '.sp-chip', function () {
    var section = $(this).data('section');
    var sp      = $(this).data('sp');
    $('.sp-chip[data-section="' + section + '"]').removeClass('active');
    $(this).addClass('active');
    $('#list_' + section + ' .opt-row').each(function () {
        var rowSp = $(this).data('sp');
        $(this).toggle(sp === 'all' || rowSp === 'all' || rowSp === sp);
    });
});

// ── Add option ────────────────────────────────────────────
$(document).on('click', '.btn-so-add', function () {
    var section   = $(this).data('section');
    var $btn      = $(this).prop('disabled', true);
    var label     = $('.so-add-label[data-section="' + section + '"]').val().trim();
    var species   = $('.so-add-species[data-section="' + section + '"]').val() || 'all';
    var order     = parseInt($('.so-add-order[data-section="' + section + '"]').val()) || 0;
    var groupName = $('.so-add-group[data-section="' + section + '"]').val() || '';
    var groupIcon = section === 'body_system' ? ($('#so_bs_icon').val() || '') : '';

    if (!label) { toastr.warning('Label is required.'); $btn.prop('disabled', false); return; }

    $.post(storeUrl, { _token: csrfToken, section: section, species: species, label: label, sort_order: order, group_name: groupName, group_icon: groupIcon }, function (res) {
        if (!res.success) { toastr.error(res.msg || 'Error'); $btn.prop('disabled', false); return; }
        toastr.success(res.msg);

        if (section === 'body_system') {
            // For body_system, reload the page to update the grouped view properly
            location.reload();
            return;
        }

        var spLabel = { all: '🌐 All', dog: '🐕 Dog', cat: '🐈 Cat', rabbit: '🐇 Rabbit', bird: '🦜 Bird' };
        var html = '<div class="opt-row" id="opt_row_' + res.option.id + '" data-sp="' + species + '" data-section="' + section + '">' +
            '<div class="opt-label">' + $('<span>').text(res.option.label).html() +
            (species !== 'all' ? ' <span class="opt-sys-badge">' + (spLabel[species] || species) + '</span>' : '') + '</div>' +
            '<span class="label label-success opt-status-badge" style="font-size:10px;">Active</span>' +
            '<div class="opt-actions">' +
                '<button class="btn btn-xs btn-warning btn-so-edit" data-id="' + res.option.id + '" data-section="' + section + '" title="Edit"><i class="fa fa-edit"></i></button>' +
                '<button class="btn btn-xs btn-danger btn-so-delete" data-id="' + res.option.id + '" title="Delete"><i class="fa fa-trash"></i></button>' +
            '</div></div>';

        $('#list_' + section + ' .text-muted').remove();
        $('#list_' + section).append(html);
        $('.so-add-label[data-section="' + section + '"]').val('');
    }).fail(function (xhr) {
        toastr.error(xhr.responseJSON?.msg || 'Failed to add option.');
    }).always(function () { $btn.prop('disabled', false); });
});

// ── Edit option ───────────────────────────────────────────
$(document).on('click', '.btn-so-edit', function () {
    var $row    = $(this).closest('.opt-row');
    var section = $(this).data('section') || $row.data('section');
    var group   = $(this).data('group') || '';
    $('#edit_opt_id').val($(this).data('id'));
    $('#edit_opt_section').val(section);
    $('#edit_opt_label').val($row.find('.opt-label').contents().filter(function(){ return this.nodeType === 3; }).text().trim());
    $('#edit_opt_status').val($row.hasClass('inactive') ? 'inactive' : 'active');
    $('#edit_opt_order').val(0);

    if (section === 'body_system') {
        $('#edit_group_wrap').show();
        $('#edit_opt_group').val(group);
    } else {
        $('#edit_group_wrap').hide();
    }

    // Product picker visible for lab/exam tests
    var showProduct = (section === 'lab_test' || section === 'exam_test');
    $('#edit_product_wrap').toggle(showProduct);
    if (showProduct) {
        var currentProductId = $(this).data('product-id') || '';
        $('#edit_opt_product_id').empty();
        initProductPicker('#edit_opt_product_id', currentProductId);
    }

    $('#editOptModal').modal('show');
});

// Shared product Select2 init (used by exam/lab edit modal here & other places via vcInitProductPicker)
function initProductPicker(selector, currentId) {
    var $sel = $(selector);
    // If already initialised, just reset value
    if ($sel.hasClass('select2-hidden-accessible')) {
        $sel.empty().val(null).trigger('change');
    }
    $sel.select2({
        width: '100%',
        placeholder: '— Search product —',
        allowClear: true,
        dropdownParent: $sel.closest('.modal').length ? $sel.closest('.modal') : $(document.body),
        ajax: {
            url: '{{ route('vc.products.search') }}',
            delay: 300,
            data: function (p) { return { q: p.term }; },
            processResults: function (d) { return d; }
        }
    });
    if (currentId) {
        $.get('{{ url('vet-clinic/products') }}/' + currentId + '/lookup', function (r) {
            if (!r) return;
            var opt = new Option(r.text, r.id, true, true);
            $(opt).attr('data-price', r.price ?? '');
            $sel.append(opt).trigger('change');
        });
    }
}
// Expose globally so other modules' modals can reuse
window.vcInitProductPicker = initProductPicker;

$('#btn_edit_opt_save').on('click', function () {
    var id      = $('#edit_opt_id').val();
    var section = $('#edit_opt_section').val();
    var $btn    = $(this).prop('disabled', true);
    $.post(updateBase + '/' + id + '/update', {
        _token:     csrfToken,
        label:      $('#edit_opt_label').val().trim(),
        status:     $('#edit_opt_status').val(),
        sort_order: parseInt($('#edit_opt_order').val()) || 0,
        group_name: section === 'body_system' ? $('#edit_opt_group').val() : '',
        product_id: (section === 'lab_test' || section === 'exam_test') ? ($('#edit_opt_product_id').val() || '') : '',
    }, function (res) {
        if (!res.success) { toastr.error(res.msg); return; }
        toastr.success(res.msg);
        // Promoted system default → reload so the override replaces the source row
        if (res.promoted) { setTimeout(function(){ location.reload(); }, 600); return; }
        if (section === 'body_system') { location.reload(); return; }
        var $row = $('#opt_row_' + id);
        var $lbl = $row.find('.opt-label');
        var badge = $lbl.find('.opt-sys-badge, .opt-meta').detach();
        $lbl.text($('#edit_opt_label').val().trim());
        $lbl.append(badge);
        var st = $('#edit_opt_status').val();
        $row.toggleClass('inactive', st === 'inactive');
        $row.find('.opt-status-badge').text(st === 'active' ? 'Active' : 'Inactive')
            .attr('class', 'label label-' + (st === 'active' ? 'success' : 'default') + ' opt-status-badge');
        $('#editOptModal').modal('hide');
    }).fail(function(){ toastr.error('Update failed.'); })
      .always(function(){ $btn.prop('disabled', false); });
});

// ── Toggle (handles both business-owned and system defaults via auto-promote) ─
$(document).on('click', '.btn-so-toggle', function () {
    var id   = $(this).data('id');
    var $btn = $(this).prop('disabled', true);
    $.post(updateBase + '/' + id + '/toggle', { _token: csrfToken }, function (res) {
        if (!res.success) { toastr.error('Failed.'); return; }
        // System default was promoted to a business copy → reload so the list refreshes
        if (res.promoted) {
            toastr.success((res.status === 'active' ? 'Enabled' : 'Disabled') + ' (override created for this business). Reloading…');
            setTimeout(function(){ location.reload(); }, 700);
            return;
        }
        var $row = $('#opt_row_' + id);
        $row.toggleClass('inactive', res.status === 'inactive');
        $row.find('.opt-status-badge').text(res.status === 'active' ? 'Active' : 'Inactive')
            .attr('class', 'label label-' + (res.status === 'active' ? 'success' : 'default') + ' opt-status-badge');
        $btn.attr('class', 'btn btn-xs btn-' + (res.status === 'active' ? 'default' : 'success') + ' btn-so-toggle')
            .find('i').attr('class', 'fa fa-' + (res.status === 'active' ? 'eye-slash' : 'eye'));
        toastr.success(res.status === 'active' ? 'Enabled.' : 'Disabled.');
    }).fail(function(){ toastr.error('Failed.'); })
      .always(function(){ $btn.prop('disabled', false); });
});

// ── Delete business option ────────────────────────────────
$(document).on('click', '.btn-so-delete', function () {
    if (!confirm('Delete this option?')) return;
    var id   = $(this).data('id');
    var $btn = $(this).prop('disabled', true);
    $.ajax({ url: updateBase + '/' + id, type: 'DELETE', data: { _token: csrfToken },
        success: function (res) {
            if (!res.success) { toastr.error(res.msg); return; }
            toastr.success(res.msg);
            $('#opt_row_' + id).remove();
        },
        error: function () { toastr.error('Delete failed.'); },
        complete: function () { $btn.prop('disabled', false); }
    });
});
</script>
@endsection
