@extends('admin.gateway.index')
@section('tab-content')

<div class="tab-pane active fade show" id="{{url()->current()}}" role="tabpanel">
    <div class="table-filter mb-4">
        <form action="{{route(Route::currentRouteName())}}" class="filter-form">
            
            <div class="row g-3">
                <div class="col-xxl-3 col-xl-4 col-lg-4">
                    <div class="filter-search">
                        <input type="search" value="{{request()->search}}" name="search" class="form-control" id="filter-search" placeholder="{{ translate("Search by Name") }}" />
                        <span><i class="ri-search-line"></i></span>
                    </div>
                </div>

                <div class="col-xxl-5 col-xl-6 col-lg-7 offset-xxl-4 offset-xl-2">
                    <div class="filter-action">

                        <div class="input-group">
                            <input type="text" class="form-control" id="datePicker" name="date" value="{{request()->input('date')}}"  placeholder="{{translate('Filter by date')}}"  aria-describedby="filterByDate">
                            <span class="input-group-text" id="filterByDate">
                                <i class="ri-calendar-2-line"></i>
                            </span>
                        </div>

                        <div class="d-flex align-items-center gap-3">
                            <button type="submit" class="filter-action-btn ">
                                <i class="ri-menu-search-line"></i> {{ translate("Filter") }}
                            </button>
                            <a class="filter-action-btn bg-danger text-white" href="{{route(Route::currentRouteName())}}">
                                <i class="ri-refresh-line"></i> {{ translate("Reset") }}
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>

    {{-- Node Service Status Card --}}
    @if(isset($serverHealth))
    <div class="card mb-3">
        <div class="card-body">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h6 class="mb-0">
                        <i class="ri-server-line"></i> {{ translate('WhatsApp Node Service') }}
                    </h6>
                    <small class="text-muted">{{ env('WP_SERVER_URL', 'http://127.0.0.1:3001') }}</small>
                </div>
                <div class="col-md-4 text-end">
                    @if($serverHealth['healthy'])
                        <span class="badge bg-success">
                            <i class="ri-checkbox-circle-line"></i> {{ translate('Online') }}
                        </span>
                        @if(isset($serverHealth['data']->uptime))
                            <small class="text-muted ms-2 d-block mt-1">
                                {{ translate('Uptime:') }} {{ round($serverHealth['data']->uptime, 2) }}s
                            </small>
                        @endif
                    @else
                        <span class="badge bg-danger">
                            <i class="ri-close-circle-line"></i> {{ translate('Offline') }}
                        </span>
                        @if(isset($serverHealth['error']))
                            <small class="text-danger ms-2 d-block mt-1">
                                {{ $serverHealth['error'] }}
                            </small>
                        @endif
                    @endif
                </div>
            </div>
        </div>
    </div>
    @endif

    <div class="card">
        <div class="card-header">
            <div class="card-header-left">
                <h4 class="card-title">{{$title}}</h4>
            </div>
            <div class="card-header-right">
                <button class="i-btn btn--info btn--sm whatsapp-server-settings" type="button" data-bs-toggle="modal" data-bs-target="#whatsappServerSetting">
                    <i class="ri-server-line"></i> {{ translate("Server Settings") }}
                </button>
                @if($serverStatus)
                    <button class="i-btn btn--primary btn--sm add-whatsapp-device" type="button" data-bs-toggle="modal" data-bs-target="#addWhatsappDevice">
                        <i class="ri-add-fill fs-16"></i> {{ translate("Add Whatsapp Device") }}
                    </button>
                @endif
            </div>
        </div>
        @if($serverStatus)
            <div class="card-body px-0 pt-0">
                <div class="table-container">
                    <table>
                        <thead>
                            <tr>
                                <th scope="col">{{ translate("Session Name") }}</th>
                                <th scope="col">{{ translate("WhatsApp Number") }}</th>
                                <th scope="col">{{ translate("Delay Settings") }}</th>
                                <th scope="col">{{ translate("Status") }}</th>
                                <th scope="col">{{ translate("Option") }}</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse ($gateways as $item)
                                <tbody>
                                <tr>
                                    <td data-label="{{translate('Session Name')}}">{{$item->name}}</td>
                                    <td data-label="{{translate('WhatsApp Number')}}">
                                        {{ \Illuminate\Support\Arr::get($item->meta_data, "number", translate("N/A")) }}
                                    </td>
                                    <td data-label="{{translate('Delay Settings')}}" >
                                        <div class="d-flex flex-column gap-1 align-items-start ">
                                            <span>{{ translate("Per Message Minimum Delay (Seconds): ") }}{{ $item->per_message_min_delay }}</span>
                                            <span>{{ translate("Per Message Minimum Delay (Seconds): ") }}{{ $item->per_message_max_delay }}</span>
                                            <span>{{ translate("Delay After Count (Quantity): ") }}{{ $item->delay_after_count }}</span>
                                            <span>{{ translate("Delay After Duration (Seconds): ") }}{{ $item->delay_after_duration }}</span>
                                            <span>{{ translate("Reset After Count (Quantity): ") }}{{ $item->reset_after_count }}</span>
                                        </div>
                                    </td>
                                    <td data-label="{{translate('Status')}}">
                                        {{ $item->status->badge() }}

                                    </td>
                                    <td data-label={{ translate('Option')}}>
                                        <div class="d-flex align-items-center gap-1">
                                            <button class="icon-btn btn-ghost btn-sm info-soft circle update-whatsapp-device"
                                                    type="button"
                                                    data-url="{{ route('admin.gateway.whatsapp.device.update', ['id' => $item->id])}}"
                                                    data-per_message_min_delay="{{$item->per_message_min_delay}}"
                                                    data-per_message_max_delay="{{$item->per_message_max_delay}}"
                                                    data-delay_after_count="{{$item->delay_after_count}}"
                                                    data-delay_after_duration="{{$item->delay_after_duration}}"
                                                    data-reset_after_count="{{$item->reset_after_count}}"
                                                    data-bs-toggle="modal"
                                                    data-bs-target="#updateWhatsappDevice">
                                                <i class="ri-edit-line"></i>
                                                <span class="tooltiptext"> {{ translate("Update whatsapp device") }} </span>
                                            </button>
                                            @if($item->status == \App\Enums\Common\Status::INACTIVE)
                                                <button class="icon-btn btn-ghost btn-sm success-soft circle qrQuote textChange{{$item->id}}"
                                                        value="{{$item->id}}"
                                                        type="button"
                                                        data-bs-toggle="offcanvas"
                                                        data-bs-target="#offcanvasQrCode"
                                                        aria-controls="offcanvasQrCode">

                                                    <i class="ri-qr-code-fill"></i>
                                                    <span class="tooltiptext"> {{ translate("Scan") }} </span>
                                                </button>

                                            @elseif($item->status == \App\Enums\Common\Status::ACTIVE)
                                                <button class="icon-btn btn-ghost btn-sm danger-soft circle deviceDisconnection{{$item->id}}"
                                                        onclick="return deviceStatusUpdate('{{$item->id}}','disconnected','deviceDisconnection','Disconnecting','Connect')"
                                                        value="{{$item->id}}"
                                                        type="button">

                                                        <i class="ri-wifi-off-fill"></i>
                                                    <span class="tooltiptext"> {{ translate("Disconnect") }} </span>
                                                </button>

                                            @else
                                            
                                                <button class="icon-btn btn-ghost btn-sm success-soft circle qrQuote textChange{{$item->id}}"
                                                    value="{{$item->id}}"
                                                    type="button"
                                                    data-bs-toggle="offcanvas"
                                                    data-bs-target="#offcanvasQrCode"
                                                    aria-controls="offcanvasQrCode">

                                                <i class="ri-qr-code-fill"></i>
                                                <span class="tooltiptext"> {{ translate("Scan") }} </span>
                                            </button>
                                            @endif

                                            <button class="icon-btn btn-ghost btn-sm info-soft circle text-info quick-view"
                                                    type="button"
                                                    data-uid="{{$item->uid}}"
                                                    data-bs-toggle="modal"
                                                    data-bs-target="#quick_view">
                                                    <i class="ri-information-line"></i>
                                                <span class="tooltiptext"> {{ translate("Quick View") }} </span>
                                            </button>
                                            <button class="icon-btn btn-ghost btn-sm danger-soft circle text-danger delete-whatsapp-device"
                                                type="button"
                                                data-item-id="{{ $item->id }}"
                                                data-url="{{route('admin.gateway.whatsapp.device.destroy', ['id' => $item->id ])}}" 
                                                data-bs-toggle="modal"
                                                data-bs-target="#deleteWhatsappDevice">
                                            <i class="ri-delete-bin-line"></i>
                                            <span class="tooltiptext"> {{ translate("Delete Whatsapp device") }} </span>
                                        </button>
                                        </div>
                                    </td>
                                </tr>
                                </tbody>
                            @empty
                                <tbody>
                                <tr>
                                    <td colspan="50"><span class="text-danger">{{ translate('No data Available')}}</span></td>
                                </tr>
                                </tbody>
                            @endforelse
                        </tbody>
                    </table>
                </div>
                @include('admin.partials.pagination', ['paginator' => $gateways])
            </div>
        @else
            <div class="card">
                <div class="card-header">
                   <span>{{ translate('Node Server Offline')}} <i class="fas fa-info-circle"></i></span>

                    <div class="header-with-btn">
                        <span class="d-flex align-items-center gap-2"> 
                            <a href="" class="badge badge--primary"> <i class="fas fa-refresh"></i>  {{ translate('Try Again') }}</a>
                        </span>
                    </div>

                </div>

                <div class="card-body">
                    <h6 class="text--danger">{{ translate('Unable to connect to WhatsApp node server. Please configure the server settings and try again.') }}</h6>
                </div>
            </div>
        @endif
    </div>
</div>

@endsection

@section('modal')

<div class="modal fade" id="whatsappServerSetting" tabindex="-1" aria-labelledby="addWhatsappDevice" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered ">
        <div class="modal-content">
            <form action="{{route('admin.gateway.whatsapp.device.server.update')}}" method="POST" id="serverSettingsForm">
                @csrf
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">
                        <i class="ri-server-line"></i> {{ translate("Configure Server Settings") }}
                    </h5>
                    <button type="button" class="icon-btn btn-ghost btn-sm danger-soft circle modal-closer" data-bs-dismiss="modal">
                        <i class="ri-close-large-line"></i>
                    </button>
                </div>
                <div class="modal-body modal-lg-custom-height">
                    <div class="row g-4">

                        <!-- Health Status Card -->
                        <div class="col-lg-12">
                            <div class="alert alert-info mb-0" role="alert">
                                <div class="d-flex align-items-center justify-content-between">
                                    <div>
                                        <i class="ri-heart-pulse-line"></i>
                                        <strong>{{ translate('Node Service Status:') }}</strong>
                                        <span id="healthStatus" class="ms-2">
                                            <span class="spinner-border spinner-border-sm"></span> {{ translate('Checking...') }}
                                        </span>
                                        <span id="syncStatus" class="ms-2" style="display: none;"></span>
                                    </div>
                                    <div class="btn-group">
                                        <button type="button" class="btn btn-sm btn-info" id="checkHealthBtn">
                                            <i class="ri-refresh-line"></i> {{ translate('Refresh') }}
                                        </button>
                                        <button type="button" class="btn btn-sm btn-warning" id="reinitializeBtn" title="{{ translate('Reinitialize connection and push configuration') }}">
                                            <i class="ri-restart-line"></i> {{ translate('Reinitialize') }}
                                        </button>
                                    </div>
                                </div>
                                <div id="healthDetails" class="mt-2" style="display: none;">
                                    <small class="text-muted">
                                        <i class="ri-time-line"></i> <span id="healthUptime"></span>
                                    </small>
                                </div>
                            </div>
                        </div>

                        <!-- Server URL (readonly) -->
                        <div class="col-lg-12">
                            <div class="form-inner">
                                <label for="server_url" class="form-label">
                                    {{ translate('WhatsApp Server URL')}}
                                    <span class="text-danger">*</span>
                                </label>
                                <input type="text"
                                       id="server_url"
                                       name="server_url"
                                       class="form-control"
                                       value="{{ env('WP_SERVER_URL', 'http://127.0.0.1:3001') }}"
                                       readonly/>
                                <small class="text-muted">{{ translate('This is auto-generated from host and port') }}</small>
                            </div>
                        </div>

                        <!-- Server Host -->
                        <div class="col-lg-6">
                            <div class="form-inner">
                                <label for="server_host" class="form-label">
                                    {{ translate('Server Host')}}
                                    <span class="text-danger">*</span>
                                </label>
                                <input type="text"
                                       id="server_host"
                                       name="server_host"
                                       placeholder="{{ translate('127.0.0.1')}}"
                                       class="form-control"
                                       value="{{ env('WP_SERVER_HOST', '127.0.0.1') }}"
                                       required/>
                            </div>
                        </div>

                        <!-- Server Port -->
                        <div class="col-lg-6">
                            <div class="form-inner">
                                <label for="server_port" class="form-label">
                                    {{ translate('Server Port')}}
                                    <span class="text-danger">*</span>
                                </label>
                                <input type="number"
                                       id="server_port"
                                       name="server_port"
                                       placeholder="{{ translate('3001')}}"
                                       class="form-control"
                                       value="{{ env('WP_SERVER_PORT', '3001') }}"
                                       required/>
                            </div>
                        </div>

                        <!-- API Key with Generate Button -->
                        <div class="col-lg-12">
                            <div class="form-inner">
                                <label for="wp_api_key" class="form-label">
                                    {{ translate('API Key')}}
                                    <span class="text-danger">*</span>
                                </label>
                                <div class="input-group">
                                    <input type="text"
                                           id="wp_api_key"
                                           name="wp_api_key"
                                           placeholder="{{ translate('Click Generate to create secure API key')}}"
                                           class="form-control font-monospace"
                                           value="{{ env('WP_API_KEY', '') }}"
                                           required/>
                                    <button type="button" class="btn btn-primary" id="generateApiKeyBtn">
                                        <i class="ri-refresh-line"></i> {{ translate('Generate') }}
                                    </button>
                                </div>
                                <small class="text-muted">
                                    <i class="ri-lock-line"></i> {{ translate('Secure key for Laravel-Node communication') }}
                                </small>
                            </div>
                        </div>

                        <!-- Post-Save Instructions (Collapsible) -->
                        <div class="col-lg-12">
                            <div class="card border-warning">
                                <div class="card-header bg-warning bg-opacity-10 py-2" style="cursor: pointer;" data-bs-toggle="collapse" data-bs-target="#postSaveInstructions">
                                    <div class="d-flex align-items-center justify-content-between">
                                        <span>
                                            <i class="ri-information-line text-warning"></i>
                                            <strong class="text-warning">{{ translate('Important: After Save Instructions') }}</strong>
                                        </span>
                                        <i class="ri-arrow-down-s-line" id="instructionsToggleIcon"></i>
                                    </div>
                                </div>
                                <div class="collapse" id="postSaveInstructions">
                                    <div class="card-body py-3">
                                        <p class="mb-2 small text-muted">{{ translate('After saving, the system will automatically sync configuration. If auto-sync fails, follow these steps:') }}</p>

                                        <div class="mb-3">
                                            <strong class="text-dark"><i class="ri-server-line"></i> {{ translate('For VPS/Dedicated Server (PM2):') }}</strong>
                                            <div class="bg-dark text-light p-2 rounded mt-1 position-relative">
                                                <code class="small">cd /path/to/xsender-whatsapp-service && pm2 restart ecosystem.config.cjs</code>
                                                <button type="button" class="btn btn-sm btn-outline-light position-absolute top-0 end-0 m-1 copy-cmd-btn" data-cmd="cd /path/to/xsender-whatsapp-service && pm2 restart ecosystem.config.cjs">
                                                    <i class="ri-file-copy-line"></i>
                                                </button>
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <strong class="text-dark"><i class="ri-cloud-line"></i> {{ translate('For cPanel:') }}</strong>
                                            <ol class="small mb-0 ps-3">
                                                <li>{{ translate('Go to cPanel → Setup Node.js App') }}</li>
                                                <li>{{ translate('Find your WhatsApp application') }}</li>
                                                <li>{{ translate('Click "Restart" button') }}</li>
                                            </ol>
                                        </div>

                                        <div class="mb-2">
                                            <strong class="text-dark"><i class="ri-terminal-line"></i> {{ translate('Clear Laravel Cache (if needed):') }}</strong>
                                            <div class="bg-dark text-light p-2 rounded mt-1 position-relative">
                                                <code class="small">php artisan config:clear && php artisan cache:clear</code>
                                                <button type="button" class="btn btn-sm btn-outline-light position-absolute top-0 end-0 m-1 copy-cmd-btn" data-cmd="php artisan config:clear && php artisan cache:clear">
                                                    <i class="ri-file-copy-line"></i>
                                                </button>
                                            </div>
                                        </div>

                                        <div class="alert alert-info py-2 mb-0 mt-3 small">
                                            <i class="ri-lightbulb-line"></i>
                                            <strong>{{ translate('Tip:') }}</strong> {{ translate('Click "Reinitialize" button above to force sync without restarting Node service.') }}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Allowed Origins -->
                        <div class="col-lg-12">
                            <div class="form-inner">
                                <label for="wp_allowed_origins" class="form-label">
                                    {{ translate('Allowed Origins')}}
                                    <span class="text-danger">*</span>
                                </label>
                                <input type="text"
                                       id="wp_allowed_origins"
                                       name="wp_allowed_origins"
                                       placeholder="{{ translate('http://xsender.test,https://yourdomain.com')}}"
                                       class="form-control"
                                       value="{{ env('WP_ALLOWED_ORIGINS', env('APP_URL', request()->root())) }}"
                                       readonly/>
                                <small class="text-muted">
                                    <i class="ri-global-line"></i> {{ translate('Auto-configured from APP_URL environment variable') }}
                                </small>
                            </div>
                        </div>

                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="i-btn btn--danger outline btn--md" data-bs-dismiss="modal">
                        {{ translate("Close") }}
                    </button>
                    <button type="submit" class="i-btn btn--primary btn--md">
                        <i class="ri-save-line"></i> {{ translate("Save Configuration") }}
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="addWhatsappDevice" tabindex="-1" aria-labelledby="addWhatsappDevice" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered ">
        <div class="modal-content">
            <form action="{{route('admin.gateway.whatsapp.device.store')}}" method="POST">
                @csrf
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel"> {{ translate("Add WhatsApp Device") }} </h5>
                    <button type="button" class="icon-btn btn-ghost btn-sm danger-soft circle modal-closer" data-bs-dismiss="modal">
                        <i class="ri-close-large-line"></i>
                    </button>
                </div>
                <div class="modal-body modal-lg-custom-height">
                    <div class="row g-4">
                        <div class="col-12">
                            <div class="form-inner">
                                <label for="name" class="form-label">{{ translate('Session/Device Name')}}<span class="text-danger">*</span></label>
                                <input type="text" id="name" name="name" placeholder="{{ translate('Enter whatsapp session name')}}" class="form-control" aria-label="name"/>
                            </div>
                        </div>
                        <div class="col-lg-6">
                            <div class="form-inner">
                                <label for="per_message_min_delay" class="form-label"> {{ translate('Per Message Minimum Delay (Seconds)')}}<span class="text-danger">*</span> </label>
                                <input type="number" id="per_message_min_delay" name="per_message_min_delay"  placeholder="{{ translate('e.g., 0.5 seconds minimum delay per message') }}" class="form-control" aria-label="per_message_min_delay"/>
                            </div>
                        </div>
                        <div class="col-lg-6">
                            <div class="form-inner">
                                <label for="per_message_max_delay" class="form-label"> {{ translate('Per Message Maximum Delay (Seconds)')}}<span class="text-danger">*</span> </label>
                                <input type="number" id="per_message_max_delay" name="per_message_max_delay" placeholder="{{ translate('e.g., 0.5 seconds max delay per message') }}" class="form-control" aria-label="per_message_max_delay"/>
                            </div>
                        </div>
                        <div class="col-lg-6">
                            <div class="form-inner">
                                <label for="delay_after_count" class="form-label">{{ translate('Delay After Count') }}<span class="text-danger">*</span></label>
                                <input type="number" min="0" step="1" id="delay_after_count" name="delay_after_count" placeholder="{{ translate('e.g., pause after 50 messages') }}" class="form-control" aria-label="Delay After Count"/>
                            </div>
                        </div>
                        
                        <div class="col-lg-6">
                            <div class="form-inner">
                                <label for="delay_after_duration" class="form-label">{{ translate('Delay After Duration (Seconds)') }}<span class="text-danger">*</span></label>
                                <input type="number" min="0" step="0.1" id="delay_after_duration" name="delay_after_duration" placeholder="{{ translate('e.g., pause for 5 seconds') }}" class="form-control" aria-label="Delay After Duration"/>
                            </div>
                        </div>
                        
                        <div class="col-12">
                            <div class="form-inner">
                                <label for="reset_after_count" class="form-label">{{ translate('Reset After Count') }}<span class="text-danger">*</span></label>
                                <input type="number" min="0" step="1" id="reset_after_count" name="reset_after_count" placeholder="{{ translate('e.g., reset after 200 messages') }}" class="form-control" aria-label="Reset After Count"/>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="i-btn btn--danger outline btn--md" data-bs-dismiss="modal"> {{ translate("Close") }} </button>
                    <button type="submit" class="i-btn btn--primary btn--md"> {{ translate("Save") }} </button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="updateWhatsappDevice" tabindex="-1" aria-labelledby="updateWhatsappDevice" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered ">
        <div class="modal-content">
            <form id="updateWhatsappGatewayForm" method="POST">
                @csrf
                <input type="hidden" name="_method" value="PATCH">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel"> {{ translate("Update WhatsApp Device") }} </h5>
                    <button type="button" class="icon-btn btn-ghost btn-sm danger-soft circle modal-closer" data-bs-dismiss="modal">
                        <i class="ri-close-large-line"></i>
                    </button>
                </div>
                <div class="modal-body modal-lg-custom-height">
                    <div class="row g-4">
                        <div class="col-lg-6">
                            <div class="form-inner">
                                <label for="per_message_min_delay" class="form-label"> {{ translate('Per Message Minimum Delay (Seconds)')}}<span class="text-danger">*</span> </label>
                                <input type="number" id="per_message_min_delay" name="per_message_min_delay"  placeholder="{{ translate('e.g., 0.5 seconds minimum delay per message') }}" class="form-control" aria-label="per_message_min_delay"/>
                            </div>
                        </div>
                        <div class="col-lg-6">
                            <div class="form-inner">
                                <label for="per_message_max_delay" class="form-label"> {{ translate('Per Message Maximum Delay (Seconds)')}}<span class="text-danger">*</span> </label>
                                <input type="number" id="per_message_max_delay" name="per_message_max_delay" placeholder="{{ translate('e.g., 0.5 seconds max delay per message') }}" class="form-control" aria-label="per_message_max_delay"/>
                            </div>
                        </div>
                        <div class="col-lg-6">
                            <div class="form-inner">
                                <label for="delay_after_count" class="form-label">{{ translate('Delay After Count') }}<span class="text-danger">*</span></label>
                                <input type="number" min="0" step="1" id="delay_after_count" name="delay_after_count" placeholder="{{ translate('e.g., pause after 50 messages') }}" class="form-control" aria-label="Delay After Count"/>
                            </div>
                        </div>
                        
                        <div class="col-lg-6">
                            <div class="form-inner">
                                <label for="delay_after_duration" class="form-label">{{ translate('Delay After Duration (Seconds)') }}<span class="text-danger">*</span></label>
                                <input type="number" min="0" step="0.1" id="delay_after_duration" name="delay_after_duration" placeholder="{{ translate('e.g., pause for 5 seconds') }}" class="form-control" aria-label="Delay After Duration"/>
                            </div>
                        </div>
                        
                        <div class="col-12">
                            <div class="form-inner">
                                <label for="reset_after_count" class="form-label">{{ translate('Reset After Count') }}<span class="text-danger">*</span></label>
                                <input type="number" min="0" step="1" id="reset_after_count" name="reset_after_count" placeholder="{{ translate('e.g., reset after 200 messages') }}" class="form-control" aria-label="Reset After Count"/>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="i-btn btn--danger outline btn--md" data-bs-dismiss="modal"> {{ translate("Close") }} </button>
                    <button type="submit" class="i-btn btn--primary btn--md"> {{ translate("Save") }} </button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade actionModal" id="deleteWhatsappDevice" tabindex="-1" aria-labelledby="deleteWhatsappDevice" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered ">
        <div class="modal-content">
        <div class="modal-header text-start">
            <span class="action-icon danger">
            <i class="bi bi-exclamation-circle"></i>
            </span>
        </div>
        <form method="POST"  id="deleteWhatsappGateway">
            @csrf
            <div class="modal-body">
                <input type="hidden" name="_method" value="DELETE">
                <div class="action-message">
                    <h5>{{ translate("Are you sure to delete this WhatsApp device?") }}</h5>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="i-btn btn--dark outline btn--lg" data-bs-dismiss="modal"> {{ translate("Cancel") }} </button>
                <button type="submit" class="i-btn btn--danger btn--lg" data-bs-dismiss="modal"> {{ translate("Delete") }} </button>
            </div>
        </form>
        </div>
    </div>
</div>

<div class="modal fade" id="quick_view" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered ">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">{{ translate("Email Gateway Information") }}</h5>
                <button type="button" class="icon-btn btn-ghost btn-sm danger-soft circle modal-closer" data-bs-dismiss="modal">
                    <i class="ri-close-line"></i>
                </button>
            </div>
            <div class="modal-body">
                <ul class="information-list"></ul>
            </div>
            <div class="modal-footer">
                <button type="button" class="i-btn btn--danger outline btn--md" data-bs-dismiss="modal">{{ translate("Close") }}</button>
                <button type="button" class="i-btn btn--primary btn--md">{{ translate("Save") }}</button>
            </div>
        </div>
    </div>
</div>

{{-- <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasQrCode" aria-labelledby="offcanvasQrCode" data-bs-backdrop="static">
    <div class="offcanvas-header justify-content-between bg-light">
        <h5 class="offcanvas-title" id="offcanvasExampleLabel">{{ translate("Connect Whatsapp") }}</h5>
        <button
            type="button"
            class="icon-btn btn-sm dark-soft hover circle modal-closer"
            data-bs-dismiss="offcanvas"
            onclick="return deviceStatusUpdate('','initiate','','','')">
            <i class="ri-close-large-line"></i>
        </button>
    </div>
    <div class="offcanvas-body p-0">
        <div class="d-flex flex-column justify-content-between h-100">
        <div class="p-3">
            <input type="hidden" name="scan_id" id="scan_id" value="">
            <ul class="information-list border-0 p-0">

            <li>
                <p>{{ translate('1. Open WhatsApp on your phone')}}</p>
            </li>

            <li>
                <p>{{ translate('2. Tap Menu  or Settings  and select Linked Devices')}}</p>
            </li>

            <li>
                <p>{{ translate('3. Point your phone to this screen to capture the code')}}</p>
            </li>
            </ul>
            <div class="qr-code mt-5">
                <img id="qrcode" src="" alt="">
            </div>
        </div>

        <div class="py-xl-5 py-4 px-3 bg-light mt-5">
            <div class="text-center  h-100">
                <h6 class="mb-2">{{ translate("Tutorial") }}</h6>
                <a class="fs-14 text-info" href="https://support.igensolutionsltd.com/help-center"><i class="ri-information-2-line fs-18"></i>{{ translate("Need help to get started?") }}</a>

                <div class="mt-4">
                <img src="https://static.whatsapp.net/rsrc.php/v3/yB/r/7Y1jh45L_8V.png" alt="whatsapp">
                </div>
            </div>
        </div>
        </div>
    </div>
</div> --}}

<!-- Post-Save Instructions Modal -->
<div class="modal fade" id="postSaveModal" tabindex="-1" aria-labelledby="postSaveModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header" id="postSaveModalHeader">
                <h5 class="modal-title" id="postSaveModalLabel">
                    <i class="ri-checkbox-circle-line text-success"></i> {{ translate('Configuration Saved') }}
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="postSaveSuccess" style="display: none;">
                    <div class="alert alert-success">
                        <i class="ri-checkbox-circle-fill"></i>
                        <strong>{{ translate('Success!') }}</strong>
                        {{ translate('Configuration saved and synced with Node service automatically.') }}
                    </div>
                    <p class="text-muted small mb-0">
                        <i class="ri-information-line"></i>
                        {{ translate('No further action required. The Node service has been updated with the new configuration.') }}
                    </p>
                </div>

                <div id="postSaveWarning" style="display: none;">
                    <div class="alert alert-warning">
                        <i class="ri-alert-fill"></i>
                        <strong>{{ translate('Saved with Warning') }}</strong>
                        {{ translate('Configuration saved but auto-sync failed. Manual action required.') }}
                    </div>

                    <p class="fw-bold mb-2">{{ translate('Please follow these steps:') }}</p>

                    <div class="accordion" id="postSaveAccordion">
                        <div class="accordion-item">
                            <h2 class="accordion-header">
                                <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseVPS">
                                    <i class="ri-server-line me-2"></i> {{ translate('VPS / Dedicated Server') }}
                                </button>
                            </h2>
                            <div id="collapseVPS" class="accordion-collapse collapse show" data-bs-parent="#postSaveAccordion">
                                <div class="accordion-body">
                                    <p class="small text-muted mb-2">{{ translate('Run these commands via SSH:') }}</p>
                                    <div class="bg-dark text-light p-2 rounded position-relative mb-2">
                                        <code class="small d-block">cd /path/to/xsender-whatsapp-service</code>
                                        <code class="small d-block">pm2 restart ecosystem.config.cjs</code>
                                        <button type="button" class="btn btn-sm btn-outline-light position-absolute top-0 end-0 m-1 copy-cmd-btn" data-cmd="cd /path/to/xsender-whatsapp-service && pm2 restart ecosystem.config.cjs">
                                            <i class="ri-file-copy-line"></i>
                                        </button>
                                    </div>
                                    <p class="small text-muted mb-0">{{ translate('Then clear Laravel cache:') }}</p>
                                    <div class="bg-dark text-light p-2 rounded position-relative">
                                        <code class="small">php artisan config:clear && php artisan cache:clear</code>
                                        <button type="button" class="btn btn-sm btn-outline-light position-absolute top-0 end-0 m-1 copy-cmd-btn" data-cmd="php artisan config:clear && php artisan cache:clear">
                                            <i class="ri-file-copy-line"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="accordion-item">
                            <h2 class="accordion-header">
                                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseCPanel">
                                    <i class="ri-cloud-line me-2"></i> {{ translate('cPanel Hosting') }}
                                </button>
                            </h2>
                            <div id="collapseCPanel" class="accordion-collapse collapse" data-bs-parent="#postSaveAccordion">
                                <div class="accordion-body">
                                    <ol class="small mb-0">
                                        <li class="mb-1">{{ translate('Login to your cPanel dashboard') }}</li>
                                        <li class="mb-1">{{ translate('Navigate to "Setup Node.js App"') }}</li>
                                        <li class="mb-1">{{ translate('Find your WhatsApp service application') }}</li>
                                        <li class="mb-1">{{ translate('Click the "Restart" button') }}</li>
                                        <li>{{ translate('Wait 10-15 seconds, then refresh this page') }}</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="alert alert-info mt-3 mb-0 py-2">
                        <i class="ri-lightbulb-line"></i>
                        <strong>{{ translate('Alternative:') }}</strong>
                        {{ translate('Close this modal and click "Reinitialize" button in the Server Settings.') }}
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ translate('Close') }}</button>
                <button type="button" class="btn btn-primary" onclick="location.reload();">
                    <i class="ri-refresh-line"></i> {{ translate('Refresh Page') }}
                </button>
            </div>
        </div>
    </div>
</div>

@php
    $channel = \App\Enums\System\ChannelTypeEnum::WHATSAPP->value;
    $title = translate('Connect WhatsApp Session');
    $settingKey = \App\Enums\SettingKey::WHATSAPP_OFF_CANVAS_GUIDE->value;

    $guide = site_settings($settingKey);
    if ($guide) $guide = json_decode($guide, true);
    $writtenGuide = \Illuminate\Support\Arr::get($guide, 'written_guide.message', config("setting.{$settingKey}.written_guide.message"));
    $externalText = \Illuminate\Support\Arr::get($guide, 'external_guide.text', config("setting.{$settingKey}.external_guide.text"));
    $externalLink = \Illuminate\Support\Arr::get($guide, 'external_guide.link', config("setting.{$settingKey}.external_guide.link"));
    $imageName = \Illuminate\Support\Arr::get($guide, 'image.name', config("setting.{$settingKey}.image.name"));

    // Construct the image path with fallback
    
    $primaryPath = config("setting.file_path.{$settingKey}.path") . '/' . $imageName;
    
    $fallbackPath = config("setting.file_path.{$settingKey}.fall_back_path") . '/' . $imageName;
    
    $imagePath = file_exists($primaryPath) ? $primaryPath : $fallbackPath;
    
    $steps = explode("\n", $writtenGuide);

    // Structure $offCanvasData to match the expected nested keys
    $offCanvasData = [
        'channel' => $channel,
        'title' => $title,
        'settingKey' => $settingKey,
        'steps' => $steps,
        'written_guide' => [
            'message' => $writtenGuide,
        ],
        'external_guide' => [
            'text' => $externalText,
            'link' => $externalLink,
        ],
        'image' => [
            'path' => $imagePath,
        ],
    ];
@endphp

@include('components.offcanvas-qrcode', ['data' => $offCanvasData])

@endsection


@push('script-push')
<script>
	(function($){
		"use strict";

        flatpickr("#datePicker", {
            dateFormat: "Y-m-d",
            mode: "range",
        });

        // =====================================================
        // API KEY GENERATION
        // =====================================================
        $(document).on('click', '#generateApiKeyBtn', function(e) {
            e.preventDefault();

            $.ajax({
                headers: {'X-CSRF-TOKEN': "{{csrf_token()}}"},
                url: "{{route('admin.gateway.whatsapp.device.server.generate.api.key')}}",
                method: 'post',
                beforeSend: function() {
                    $('#generateApiKeyBtn').prop('disabled', true)
                        .html('<i class="ri-loader-2-line"></i> {{ translate("Generating...") }}');
                },
                success: function(res) {
                    if (res.success) {
                        $('#wp_api_key').val(res.api_key);
                        notify('success', res.message || '{{ translate("API key generated successfully") }}');
                    } else {
                        notify('error', res.message || '{{ translate("Failed to generate API key") }}');
                    }
                },
                error: function(xhr, status, error) {
                    notify('error', '{{ translate("Something went wrong") }}');
                    console.error('API Key Generation Error:', error);
                },
                complete: function() {
                    $('#generateApiKeyBtn').prop('disabled', false)
                        .html('<i class="ri-refresh-line"></i> {{ translate("Generate") }}');
                }
            });
        });

        // =====================================================
        // HEALTH CHECK
        // =====================================================
        function checkNodeHealth() {
            $.ajax({
                headers: {'X-CSRF-TOKEN': "{{csrf_token()}}"},
                url: "{{route('admin.gateway.whatsapp.device.server.health')}}",
                method: 'get',
                beforeSend: function() {
                    $('#healthStatus').html('<span class="spinner-border spinner-border-sm"></span> {{ translate("Checking...") }}');
                    $('#healthDetails').hide();
                    $('#syncStatus').hide();
                },
                success: function(res) {
                    if (res.success && res.health.healthy) {
                        $('#healthStatus').html('<span class="badge bg-success"><i class="ri-checkbox-circle-line"></i> {{ translate("Online") }}</span>');

                        // Show uptime if available
                        if (res.health.data && res.health.data.uptime) {
                            var uptime = parseFloat(res.health.data.uptime);
                            var uptimeText = '';

                            if (uptime < 60) {
                                uptimeText = Math.round(uptime) + ' {{ translate("seconds") }}';
                            } else if (uptime < 3600) {
                                uptimeText = Math.round(uptime / 60) + ' {{ translate("minutes") }}';
                            } else if (uptime < 86400) {
                                uptimeText = Math.round(uptime / 3600) + ' {{ translate("hours") }}';
                            } else {
                                uptimeText = Math.round(uptime / 86400) + ' {{ translate("days") }}';
                            }

                            $('#healthUptime').text('{{ translate("Uptime:") }} ' + uptimeText);
                            $('#healthDetails').show();
                        }

                        // Show sync status
                        if (res.health.configSynced !== undefined) {
                            if (res.health.configSynced) {
                                $('#syncStatus').html('<span class="badge bg-success"><i class="ri-checkbox-circle-line"></i> {{ translate("Config Synced") }}</span>').show();
                            } else {
                                $('#syncStatus').html('<span class="badge bg-warning text-dark"><i class="ri-alert-line"></i> ' + (res.health.syncMessage || '{{ translate("Not Synced") }}') + '</span>').show();
                            }
                        }
                    } else {
                        $('#healthStatus').html('<span class="badge bg-danger"><i class="ri-close-circle-line"></i> {{ translate("Offline") }}</span>');
                        if (res.health && res.health.error) {
                            $('#healthUptime').text('{{ translate("Error:") }} ' + res.health.error);
                            $('#healthDetails').show();
                        }
                    }
                },
                error: function(xhr, status, error) {
                    $('#healthStatus').html('<span class="badge bg-danger"><i class="ri-close-circle-line"></i> {{ translate("Offline") }}</span>');
                    $('#healthUptime').text('{{ translate("Cannot connect to Node service") }}');
                    $('#healthDetails').show();
                }
            });
        }

        // Check health when modal opens
        $('.whatsapp-server-settings').on('click', function() {
            setTimeout(checkNodeHealth, 300);
        });

        // Manual health check button
        $(document).on('click', '#checkHealthBtn', function(e) {
            e.preventDefault();
            checkNodeHealth();
        });

        // Reinitialize Node service button
        $(document).on('click', '#reinitializeBtn', function(e) {
            e.preventDefault();
            var $btn = $(this);
            var originalHtml = $btn.html();

            $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');

            $.ajax({
                url: "{{ route('admin.gateway.whatsapp.device.server.reinitialize') }}",
                method: 'POST',
                headers: {'X-CSRF-TOKEN': "{{ csrf_token() }}"},
                success: function(response) {
                    if (response.success) {
                        notify('success', response.message);
                        // Refresh health status after reinitialize
                        setTimeout(checkNodeHealth, 1000);
                    } else {
                        notify('error', response.message || '{{ translate("Failed to reinitialize") }}');
                    }
                },
                error: function(xhr) {
                    var msg = xhr.responseJSON?.message || '{{ translate("Failed to reinitialize Node service") }}';
                    notify('error', msg);
                },
                complete: function() {
                    $btn.prop('disabled', false).html(originalHtml);
                }
            });
        });

        // Update server URL when host/port changes
        $('#server_host, #server_port').on('input', function() {
            var host = $('#server_host').val() || '127.0.0.1';
            var port = $('#server_port').val() || '3001';
            $('#server_url').val('http://' + host + ':' + port);
        });

        // =====================================================
        // COPY TO CLIPBOARD
        // =====================================================
        $(document).on('click', '.copy-cmd-btn', function(e) {
            e.preventDefault();
            var cmd = $(this).data('cmd');
            var $btn = $(this);
            var originalHtml = $btn.html();

            navigator.clipboard.writeText(cmd).then(function() {
                $btn.html('<i class="ri-check-line"></i>');
                setTimeout(function() {
                    $btn.html(originalHtml);
                }, 1500);
                notify('success', '{{ translate("Command copied to clipboard") }}');
            }).catch(function(err) {
                // Fallback for older browsers
                var textarea = document.createElement('textarea');
                textarea.value = cmd;
                document.body.appendChild(textarea);
                textarea.select();
                document.execCommand('copy');
                document.body.removeChild(textarea);

                $btn.html('<i class="ri-check-line"></i>');
                setTimeout(function() {
                    $btn.html(originalHtml);
                }, 1500);
                notify('success', '{{ translate("Command copied to clipboard") }}');
            });
        });

        // =====================================================
        // COLLAPSIBLE INSTRUCTIONS TOGGLE ICON
        // =====================================================
        $('#postSaveInstructions').on('show.bs.collapse', function() {
            $('#instructionsToggleIcon').removeClass('ri-arrow-down-s-line').addClass('ri-arrow-up-s-line');
        }).on('hide.bs.collapse', function() {
            $('#instructionsToggleIcon').removeClass('ri-arrow-up-s-line').addClass('ri-arrow-down-s-line');
        });

        // =====================================================
        // SERVER SETTINGS FORM SUBMISSION (AJAX)
        // =====================================================
        $('#serverSettingsForm').on('submit', function(e) {
            e.preventDefault();
            var $form = $(this);
            var $submitBtn = $form.find('button[type="submit"]');
            var originalBtnHtml = $submitBtn.html();

            $.ajax({
                url: $form.attr('action'),
                method: 'POST',
                data: $form.serialize(),
                dataType: 'json',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                },
                beforeSend: function() {
                    $submitBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> {{ translate("Saving...") }}');
                },
                success: function(response) {
                    // Close the settings modal
                    $('#whatsappServerSetting').modal('hide');

                    // Show post-save modal based on sync result
                    setTimeout(function() {
                        if (response.success && response.synced && !response.restartRequired) {
                            // Fully successful - saved and synced, no restart needed
                            $('#postSaveSuccess').show();
                            $('#postSaveWarning').hide();
                            $('#postSaveModalLabel').html('<i class="ri-checkbox-circle-line text-success"></i> {{ translate("Configuration Saved") }}');
                            notify('success', response.message || '{{ translate("Configuration saved and synced successfully") }}');
                        } else if (response.success && response.synced && response.restartRequired) {
                            // Synced but HOST/PORT changed - restart required
                            $('#postSaveSuccess').hide();
                            $('#postSaveWarning').show();
                            $('#postSaveModalLabel').html('<i class="ri-restart-line text-info"></i> {{ translate("Restart Required") }}');
                            // Update warning message for restart scenario
                            $('#postSaveWarning .alert-warning').html(
                                '<i class="ri-information-fill"></i> ' +
                                '<strong>{{ translate("Configuration Synced") }}</strong> ' +
                                '{{ translate("Server HOST/PORT changed. Node service restart required for these changes to take effect.") }}'
                            );
                            notify('info', response.message || '{{ translate("Restart required for HOST/PORT changes") }}');
                        } else if (response.success && !response.synced) {
                            // Saved but sync failed - show instructions
                            $('#postSaveSuccess').hide();
                            $('#postSaveWarning').show();
                            $('#postSaveModalLabel').html('<i class="ri-alert-line text-warning"></i> {{ translate("Action Required") }}');
                            // Reset warning message
                            $('#postSaveWarning .alert-warning').html(
                                '<i class="ri-alert-fill"></i> ' +
                                '<strong>{{ translate("Saved with Warning") }}</strong> ' +
                                '{{ translate("Configuration saved but auto-sync failed. Manual action required.") }}'
                            );
                            notify('warning', response.message || '{{ translate("Configuration saved but sync failed") }}');
                        } else {
                            // Error
                            notify('error', response.message || '{{ translate("Failed to save configuration") }}');
                            return;
                        }
                        $('#postSaveModal').modal('show');
                    }, 300);
                },
                error: function(xhr) {
                    var errorMsg = xhr.responseJSON?.message || '{{ translate("Failed to save configuration") }}';
                    notify('error', errorMsg);
                },
                complete: function() {
                    $submitBtn.prop('disabled', false).html(originalBtnHtml);
                }
            });
        });

        $(document).on('click', '.qrQuote', function(e) {

            e.preventDefault()
            var id = $(this).attr('value')
            var url = "{{route('admin.gateway.whatsapp.device.server.qrcode')}}"
            $.ajax({
                headers: {'X-CSRF-TOKEN': "{{csrf_token()}}"},
                url:url,
                data: {id:id},
                dataType: 'json',
                method: 'post',
                beforeSend: function() {

                    $('.textChange'+id).html(`<i class="ri-loader-2-line"></i>
                                                    <span class="tooltiptext"> {{ translate("Loading") }} </span>`);
                },
                success: function(res) {

                    if (res.response && res.response.id) {
                        $("#scan_id").val(res.response.id);
                    }

                    if (res.data.message && res.data.qr && res.data.status===200) {

                        $('#qrcode').attr('src', res.data.qr);
                        notify('success', res.data.message);

                        if (res.response && res.response.id) {
                            sleep(10000).then(() => {

                                wapSession(res.response.id);
                            });
                        }
                    } else if (res.data.message) {

                        notify('error', res.data.message);
                    }
                },
                complete: function(){
                    $('.textChange'+id).html(`<i class="ri-qr-code-fill"></i>
                                                    <span class="tooltiptext"> {{ translate("Scan") }} </span>`);
                },
                error: function(e) {
                    notify('error','Something went wrong')
                }
            });
        });

        function wapSession(id) {

            $.ajax({

                headers: {'X-CSRF-TOKEN': "{{csrf_token()}}"},
                url:"{{route('admin.gateway.whatsapp.device.server.status')}}",
                data: {id:id},
                dataType: 'json',
                method: 'post',
                success: function(res) {

                    if (res.response && res.response.id) {
                        $("#scan_id").val(res.response.id);
                    }

                    // Show message if available
                    if (res.data.message) {
                        console.log(res.data.message);
                    }

                    // Update QR code if provided
                    if (res.data.qr && res.data.qr !== '') {
                        $('#qrcode').attr('src', res.data.qr);
                    }

                    if (res.data.status === 301) {
                        // Successfully connected
                        notify('success', res.data.message || '{{ translate("Successfully connected WhatsApp device") }}');

                        sleep(2500).then(() => {
                            $('.qrQuote').offcanvas('hide');
                            location.reload();
                        });
                    } else if (res.data.status === 200) {
                        // Still connecting - show message and continue polling
                        if (res.data.message) {
                            console.log('Checking status...', res.data.message);
                        }

                        if (res.response && res.response.id) {
                            sleep(10000).then(() => {
                                wapSession(res.response.id);
                            });
                        }
                    } else {
                        // Unknown status - continue polling
                        if (res.response && res.response.id) {
                            sleep(10000).then(() => {
                                wapSession(res.response.id);
                            });
                        }
                    }
                },
                error: function(e) {
                    console.error('Error checking session status:', e);
                    // Retry after delay
                    sleep(10000).then(() => {
                        wapSession(id);
                    });
                }
            })
        }



        // Track disconnected devices
        var disconnectedDevices = [];

        // Auto-check all device sessions on page load
        function checkAllDeviceSessions() {
            disconnectedDevices = [];
            @foreach ($gateways as $device)
                @if($device->status == \App\Enums\Common\Status::ACTIVE)
                    checkDeviceSession({{ $device->id }}, '{{ $device->name }}');
                @endif
            @endforeach

            // Show summary notification after checking all devices
            setTimeout(function() {
                if (disconnectedDevices.length > 0) {
                    var message = '{{ translate("Session disconnected for:") }} ' + disconnectedDevices.join(', ');
                    message += '. {{ translate("Please scan QR code to reconnect.") }}';
                    notify('warning', message);

                    // Show persistent notification banner
                    showDisconnectedBanner(disconnectedDevices);
                }
            }, 3000);
        }

        // Show disconnected devices banner
        function showDisconnectedBanner(devices) {
            var existingBanner = $('#disconnected-devices-banner');
            if (existingBanner.length) {
                existingBanner.remove();
            }

            var banner = $(`
                <div id="disconnected-devices-banner" class="alert alert-warning alert-dismissible fade show mb-3" role="alert">
                    <div class="d-flex align-items-center">
                        <i class="ri-wifi-off-line fs-4 me-2"></i>
                        <div>
                            <strong>{{ translate("Session Disconnected") }}</strong>
                            <p class="mb-0 small">{{ translate("The following devices have disconnected sessions:") }} <strong>${devices.join(', ')}</strong></p>
                            <p class="mb-0 small text-muted">{{ translate("Click the QR icon to scan and reconnect.") }}</p>
                        </div>
                    </div>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            `);

            // Insert banner after table filter
            $('.table-filter').after(banner);
        }

        // Check individual device session status
        function checkDeviceSession(deviceId, sessionName) {
            $.ajax({
                headers: {'X-CSRF-TOKEN': "{{csrf_token()}}"},
                url: "{{route('admin.gateway.whatsapp.device.server.status')}}",
                data: { id: deviceId },
                dataType: 'json',
                method: 'post',
                success: function(res) {
                    // If device is marked active in DB but session is not connected
                    if (res.data.status !== 301) {
                        console.log('Device "' + sessionName + '" is marked active but session is not connected');
                        disconnectedDevices.push(sessionName);

                        // Update the status badge in the table to show warning
                        updateDeviceStatusBadge(deviceId, 'disconnected');
                    }
                },
                error: function(e) {
                    console.log('Failed to check session status for device: ' + sessionName);
                    disconnectedDevices.push(sessionName);
                    updateDeviceStatusBadge(deviceId, 'error');
                }
            });
        }

        // Update device status badge in the table
        function updateDeviceStatusBadge(deviceId, status) {
            // Find the row with this device
            var $row = $('button.qrQuote[value="' + deviceId + '"], button.deviceDisconnection' + deviceId).closest('tr');

            if ($row.length) {
                var $statusCell = $row.find('td[data-label="{{ translate("Status") }}"]');
                if ($statusCell.length) {
                    var badge = '';
                    if (status === 'disconnected') {
                        badge = '<span class="badge bg-warning text-dark"><i class="ri-wifi-off-line"></i> {{ translate("Session Lost") }}</span>';
                    } else if (status === 'error') {
                        badge = '<span class="badge bg-danger"><i class="ri-error-warning-line"></i> {{ translate("Error") }}</span>';
                    }
                    $statusCell.html(badge);

                    // Change disconnect button to QR scan button
                    var $actionCell = $row.find('td[data-label="{{ translate("Option") }}"]');
                    if ($actionCell.length) {
                        var $disconnectBtn = $actionCell.find('.deviceDisconnection' + deviceId);
                        if ($disconnectBtn.length) {
                            $disconnectBtn.removeClass('danger-soft deviceDisconnection' + deviceId)
                                          .addClass('success-soft qrQuote textChange' + deviceId)
                                          .attr('onclick', '')
                                          .attr('data-bs-toggle', 'offcanvas')
                                          .attr('data-bs-target', '#offcanvasQrCode')
                                          .attr('aria-controls', 'offcanvasQrCode')
                                          .html('<i class="ri-qr-code-fill"></i><span class="tooltiptext">{{ translate("Scan") }}</span>');
                        }
                    }
                }
            }
        }

        $(document).ready(function() {

            // Check all device sessions on page load
            checkAllDeviceSessions();

            $('.whatsapp-server-settings').on('click', function() {

                const modal = $('#whatsappServerSetting');
                modal.modal('show');
            });
            $('.add-whatsapp-device').on('click', function() {

                const modal = $('#addWhatsappDevice');
                modal.modal('show');
            });

            $('.update-whatsapp-device').on('click', function() {

                const modal = $('#updateWhatsappDevice');
                modal.find('form[id=updateWhatsappGatewayForm]').attr('action', $(this).data('url'));
                modal.find('input[name=per_message_min_delay]').val($(this).data('per_message_min_delay'));
                modal.find('input[name=per_message_max_delay]').val($(this).data('per_message_max_delay'));
                modal.find('input[name=delay_after_count]').val($(this).data('delay_after_count'));
                modal.find('input[name=delay_after_duration]').val($(this).data('delay_after_duration'));
                modal.find('input[name=reset_after_count]').val($(this).data('reset_after_count'));
                modal.modal('show');
            });

            $('.delete-whatsapp-device').on('click', function() {

                var modal = $('#deleteWhatsappDevice');
                modal.find('form[id=deleteWhatsappGateway]').attr('action', $(this).data('url'));
                modal.modal('show');
            });

            $('.quick-view').on('click', function() {
                const modal = $('#quick_view');
                const modalBodyInformation = modal.find('.modal-body .information-list');
                modalBodyInformation.empty();

                var uid = $(this).data('uid');
                if(uid) {
                    var title = 'gateway_identifier';
                    const listItem = $('<li>');
                    const paramKeySpan = $('<span>').text(textFormat(['_'], title, ' '));
                    const arrowIcon = $('<i>').addClass('bi bi-arrow-right');
                    const paramValueSpan = $(`<span title='${title}'>`).addClass('text-break text-muted').text(uid);

                    listItem.append(paramKeySpan).append(arrowIcon).append(paramValueSpan);
                    modalBodyInformation.append(listItem);
                }
                modal.modal('show');
            });
        });

	})(jQuery);
</script>
@endpush
