@extends('layouts.admin.app')

@section('title', translate('AI Chat Board'))

@section('content')
    <div class="content container-fluid">
        <div class="page-header">
            <h1 class="page-header-title mr-3">
                <span class="page-header-icon">
                    <img src="{{ asset('public/assets/admin/img/business.png') }}" class="w--26" alt="">
                </span>
                <span>{{ translate('messages.business_setup') }}</span>
            </h1>
            @include('admin-views.business-settings.partials.nav-menu')
        </div>

        @if ($errors->any())
            <div class="alert alert-danger">
                <ul class="mb-0 pl-3">
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        <div class="card mb-3">
            <div class="card-body">
                <div class="d-flex flex-wrap gap-3 justify-content-between align-items-center">
                    <div>
                        <h3 class="mb-1">{{ translate('AI Chat Board / Auto Reply System') }}</h3>
                        <p class="mb-0 text-muted fs-12">
                            {{ translate('Auto reply uses knowledge base, offers, FAQ, product data, policy content, and approved corrections in one smart flow.') }}
                        </p>
                    </div>
                    <div class="d-flex flex-wrap gap-2 align-items-center">
                        <span class="badge badge-soft-success px-3 py-2">{{ translate('Knowledge') }}: {{ $knowledgeEntries->total() }}</span>
                        <span class="badge badge-soft-info px-3 py-2">{{ translate('Offers') }}: {{ $offers->total() }}</span>
                        <span class="badge badge-soft-primary px-3 py-2">{{ translate('FAQ') }}: {{ $faqs->total() }}</span>
                        <span class="badge badge-soft-warning px-3 py-2">{{ translate('Corrections') }}: {{ $corrections->total() }}</span>
                        <span class="badge badge-soft-dark px-3 py-2">{{ translate('External Sessions') }}: {{ $externalSessionCount }}</span>
                        <span class="badge badge-soft-secondary px-3 py-2">{{ translate('Channel Messages') }}: {{ $externalMessageCount }}</span>

                        <form action="{{ route('admin.business-settings.ai-chat.sync-products') }}" method="post" class="d-inline ms-auto">
                            @csrf
                            <button type="submit" class="btn btn--primary btn-sm px-3"
                                    onclick="return confirm('{{ translate('This will clear the AI product cache so the latest product data is used. Continue?') }}')">
                                <i class="tio-refresh mr-1"></i> {{ translate('Sync Products to AI') }}
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div class="card mb-4" id="settings-section">
            <div class="card-header">
                <h4 class="mb-0">{{ translate('Admin Controls') }}</h4>
            </div>
            <div class="card-body">
                <form action="{{ route('admin.business-settings.ai-chat.settings') }}" method="post">
                    @csrf
                    <div class="row g-3">
                        <div class="col-lg-2 col-md-4">
                            <label class="form-label">{{ translate('Chat ON/OFF') }}</label>
                            <select class="form-control" name="ai_chat_board_enabled">
                                <option value="1" {{ $settings['chat_enabled'] ? 'selected' : '' }}>{{ translate('ON') }}</option>
                                <option value="0" {{ !$settings['chat_enabled'] ? 'selected' : '' }}>{{ translate('OFF') }}</option>
                            </select>
                        </div>
                        <div class="col-lg-2 col-md-4">
                            <label class="form-label">{{ translate('Auto Reply') }}</label>
                            <select class="form-control" name="ai_chat_auto_reply_enabled">
                                <option value="1" {{ $settings['auto_reply_enabled'] ? 'selected' : '' }}>{{ translate('ON') }}</option>
                                <option value="0" {{ !$settings['auto_reply_enabled'] ? 'selected' : '' }}>{{ translate('OFF') }}</option>
                            </select>
                        </div>
                        <div class="col-lg-2 col-md-4">
                            <label class="form-label">{{ translate('Offer Module') }}</label>
                            <select class="form-control" name="ai_chat_offer_module_enabled">
                                <option value="1" {{ $settings['offer_enabled'] ? 'selected' : '' }}>{{ translate('ON') }}</option>
                                <option value="0" {{ !$settings['offer_enabled'] ? 'selected' : '' }}>{{ translate('OFF') }}</option>
                            </select>
                        </div>
                        <div class="col-lg-2 col-md-4">
                            <label class="form-label">{{ translate('FAQ') }}</label>
                            <select class="form-control" name="ai_chat_faq_enabled">
                                <option value="1" {{ $settings['faq_enabled'] ? 'selected' : '' }}>{{ translate('ON') }}</option>
                                <option value="0" {{ !$settings['faq_enabled'] ? 'selected' : '' }}>{{ translate('OFF') }}</option>
                            </select>
                        </div>
                        <div class="col-lg-2 col-md-4">
                            <label class="form-label">{{ translate('Knowledge') }}</label>
                            <select class="form-control" name="ai_chat_knowledge_enabled">
                                <option value="1" {{ $settings['knowledge_enabled'] ? 'selected' : '' }}>{{ translate('ON') }}</option>
                                <option value="0" {{ !$settings['knowledge_enabled'] ? 'selected' : '' }}>{{ translate('OFF') }}</option>
                            </select>
                        </div>
                        <div class="col-lg-2 col-md-4">
                            <label class="form-label">{{ translate('Correction Approval') }}</label>
                            <select class="form-control" name="ai_chat_correction_approval_enabled">
                                <option value="1" {{ $settings['correction_approval_enabled'] ? 'selected' : '' }}>{{ translate('Required') }}</option>
                                <option value="0" {{ !$settings['correction_approval_enabled'] ? 'selected' : '' }}>{{ translate('Not Required') }}</option>
                            </select>
                        </div>
                        <div class="col-lg-6">
                            <label class="form-label">{{ translate('Answer Priority Order') }}</label>
                            <input type="text" class="form-control" name="ai_chat_answer_priority_order"
                                   value="{{ implode(',', $settings['answer_priority_order']) }}"
                                   placeholder="correction,knowledge,faq,offer,product,policy">
                            <small class="text-muted">{{ translate('Use comma separated source order') }}</small>
                        </div>
                        <div class="col-lg-3">
                            <label class="form-label">{{ translate('Fallback Message (BN)') }}</label>
                            <textarea class="form-control" rows="2" name="ai_chat_fallback_message_bn">{{ $settings['fallback_message_bn'] }}</textarea>
                        </div>
                        <div class="col-lg-3">
                            <label class="form-label">{{ translate('Fallback Message (EN)') }}</label>
                            <textarea class="form-control" rows="2" name="ai_chat_fallback_message_en">{{ $settings['fallback_message_en'] }}</textarea>
                        </div>
                        <div class="col-lg-2 col-md-4">
                            <label class="form-label">
                                {{ translate('Min Match % Threshold') }}
                                <span data-toggle="tooltip" title="{{ translate('Product search results below this % will be treated as Not Found. Set 0 to disable filtering.') }}">
                                    <i class="tio-info-outined text-muted"></i>
                                </span>
                            </label>
                            <div class="input-group">
                                <input type="number" class="form-control" name="ai_chat_product_match_threshold"
                                       min="0" max="100" step="5"
                                       value="{{ $settings['min_match_threshold'] ?? 0 }}"
                                       placeholder="0">
                                <span class="input-group-text">%</span>
                            </div>
                            <small class="text-muted">{{ translate('0 = show all results, 60 = only 60%+ matches') }}</small>
                        </div>
                    </div>
                    <div class="d-flex justify-content-end mt-3">
                        <button type="submit" class="btn btn--primary">{{ translate('Save Settings') }}</button>
                    </div>
                </form>
            </div>
        </div>

        <div class="card mb-4" id="channel-section">
            <div class="card-header">
                <h4 class="mb-0">{{ translate('WhatsApp & Messenger Auto Reply') }}</h4>
            </div>
            <div class="card-body">
                <form action="{{ route('admin.business-settings.ai-chat.channels.update') }}" method="post">
                    @csrf
                    <div class="row g-3">
                        <div class="col-lg-3 col-md-6">
                            <label class="form-label">{{ translate('Meta Channels') }}</label>
                            <select class="form-control" name="meta_channels_enabled">
                                <option value="1" {{ data_get($channelSettings, 'enabled') ? 'selected' : '' }}>{{ translate('ON') }}</option>
                                <option value="0" {{ !data_get($channelSettings, 'enabled') ? 'selected' : '' }}>{{ translate('OFF') }}</option>
                            </select>
                        </div>
                        <div class="col-lg-3 col-md-6">
                            <label class="form-label">{{ translate('Graph API Version') }}</label>
                            <input type="text" class="form-control" name="meta_graph_version"
                                   value="{{ old('meta_graph_version', data_get($channelSettings, 'graph_version', 'v23.0')) }}"
                                   placeholder="v23.0">
                        </div>
                        <div class="col-lg-3 col-md-6">
                            <label class="form-label">{{ translate('WhatsApp Auto Reply') }}</label>
                            <select class="form-control" name="whatsapp_enabled">
                                <option value="1" {{ data_get($channelSettings, 'whatsapp.enabled') ? 'selected' : '' }}>{{ translate('ON') }}</option>
                                <option value="0" {{ !data_get($channelSettings, 'whatsapp.enabled') ? 'selected' : '' }}>{{ translate('OFF') }}</option>
                            </select>
                        </div>
                        <div class="col-lg-3 col-md-6">
                            <label class="form-label">{{ translate('Messenger Auto Reply') }}</label>
                            <select class="form-control" name="messenger_enabled">
                                <option value="1" {{ data_get($channelSettings, 'messenger.enabled') ? 'selected' : '' }}>{{ translate('ON') }}</option>
                                <option value="0" {{ !data_get($channelSettings, 'messenger.enabled') ? 'selected' : '' }}>{{ translate('OFF') }}</option>
                            </select>
                        </div>

                        <div class="col-12">
                            <div class="alert alert-soft-info mb-0">
                                <strong>{{ translate('How this works') }}:</strong>
                                <span>{{ translate('Meta will send incoming WhatsApp and Messenger webhook events to the URLs below. The AI Chat Board reply engine will generate and send the reply automatically.') }}</span>
                            </div>
                        </div>

                        <div class="col-lg-6">
                            <div class="border rounded p-3 h-100">
                                <h5 class="mb-3">{{ translate('WhatsApp Cloud API') }}</h5>
                                <div class="row g-3">
                                    <div class="col-12">
                                        <label class="form-label">{{ translate('Webhook URL') }}</label>
                                        <div class="input-group">
                                            <input type="text" class="form-control" id="whatsapp-webhook-url" value="{{ route('meta-chat.webhook.verify', ['channel' => 'whatsapp']) }}" readonly>
                                            <button type="button" class="btn btn-outline-primary copy-to-clipboard" data-target="#whatsapp-webhook-url"><i class="tio-copy"></i></button>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">{{ translate('Verify Token') }}</label>
                                        <input type="text" class="form-control" name="whatsapp_verify_token" value="{{ old('whatsapp_verify_token', data_get($channelSettings, 'whatsapp.verify_token')) }}" required>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">{{ translate('Phone Number ID') }}</label>
                                        <input type="text" class="form-control" name="whatsapp_phone_number_id" value="{{ old('whatsapp_phone_number_id', data_get($channelSettings, 'whatsapp.phone_number_id')) }}">
                                    </div>
                                    <div class="col-md-12">
                                        <label class="form-label">{{ translate('Access Token') }}</label>
                                        <input type="text" class="form-control" name="whatsapp_access_token" value="{{ old('whatsapp_access_token', data_get($channelSettings, 'whatsapp.access_token')) }}" placeholder="{{ translate('Paste long-lived access token') }}">
                                    </div>
                                    <div class="col-md-12">
                                        <label class="form-label">{{ translate('Business Account ID') }}</label>
                                        <input type="text" class="form-control" name="whatsapp_business_account_id" value="{{ old('whatsapp_business_account_id', data_get($channelSettings, 'whatsapp.business_account_id')) }}">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-lg-6">
                            <div class="border rounded p-3 h-100">
                                <h5 class="mb-3">{{ translate('Messenger Platform') }}</h5>
                                <div class="row g-3">
                                    <div class="col-12">
                                        <label class="form-label">{{ translate('Webhook URL') }}</label>
                                        <div class="input-group">
                                            <input type="text" class="form-control" id="messenger-webhook-url" value="{{ route('meta-chat.webhook.verify', ['channel' => 'messenger']) }}" readonly>
                                            <button type="button" class="btn btn-outline-primary copy-to-clipboard" data-target="#messenger-webhook-url"><i class="tio-copy"></i></button>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">{{ translate('Verify Token') }}</label>
                                        <input type="text" class="form-control" name="messenger_verify_token" value="{{ old('messenger_verify_token', data_get($channelSettings, 'messenger.verify_token')) }}" required>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">{{ translate('Page ID') }}</label>
                                        <input type="text" class="form-control" name="messenger_page_id" value="{{ old('messenger_page_id', data_get($channelSettings, 'messenger.page_id')) }}">
                                    </div>
                                    <div class="col-md-12">
                                        <label class="form-label">{{ translate('Page Access Token') }}</label>
                                        <input type="text" class="form-control" name="messenger_page_access_token" value="{{ old('messenger_page_access_token', data_get($channelSettings, 'messenger.page_access_token')) }}" placeholder="{{ translate('Paste page access token') }}">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="d-flex justify-content-end mt-3">
                        <button type="submit" class="btn btn--primary">{{ translate('Save Channel Settings') }}</button>
                    </div>
                </form>
            </div>
        </div>

        {{-- ====================== KEYWORD AUTO-REPLY SECTION ====================== --}}
        <div class="card mb-4" id="keyword-section">
            <div class="card-header d-flex align-items-center gap-2">
                <h4 class="mb-0">{{ translate('Keyword Auto-Reply') }}</h4>
                <span class="badge badge-soft-primary">{{ translate('Highest Priority') }}</span>
            </div>
            <div class="card-body">
                <div class="alert alert-soft-info mb-3 py-2">
                    <i class="tio-info-outined mr-1"></i>
                    {{ translate('When a customer message contains a keyword below, the bot replies instantly with the defined message — before any other source.') }}
                    <strong>{{ translate('Separate multiple keywords with commas.') }}</strong>
                    {{ translate('Example keywords:') }} <code>hi, hello, আসসালামু আলাইকুম</code>
                </div>

                <form action="{{ $editKeyword ? route('admin.business-settings.ai-chat.knowledge.update', $editKeyword->id) : route('admin.business-settings.ai-chat.knowledge.store') }}" method="post">
                    @csrf
                    @if($editKeyword) @method('put') @endif
                    <input type="hidden" name="source_category" value="keyword">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label">{{ translate('Rule Name') }} <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="title"
                                   value="{{ old('title', $editKeyword?->title) }}"
                                   placeholder="{{ translate('e.g. Greeting - Hi/Hello') }}" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">{{ translate('Keywords (comma separated)') }} <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="question_patterns"
                                   value="{{ old('question_patterns', $editKeyword?->question_patterns) }}"
                                   placeholder="{{ translate('hi, hello, hey, হ্যালো') }}" required>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">{{ translate('Priority') }}</label>
                            <input type="number" class="form-control" name="priority"
                                   value="{{ old('priority', $editKeyword?->priority ?? 100) }}">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">{{ translate('Status') }}</label>
                            <select class="form-control" name="is_active">
                                <option value="1" {{ old('is_active', $editKeyword?->is_active ?? true) ? 'selected' : '' }}>{{ translate('Active') }}</option>
                                <option value="0" {{ !old('is_active', $editKeyword?->is_active ?? true) ? 'selected' : '' }}>{{ translate('Inactive') }}</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ translate('Auto Reply (Bangla)') }}</label>
                            <textarea class="form-control" rows="2" name="answer_bn"
                                      placeholder="{{ translate('হ্যালো! কিভাবে সাহায্য করতে পারি?') }}">{{ old('answer_bn', $editKeyword?->answer_bn) }}</textarea>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ translate('Auto Reply (English)') }}</label>
                            <textarea class="form-control" rows="2" name="answer_en"
                                      placeholder="{{ translate('Hello! How can I help you today?') }}">{{ old('answer_en', $editKeyword?->answer_en) }}</textarea>
                        </div>
                        <div class="col-md-12 d-flex justify-content-end gap-2">
                            <a href="{{ route('admin.business-settings.ai-chat-board') }}#keyword-section" class="btn btn--reset">{{ translate('Reset') }}</a>
                            <button type="submit" class="btn btn--primary">
                                {{ $editKeyword ? translate('Update Keyword Rule') : translate('Add Keyword Rule') }}
                            </button>
                        </div>
                    </div>
                </form>

                <div class="table-responsive mt-4">
                    <table class="table table-hover table-borderless table-thead-bordered">
                        <thead class="thead-light">
                        <tr>
                            <th>#</th>
                            <th>{{ translate('Rule Name') }}</th>
                            <th>{{ translate('Keywords') }}</th>
                            <th>{{ translate('Reply (BN)') }}</th>
                            <th>{{ translate('Priority') }}</th>
                            <th>{{ translate('Status') }}</th>
                            <th class="text-center">{{ translate('Action') }}</th>
                        </tr>
                        </thead>
                        <tbody>
                        @forelse($keywordEntries as $k => $kw)
                            <tr>
                                <td>{{ $k + $keywordEntries->firstItem() }}</td>
                                <td><strong>{{ $kw->title }}</strong></td>
                                <td>
                                    @foreach(array_filter(array_map('trim', explode(',', $kw->question_patterns ?? ''))) as $tag)
                                        <span class="badge badge-soft-secondary mr-1">{{ $tag }}</span>
                                    @endforeach
                                </td>
                                <td class="text-muted" style="max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">{{ $kw->answer_bn }}</td>
                                <td>{{ $kw->priority }}</td>
                                <td><span class="badge badge-soft-{{ $kw->is_active ? 'success' : 'danger' }}">{{ $kw->is_active ? translate('Active') : translate('Inactive') }}</span></td>
                                <td class="text-center">
                                    <a class="btn btn-sm btn--primary" href="{{ route('admin.business-settings.ai-chat-board', ['edit_keyword' => $kw->id]) }}#keyword-section">{{ translate('Edit') }}</a>
                                    <a class="btn btn-sm btn-outline-info" href="{{ route('admin.business-settings.ai-chat.knowledge.status', [$kw->id, $kw->is_active ? 0 : 1]) }}">{{ $kw->is_active ? translate('Disable') : translate('Enable') }}</a>
                                    <form action="{{ route('admin.business-settings.ai-chat.knowledge.destroy', $kw->id) }}" method="post" class="d-inline-block">
                                        @csrf @method('delete')
                                        <button type="submit" class="btn btn-sm btn-outline-danger" onclick="return confirm('{{ translate('Delete this keyword rule?') }}')">{{ translate('Delete') }}</button>
                                    </form>
                                </td>
                            </tr>
                        @empty
                            <tr><td colspan="7" class="text-center py-4 text-muted">{{ translate('No keyword rules yet. Add your first keyword rule above.') }}</td></tr>
                        @endforelse
                        </tbody>
                    </table>
                </div>
                <div class="d-flex justify-content-end">{!! $keywordEntries->withQueryString()->links() !!}</div>
            </div>
        </div>
        {{-- ================================================================== --}}

        <div class="card mb-4" id="knowledge-section">
            <div class="card-header"><h4 class="mb-0">{{ translate('Knowledge Base') }}</h4></div>
            <div class="card-body">
                <form action="{{ $editKnowledge ? route('admin.business-settings.ai-chat.knowledge.update', $editKnowledge->id) : route('admin.business-settings.ai-chat.knowledge.store') }}" method="post">
                    @csrf
                    @if($editKnowledge) @method('put') @endif
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label">{{ translate('Title') }}</label>
                            <input type="text" class="form-control" name="title" value="{{ old('title', $editKnowledge?->title) }}" required>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">{{ translate('Category') }}</label>
                            <select class="form-control" name="source_category">
                                @foreach(['custom','delivery','pricing','policy','faq','product'] as $type)
                                    <option value="{{ $type }}" {{ old('source_category', $editKnowledge?->source_category ?? 'custom') === $type ? 'selected' : '' }}>{{ ucfirst($type) }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">{{ translate('Priority') }}</label>
                            <input type="number" class="form-control" name="priority" value="{{ old('priority', $editKnowledge?->priority ?? 0) }}">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">{{ translate('Status') }}</label>
                            <select class="form-control" name="is_active">
                                <option value="1" {{ old('is_active', $editKnowledge?->is_active ?? true) ? 'selected' : '' }}>{{ translate('Active') }}</option>
                                <option value="0" {{ !old('is_active', $editKnowledge?->is_active ?? true) ? 'selected' : '' }}>{{ translate('Inactive') }}</option>
                            </select>
                        </div>
                        <div class="col-md-2 d-flex align-items-end justify-content-end">
                            <a href="{{ route('admin.business-settings.ai-chat-board') }}#knowledge-section" class="btn btn--reset mr-2">{{ translate('Reset') }}</a>
                            <button type="submit" class="btn btn--primary">{{ $editKnowledge ? translate('Update') : translate('Add') }}</button>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ translate('Question Patterns / Keywords') }}</label>
                            <input type="text" class="form-control" name="question_patterns" value="{{ old('question_patterns', $editKnowledge?->question_patterns) }}" placeholder="delivery fee, shipping time, home delivery">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ translate('Tags') }}</label>
                            <input type="text" class="form-control" name="tags" value="{{ old('tags', $editKnowledge?->tags) }}" placeholder="offer, delivery, price">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ translate('Answer (Bangla)') }}</label>
                            <textarea class="form-control" rows="3" name="answer_bn">{{ old('answer_bn', $editKnowledge?->answer_bn) }}</textarea>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ translate('Answer (English)') }}</label>
                            <textarea class="form-control" rows="3" name="answer_en">{{ old('answer_en', $editKnowledge?->answer_en) }}</textarea>
                        </div>
                    </div>
                </form>

                <div class="table-responsive mt-4">
                    <table class="table table-hover table-borderless table-thead-bordered">
                        <thead class="thead-light">
                        <tr>
                            <th>{{ translate('SL') }}</th>
                            <th>{{ translate('Title') }}</th>
                            <th>{{ translate('Keywords') }}</th>
                            <th>{{ translate('Priority') }}</th>
                            <th>{{ translate('Status') }}</th>
                            <th class="text-center">{{ translate('Action') }}</th>
                        </tr>
                        </thead>
                        <tbody>
                        @forelse($knowledgeEntries as $key => $entry)
                            <tr>
                                <td>{{ $key + $knowledgeEntries->firstItem() }}</td>
                                <td>{{ $entry->title }}</td>
                                <td>{{ \Illuminate\Support\Str::limit($entry->question_patterns, 60) }}</td>
                                <td>{{ $entry->priority }}</td>
                                <td><span class="badge badge-soft-{{ $entry->is_active ? 'success' : 'danger' }}">{{ $entry->is_active ? translate('Active') : translate('Inactive') }}</span></td>
                                <td class="text-center">
                                    <a class="btn btn-sm btn--primary" href="{{ route('admin.business-settings.ai-chat-board', ['edit_knowledge' => $entry->id]) }}#knowledge-section">{{ translate('Edit') }}</a>
                                    <a class="btn btn-sm btn-outline-info" href="{{ route('admin.business-settings.ai-chat.knowledge.status', [$entry->id, $entry->is_active ? 0 : 1]) }}">{{ $entry->is_active ? translate('Disable') : translate('Enable') }}</a>
                                    <form action="{{ route('admin.business-settings.ai-chat.knowledge.destroy', $entry->id) }}" method="post" class="d-inline-block">@csrf @method('delete')<button type="submit" class="btn btn-sm btn-outline-danger">{{ translate('Delete') }}</button></form>
                                </td>
                            </tr>
                        @empty
                            <tr><td colspan="6" class="text-center py-4">{{ translate('No data found') }}</td></tr>
                        @endforelse
                        </tbody>
                    </table>
                </div>
                <div class="d-flex justify-content-end">{!! $knowledgeEntries->withQueryString()->links() !!}</div>
            </div>
        </div>

        <div class="card mb-4" id="offer-section">
            <div class="card-header"><h4 class="mb-0">{{ translate('Offer Management') }}</h4></div>
            <div class="card-body">
                <form action="{{ $editOffer ? route('admin.business-settings.ai-chat.offer.update', $editOffer->id) : route('admin.business-settings.ai-chat.offer.store') }}" method="post">
                    @csrf
                    @if($editOffer) @method('put') @endif
                    <div class="row g-3">
                        <div class="col-md-4"><label class="form-label">{{ translate('Title') }}</label><input type="text" class="form-control" name="title" value="{{ old('title', $editOffer?->title) }}" required></div>
                        <div class="col-md-2"><label class="form-label">{{ translate('Priority') }}</label><input type="number" class="form-control" name="priority" value="{{ old('priority', $editOffer?->priority ?? 0) }}"></div>
                        <div class="col-md-2"><label class="form-label">{{ translate('Start Date') }}</label><input type="date" class="form-control" name="start_date" value="{{ old('start_date', $editOffer?->start_date?->format('Y-m-d')) }}"></div>
                        <div class="col-md-2"><label class="form-label">{{ translate('End Date') }}</label><input type="date" class="form-control" name="end_date" value="{{ old('end_date', $editOffer?->end_date?->format('Y-m-d')) }}"></div>
                        <div class="col-md-2"><label class="form-label">{{ translate('Status') }}</label>
                            <select class="form-control" name="is_active">
                                <option value="1" {{ old('is_active', $editOffer?->is_active ?? true) ? 'selected' : '' }}>{{ translate('Active') }}</option>
                                <option value="0" {{ !old('is_active', $editOffer?->is_active ?? true) ? 'selected' : '' }}>{{ translate('Inactive') }}</option>
                            </select>
                        </div>
                        <div class="col-md-6"><label class="form-label">{{ translate('Description') }}</label><textarea class="form-control" rows="3" name="description">{{ old('description', $editOffer?->description) }}</textarea></div>
                        <div class="col-md-3"><label class="form-label">{{ translate('Title (BN)') }}</label><input type="text" class="form-control" name="title_bn" value="{{ old('title_bn', $editOffer?->title_bn) }}"></div>
                        <div class="col-md-3"><label class="form-label">{{ translate('Title (EN)') }}</label><input type="text" class="form-control" name="title_en" value="{{ old('title_en', $editOffer?->title_en) }}"></div>
                        <div class="col-md-6"><label class="form-label">{{ translate('Description (BN)') }}</label><textarea class="form-control" rows="2" name="description_bn">{{ old('description_bn', $editOffer?->description_bn) }}</textarea></div>
                        <div class="col-md-6"><label class="form-label">{{ translate('Description (EN)') }}</label><textarea class="form-control" rows="2" name="description_en">{{ old('description_en', $editOffer?->description_en) }}</textarea></div>
                        <div class="col-md-12 d-flex justify-content-end">
                            <a href="{{ route('admin.business-settings.business-setup', ['tab' => 'ai-chat-board']) }}#offer-section" class="btn btn--reset mr-2">{{ translate('Reset') }}</a>
                            <button type="submit" class="btn btn--primary">{{ $editOffer ? translate('Update') : translate('Add') }}</button>
                        </div>
                    </div>
                </form>

                <div class="table-responsive mt-4">
                    <table class="table table-hover table-borderless table-thead-bordered">
                        <thead class="thead-light"><tr><th>{{ translate('SL') }}</th><th>{{ translate('Title') }}</th><th>{{ translate('Validity') }}</th><th>{{ translate('Priority') }}</th><th>{{ translate('Status') }}</th><th class="text-center">{{ translate('Action') }}</th></tr></thead>
                        <tbody>
                        @forelse($offers as $key => $offer)
                            <tr>
                                <td>{{ $key + $offers->firstItem() }}</td>
                                <td>{{ $offer->title }}</td>
                                <td>{{ $offer->start_date?->format('d M Y') ?? '-' }} - {{ $offer->end_date?->format('d M Y') ?? '-' }}</td>
                                <td>{{ $offer->priority }}</td>
                                <td><span class="badge badge-soft-{{ $offer->is_active ? 'success' : 'danger' }}">{{ $offer->is_active ? translate('Active') : translate('Inactive') }}</span></td>
                                <td class="text-center">
                                    <a class="btn btn-sm btn--primary" href="{{ route('admin.business-settings.business-setup', ['tab' => 'ai-chat-board', 'edit_offer' => $offer->id]) }}#offer-section">{{ translate('Edit') }}</a>
                                    <a class="btn btn-sm btn-outline-info" href="{{ route('admin.business-settings.ai-chat.offer.status', [$offer->id, $offer->is_active ? 0 : 1]) }}">{{ $offer->is_active ? translate('Disable') : translate('Enable') }}</a>
                                    <form action="{{ route('admin.business-settings.ai-chat.offer.destroy', $offer->id) }}" method="post" class="d-inline-block">@csrf @method('delete')<button type="submit" class="btn btn-sm btn-outline-danger">{{ translate('Delete') }}</button></form>
                                </td>
                            </tr>
                        @empty
                            <tr><td colspan="6" class="text-center py-4">{{ translate('No data found') }}</td></tr>
                        @endforelse
                        </tbody>
                    </table>
                </div>
                <div class="d-flex justify-content-end">{!! $offers->withQueryString()->links() !!}</div>
            </div>
        </div>

        <div class="card mb-4" id="faq-section">
            <div class="card-header"><h4 class="mb-0">{{ translate('FAQ Management') }}</h4></div>
            <div class="card-body">
                <form action="{{ $editFaq ? route('admin.business-settings.ai-chat.faq.update', $editFaq->id) : route('admin.business-settings.ai-chat.faq.store') }}" method="post">
                    @csrf
                    @if($editFaq) @method('put') @endif
                    <div class="row g-3">
                        <div class="col-md-4"><label class="form-label">{{ translate('Question') }}</label><input type="text" class="form-control" name="question" value="{{ old('question', $editFaq?->question) }}" required></div>
                        <div class="col-md-2"><label class="form-label">{{ translate('Priority') }}</label><input type="number" class="form-control" name="priority" value="{{ old('priority', $editFaq?->priority ?? 0) }}"></div>
                        <div class="col-md-2"><label class="form-label">{{ translate('Status') }}</label>
                            <select class="form-control" name="is_active">
                                <option value="1" {{ old('is_active', $editFaq?->is_active ?? true) ? 'selected' : '' }}>{{ translate('Active') }}</option>
                                <option value="0" {{ !old('is_active', $editFaq?->is_active ?? true) ? 'selected' : '' }}>{{ translate('Inactive') }}</option>
                            </select>
                        </div>
                        <div class="col-md-4 d-flex align-items-end justify-content-end">
                            <a href="{{ route('admin.business-settings.business-setup', ['tab' => 'ai-chat-board']) }}#faq-section" class="btn btn--reset mr-2">{{ translate('Reset') }}</a>
                            <button type="submit" class="btn btn--primary">{{ $editFaq ? translate('Update') : translate('Add') }}</button>
                        </div>
                        <div class="col-md-6"><label class="form-label">{{ translate('Question (BN)') }}</label><textarea class="form-control" rows="2" name="question_bn">{{ old('question_bn', $editFaq?->question_bn) }}</textarea></div>
                        <div class="col-md-6"><label class="form-label">{{ translate('Question (EN)') }}</label><textarea class="form-control" rows="2" name="question_en">{{ old('question_en', $editFaq?->question_en) }}</textarea></div>
                        <div class="col-md-6"><label class="form-label">{{ translate('Answer (BN)') }}</label><textarea class="form-control" rows="3" name="answer_bn">{{ old('answer_bn', $editFaq?->answer_bn) }}</textarea></div>
                        <div class="col-md-6"><label class="form-label">{{ translate('Answer (EN)') }}</label><textarea class="form-control" rows="3" name="answer_en">{{ old('answer_en', $editFaq?->answer_en) }}</textarea></div>
                    </div>
                </form>

                <div class="table-responsive mt-4">
                    <table class="table table-hover table-borderless table-thead-bordered">
                        <thead class="thead-light"><tr><th>{{ translate('SL') }}</th><th>{{ translate('Question') }}</th><th>{{ translate('Priority') }}</th><th>{{ translate('Status') }}</th><th class="text-center">{{ translate('Action') }}</th></tr></thead>
                        <tbody>
                        @forelse($faqs as $key => $faq)
                            <tr>
                                <td>{{ $key + $faqs->firstItem() }}</td>
                                <td>{{ \Illuminate\Support\Str::limit($faq->question, 90) }}</td>
                                <td>{{ $faq->priority }}</td>
                                <td><span class="badge badge-soft-{{ $faq->is_active ? 'success' : 'danger' }}">{{ $faq->is_active ? translate('Active') : translate('Inactive') }}</span></td>
                                <td class="text-center">
                                    <a class="btn btn-sm btn--primary" href="{{ route('admin.business-settings.business-setup', ['tab' => 'ai-chat-board', 'edit_faq' => $faq->id]) }}#faq-section">{{ translate('Edit') }}</a>
                                    <a class="btn btn-sm btn-outline-info" href="{{ route('admin.business-settings.ai-chat.faq.status', [$faq->id, $faq->is_active ? 0 : 1]) }}">{{ $faq->is_active ? translate('Disable') : translate('Enable') }}</a>
                                    <form action="{{ route('admin.business-settings.ai-chat.faq.destroy', $faq->id) }}" method="post" class="d-inline-block">@csrf @method('delete')<button type="submit" class="btn btn-sm btn-outline-danger">{{ translate('Delete') }}</button></form>
                                </td>
                            </tr>
                        @empty
                            <tr><td colspan="5" class="text-center py-4">{{ translate('No data found') }}</td></tr>
                        @endforelse
                        </tbody>
                    </table>
                </div>
                <div class="d-flex justify-content-end">{!! $faqs->withQueryString()->links() !!}</div>
            </div>
        </div>

        <div class="card mb-4" id="correction-section">
            <div class="card-header"><h4 class="mb-0">{{ translate('Correction / Override System') }}</h4></div>
            <div class="card-body">
                <form action="{{ $editCorrection ? route('admin.business-settings.ai-chat.correction.update', $editCorrection->id) : route('admin.business-settings.ai-chat.correction.store') }}" method="post">
                    @csrf
                    @if($editCorrection) @method('put') @endif
                    <div class="row g-3">
                        <div class="col-md-4"><label class="form-label">{{ translate('Customer Question') }}</label><input type="text" class="form-control" name="question" value="{{ old('question', $editCorrection?->question) }}" required></div>
                        <div class="col-md-2"><label class="form-label">{{ translate('Priority') }}</label><input type="number" class="form-control" name="priority" value="{{ old('priority', $editCorrection?->priority ?? 100) }}"></div>
                        <div class="col-md-2"><label class="form-label">{{ translate('Active') }}</label>
                            <select class="form-control" name="is_active">
                                <option value="1" {{ old('is_active', $editCorrection?->is_active ?? true) ? 'selected' : '' }}>{{ translate('Yes') }}</option>
                                <option value="0" {{ !old('is_active', $editCorrection?->is_active ?? true) ? 'selected' : '' }}>{{ translate('No') }}</option>
                            </select>
                        </div>
                        <div class="col-md-2"><label class="form-label">{{ translate('Approved') }}</label>
                            <select class="form-control" name="is_approved">
                                <option value="1" {{ old('is_approved', $editCorrection?->is_approved ?? false) ? 'selected' : '' }}>{{ translate('Yes') }}</option>
                                <option value="0" {{ !old('is_approved', $editCorrection?->is_approved ?? false) ? 'selected' : '' }}>{{ translate('No') }}</option>
                            </select>
                        </div>
                        <div class="col-md-2 d-flex align-items-end justify-content-end">
                            <a href="{{ route('admin.business-settings.business-setup', ['tab' => 'ai-chat-board']) }}#correction-section" class="btn btn--reset mr-2">{{ translate('Reset') }}</a>
                            <button type="submit" class="btn btn--primary">{{ $editCorrection ? translate('Update') : translate('Add') }}</button>
                        </div>
                        <div class="col-md-6"><label class="form-label">{{ translate('Corrected Answer (BN)') }}</label><textarea class="form-control" rows="3" name="corrected_answer_bn">{{ old('corrected_answer_bn', $editCorrection?->corrected_answer_bn) }}</textarea></div>
                        <div class="col-md-6"><label class="form-label">{{ translate('Corrected Answer (EN)') }}</label><textarea class="form-control" rows="3" name="corrected_answer_en">{{ old('corrected_answer_en', $editCorrection?->corrected_answer_en) }}</textarea></div>
                        <div class="col-md-6"><label class="form-label">{{ translate('Question (BN)') }}</label><textarea class="form-control" rows="2" name="question_bn">{{ old('question_bn', $editCorrection?->question_bn) }}</textarea></div>
                        <div class="col-md-6"><label class="form-label">{{ translate('Question (EN)') }}</label><textarea class="form-control" rows="2" name="question_en">{{ old('question_en', $editCorrection?->question_en) }}</textarea></div>
                        <div class="col-md-12"><label class="form-label">{{ translate('Notes') }}</label><textarea class="form-control" rows="2" name="notes">{{ old('notes', $editCorrection?->notes) }}</textarea></div>
                    </div>
                </form>

                <div class="table-responsive mt-4">
                    <table class="table table-hover table-borderless table-thead-bordered">
                        <thead class="thead-light"><tr><th>{{ translate('SL') }}</th><th>{{ translate('Question') }}</th><th>{{ translate('Priority') }}</th><th>{{ translate('Approved') }}</th><th>{{ translate('Status') }}</th><th class="text-center">{{ translate('Action') }}</th></tr></thead>
                        <tbody>
                        @forelse($corrections as $key => $correction)
                            <tr>
                                <td>{{ $key + $corrections->firstItem() }}</td>
                                <td>{{ \Illuminate\Support\Str::limit($correction->question, 80) }}</td>
                                <td>{{ $correction->priority }}</td>
                                <td><span class="badge badge-soft-{{ $correction->is_approved ? 'success' : 'warning' }}">{{ $correction->is_approved ? translate('Approved') : translate('Pending') }}</span></td>
                                <td><span class="badge badge-soft-{{ $correction->is_active ? 'success' : 'danger' }}">{{ $correction->is_active ? translate('Active') : translate('Inactive') }}</span></td>
                                <td class="text-center">
                                    <a class="btn btn-sm btn--primary" href="{{ route('admin.business-settings.business-setup', ['tab' => 'ai-chat-board', 'edit_correction' => $correction->id]) }}#correction-section">{{ translate('Edit') }}</a>
                                    <a class="btn btn-sm btn-outline-info" href="{{ route('admin.business-settings.ai-chat.correction.status', [$correction->id, $correction->is_active ? 0 : 1]) }}">{{ $correction->is_active ? translate('Disable') : translate('Enable') }}</a>
                                    <a class="btn btn-sm btn-outline-success" href="{{ route('admin.business-settings.ai-chat.correction.approval', [$correction->id, $correction->is_approved ? 0 : 1]) }}">{{ $correction->is_approved ? translate('Unapprove') : translate('Approve') }}</a>
                                    <form action="{{ route('admin.business-settings.ai-chat.correction.destroy', $correction->id) }}" method="post" class="d-inline-block">@csrf @method('delete')<button type="submit" class="btn btn-sm btn-outline-danger">{{ translate('Delete') }}</button></form>
                                </td>
                            </tr>
                        @empty
                            <tr><td colspan="6" class="text-center py-4">{{ translate('No data found') }}</td></tr>
                        @endforelse
                        </tbody>
                    </table>
                </div>
                <div class="d-flex justify-content-end">{!! $corrections->withQueryString()->links() !!}</div>
            </div>
        </div>

        <div class="card" id="logs-section">
            <div class="card-header"><h4 class="mb-0">{{ translate('Recent Chat Logs') }}</h4></div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover table-borderless table-thead-bordered">
                        <thead class="thead-light">
                            <tr>
                                <th>{{ translate('Time') }}</th>
                                <th>{{ translate('Question') }}</th>
                                <th>{{ translate('Source') }}</th>
                                <th>{{ translate('Match %') }}
                                    <span data-toggle="tooltip" title="{{ translate('How closely the AI result matched the customer query. Higher = better match.') }}">
                                        <i class="tio-info-outined text-muted fs-10"></i>
                                    </span>
                                </th>
                                <th>{{ translate('Attempt') }}
                                    <span data-toggle="tooltip" title="{{ translate('Which query attempt found the result (1=exact, 2=relaxed, 3=fallback).') }}">
                                        <i class="tio-info-outined text-muted fs-10"></i>
                                    </span>
                                </th>
                                <th>{{ translate('Fallback') }}</th>
                            </tr>
                        </thead>
                        <tbody>
                        @forelse($logs as $log)
                            @php
                                $pct     = (int) ($log->confidence_score ?? 0);
                                $attempt = (int) ($log->query_attempt ?? 0);
                                $pctClass = $pct >= 80 ? 'success' : ($pct >= 50 ? 'warning' : ($pct > 0 ? 'danger' : 'secondary'));
                                $attemptLabel = $attempt === 1 ? 'Exact' : ($attempt === 2 ? 'Relaxed' : ($attempt === 3 ? 'Fallback' : '-'));
                                $attemptClass = $attempt === 1 ? 'success' : ($attempt === 2 ? 'warning' : 'secondary');
                            @endphp
                            <tr>
                                <td class="text-nowrap">{{ $log->created_at?->format('d M Y h:i A') }}</td>
                                <td>
                                    <div>{{ \Illuminate\Support\Str::limit($log->question, 90) }}</div>
                                    <small class="text-muted">{{ \Illuminate\Support\Str::limit($log->reply, 120) }}</small>
                                </td>
                                <td><span class="badge badge-soft-primary">{{ $log->source_type ?? '-' }}</span></td>
                                <td>
                                    @if($pct > 0)
                                        <span class="badge badge-soft-{{ $pctClass }}">{{ $pct }}%</span>
                                    @else
                                        <span class="text-muted">—</span>
                                    @endif
                                </td>
                                <td>
                                    @if($attempt > 0)
                                        <span class="badge badge-soft-{{ $attemptClass }}">#{{ $attempt }} {{ $attemptLabel }}</span>
                                    @else
                                        <span class="text-muted">—</span>
                                    @endif
                                </td>
                                <td>
                                    @if($log->fallback_used)
                                        <span class="badge badge-soft-warning">{{ translate('Yes') }}</span>
                                    @else
                                        <span class="badge badge-soft-success">{{ translate('No') }}</span>
                                    @endif
                                </td>
                            </tr>
                        @empty
                            <tr><td colspan="6" class="text-center py-4">{{ translate('No data found') }}</td></tr>
                        @endforelse
                        </tbody>
                    </table>
                </div>
                <div class="d-flex justify-content-end">{!! $logs->withQueryString()->links() !!}</div>
            </div>
        </div>
    </div>
@endsection

@push('script_2')
    <script>
        'use strict';

        $(document).on('click', '.copy-to-clipboard', function () {
            const target = $(this).data('target');
            const element = document.querySelector(target);

            if (!element) {
                return;
            }

            navigator.clipboard.writeText(element.value).then(function () {
                toastr.success('Copied to clipboard!');
            });
        });
    </script>
@endpush
