@include('layouts.header')

@php
App::setLocale(Auth::user()->lang);
@endphp

<!-- BEGIN: Content-->
<div class="app-content content ">
    <div class="content-overlay"></div>
    <div class="header-navbar-shadow"></div>
    <div class="content-wrapper">
        <!-- header info start -->
        <div class="row">
            <div class="col-lg-3 col-sm-6">
                <div class="card">
                    <div class="card-body d-flex align-items-center justify-content-between">
                        <div>
                            <h3 class="fw-bolder mb-75">{{ $totalIntents }}</h3>
                            <span>{{ __('Total Intents') }}</span>
                        </div>
                        <div class="avatar bg-light-primary p-50">
                            <span class="avatar-content">
                                <i data-feather="message-circle" class="font-medium-4"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-sm-6">
                <div class="card">
                    <div class="card-body d-flex align-items-center justify-content-between">
                        <div>
                            <h3 class="fw-bolder mb-75">{{ $activeIntents }}</h3>
                            <span>{{ __('Active Intents') }}</span>
                        </div>
                        <div class="avatar bg-light-success p-50">
                            <span class="avatar-content">
                                <i data-feather="check-circle" class="font-medium-4"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-sm-6">
                <div class="card">
                    <div class="card-body d-flex align-items-center justify-content-between">
                        <div>
                            <h3 class="fw-bolder mb-75">{{ $totalSessions }}</h3>
                            <span>{{ __('Total Sessions') }}</span>
                        </div>
                        <div class="avatar bg-light-info p-50">
                            <span class="avatar-content">
                                <i data-feather="users" class="font-medium-4"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-sm-6">
                <div class="card">
                    <div class="card-body d-flex align-items-center justify-content-between">
                        <div>
                            <h3 class="fw-bolder mb-75">{{ $totalResponses }}</h3>
                            <span>{{ __('Total Responses') }}</span>
                        </div>
                        <div class="avatar bg-light-warning p-50">
                            <span class="avatar-content">
                                <i data-feather="send" class="font-medium-4"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- header info end -->
        <div class="content-body">
            <!-- Tabs -->
            <ul class="nav nav-pills mb-2" role="tablist">
                <li class="nav-item">
                    <a class="nav-link active" id="intents-tab" data-bs-toggle="pill" href="#intents" role="tab">
                        <i data-feather="message-circle" class="font-medium-3 me-50"></i>
                        <span class="fw-bold">{{ __('Intents') }}</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" id="sessions-tab" data-bs-toggle="pill" href="#sessions" role="tab">
                        <i data-feather="activity" class="font-medium-3 me-50"></i>
                        <span class="fw-bold">{{ __('Sessions') }}</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" id="responses-tab" data-bs-toggle="pill" href="#responses" role="tab">
                        <i data-feather="mail" class="font-medium-3 me-50"></i>
                        <span class="fw-bold">{{ __('Response Log') }}</span>
                    </a>
                </li>
            </ul>

            <div class="tab-content">
                <!-- Intents Tab -->
                <div class="tab-pane active" id="intents" role="tabpanel">
                    <section class="app-chatbot-intents">
                        <div class="card">
                            <h5 class="card-header">
                                <div class="input-group input-group-sm position-relative mx-auto">
                                    {{ __('Chatbot Intents') }}<span class="badge badge-light-secondary ms-2">{{ $intents->total() }}</span>
                                    <input type="search" class="form-control" id="search-intent" placeholder="{{__('Search')}}..." />
                                    <button type="button" class="btn btn-sm btn-info" id="searchbtn-intent"><i data-feather="search" class="me-0"></i></button>
                                    <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addIntent">
                                        <i data-feather="plus" class="me-1"></i>{{ strtoupper(__('Add Intent')) }}
                                    </button>
                                </div>
                            </h5>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead class="table-light">
                                            <tr>
                                                <th>{{ __('Chatbot') }}</th>
                                                <th>{{ __('Pattern') }}</th>
                                                <th>{{ __('Response') }}</th>
                                                <th>{{ __('Category') }}</th>
                                                <th>{{ __('Priority') }}</th>
                                                <th>{{ __('Status') }}</th>
                                                <th>{{ __('Actions') }}</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @forelse ($intents as $intent)
                                            <tr>
                                                <td><strong>{{ $intent->chatbot->name ?? 'N/A' }}</strong></td>
                                                <td>
                                                    <span class="badge badge-light-primary">{{ \Str::limit($intent->pattern, 30) }}</span>
                                                </td>
                                                <td><small>{{ \Str::limit($intent->response, 50) }}</small></td>
                                                <td><span class="badge badge-light-info">{{ ucfirst($intent->category) }}</span></td>
                                                <td><span class="badge badge-light-secondary">{{ $intent->priority }}</span></td>
                                                <td>
                                                    @if($intent->is_active)
                                                        <span class="badge badge-light-success">{{ __('Active') }}</span>
                                                    @else
                                                        <span class="badge badge-light-secondary">{{ __('Inactive') }}</span>
                                                    @endif
                                                </td>
                                                <td>
                                                    <div class="dropdown">
                                                        <button type="button" class="btn btn-sm btn-icon dropdown-toggle hide-arrow" data-bs-toggle="dropdown">
                                                            <i data-feather="more-vertical"></i>
                                                        </button>
                                                        <div class="dropdown-menu">
                                                            <a class="dropdown-item" href="#" onclick="editIntent({{ $intent->id }})">
                                                                <i data-feather="edit" class="me-50"></i>{{ __('Edit') }}</a>
                                            @empty
                                            <tr>
                                                <td colspan="7" class="text-center text-muted py-4">
                                                    {{ __('No intents found. Create your first intent using the "Add Intent" button above.') }}
                                                </td>
                                            </tr>
                                            @endforelse
                                                            <a class="dropdown-item" href="#" onclick="toggleIntent({{ $intent->id }})">
                                                                <i data-feather="toggle-{{ $intent->is_active ? 'left' : 'right' }}" class="me-50"></i>{{ $intent->is_active ? __('Deactivate') : __('Activate') }}
                                                            </a>
                                                            <a class="dropdown-item text-danger" href="#" onclick="deleteIntent({{ $intent->id }})">
                                                                <i data-feather="trash" class="me-50"></i>{{ __('Delete') }}
                                                            </a>
                                                        </div>
                                                    </div>
                                                </td>
                                            </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                                <div class="d-flex justify-content-center mt-3">
                                    {{ $intents->links() }}
                                </div>
                            </div>
                        </div>
                    </section>
                </div>

                <!-- Sessions Tab -->
                <div class="tab-pane" id="sessions" role="tabpanel">
                    <section class="app-chatbot-sessions">
                        <div class="card">
                            <h5 class="card-header">{{ __('Active Chatbot Sessions') }}</h5>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead class="table-light">
                                            <tr>
                                                <th>{{ __('Session ID') }}</th>
                                                <th>{{ __('User Phone') }}</th>
                                                <th>{{ __('Current State') }}</th>
                                                <th>{{ __('Started') }}</th>
                                                <th>{{ __('Last Activity') }}</th>
                                                <th>{{ __('Actions') }}</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach ($sessions as $session)
                                            <tr>
                                                <td><code>{{ \Str::limit($session->session_id, 20) }}</code></td>
                                                <td><strong>{{ $session->user_phone }}</strong></td>
                                                <td><span class="badge badge-light-primary">{{ $session->current_state ?? 'idle' }}</span></td>
                                                <td>{{ $session->created_at->diffForHumans() }}</td>
                                                <td>{{ $session->updated_at->diffForHumans() }}</td>
                                                <td>
                                                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="viewSession('{{ $session->session_id }}')">
                                                        <i data-feather="eye" class="me-50"></i>{{ __('View') }}
                                                    </button>
                                                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="endSession('{{ $session->session_id }}')">
                                                        <i data-feather="x-circle" class="me-50"></i>{{ __('End') }}
                                                    </button>
                                                </td>
                                            </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                                <div class="d-flex justify-content-center mt-3">
                                    {{ $sessions->links() }}
                                </div>
                            </div>
                        </div>
                    </section>
                </div>

                <!-- Responses Tab -->
                <div class="tab-pane" id="responses" role="tabpanel">
                    <section class="app-chatbot-responses">
                        <div class="card">
                            <h5 class="card-header">{{ __('Response Log') }}</h5>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead class="table-light">
                                            <tr>
                                                <th>{{ __('Session') }}</th>
                                                <th>{{ __('User Phone') }}</th>
                                                <th>{{ __('Intent Matched') }}</th>
                                                <th>{{ __('User Message') }}</th>
                                                <th>{{ __('Bot Response') }}</th>
                                                <th>{{ __('Time') }}</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach ($responses as $response)
                                            <tr>
                                                <td><code>{{ \Str::limit($response->session_id, 15) }}</code></td>
                                                <td>{{ $response->user_phone }}</td>
                                                <td>
                                                    @if($response->intent)
                                                        <span class="badge badge-light-success">{{ $response->intent->intent_name }}</span>
                                                    @else
                                                        <span class="badge badge-light-secondary">{{ __('No match') }}</span>
                                                    @endif
                                                </td>
                                                <td><small>{{ \Str::limit($response->user_message, 40) }}</small></td>
                                                <td><small>{{ \Str::limit($response->bot_response, 40) }}</small></td>
                                                <td>{{ $response->created_at->format('M d, h:i A') }}</td>
                                            </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                                <div class="d-flex justify-content-center mt-3">
                                    {{ $responses->links() }}
                                </div>
                            </div>
                        </div>
                    </section>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- END: Content-->

<!-- Modal Add Intent -->
<div class="modal fade" id="addIntent" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">{{ __('Create New Intent') }}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="{{ route('chatbot.intent.store') }}">
                @csrf
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">{{ __('Select Chatbot') }}*</label>
                        <select name="chatbot_id" class="form-select" required>
                            <option value="">{{ __('Choose a chatbot') }}</option>
                            @foreach($chatbots as $bot)
                                <option value="{{ $bot->id }}">{{ $bot->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">{{ __('Pattern') }}*</label>
                        <input type="text" name="pattern" class="form-control" placeholder="e.g., hello, hi, hey" required>
                        <small class="text-muted">{{ __('Keywords or phrases that trigger this response') }}</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">{{ __('Response Text') }}*</label>
                        <textarea name="response" class="form-control" rows="4" required placeholder="{{ __('Hello! How can I help you today?') }}"></textarea>
                        <small class="text-muted">{{ __('The message to send when this intent is matched') }}</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">{{ __('Category') }}</label>
                        <select name="category" class="form-select">
                            <option value="general" selected>{{ __('General') }}</option>
                            <option value="greeting">{{ __('Greeting') }}</option>
                            <option value="faq">{{ __('FAQ') }}</option>
                            <option value="support">{{ __('Support') }}</option>
                            <option value="sales">{{ __('Sales') }}</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">{{ __('Priority') }}</label>
                        <select name="priority" class="form-select">
                            <option value="0" selected>{{ __('Low') }}</option>
                            <option value="5">{{ __('Medium') }}</option>
                            <option value="10">{{ __('High') }}</option>
                        </select>
                        <small class="text-muted">{{ __('Higher priority intents are matched first') }}</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ __('Cancel') }}</button>
                    <button type="submit" class="btn btn-primary">{{ __('Create Intent') }}</button>
                </div>
            </form>
        </div>
    </div>
</div>

@include('layouts.footer')

<script>
function toggleIntent(id) {
    fetch('/chatbot-intent-toggle', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
        },
        body: JSON.stringify({ intent_id: id })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        }
    });
}

function deleteIntent(id) {
    if (confirm('{{ __("Delete this intent? This cannot be undone.") }}')) {
        window.location.href = `/chatbot-intent-destroy?intent_id=${id}`;
    }
}

function endSession(sessionId) {
    if (confirm('{{ __("End this chatbot session?") }}')) {
        fetch('/chatbot-session-end', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            },
            body: JSON.stringify({ session_id: sessionId })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                location.reload();
            }
        });
    }
}

// Re-initialize Feather icons after tab switch
document.querySelectorAll('a[data-bs-toggle="pill"]').forEach(tab => {
    tab.addEventListener('shown.bs.tab', function() {
        feather.replace();
    });
});
</script>
