@extends('layout.app')
@section('content')
    @php
        $storedVoices = $storedVoices ?? collect();
        $usableVoices = $usableVoices ?? $storedVoices;
        $hasUsableVoices = $usableVoices->isNotEmpty();
        $storedVoiceOptions = $usableVoices->map(function ($voice) {
            return [
                'id' => $voice->id,
                'label' => $voice->title ?? $voice->original_name,
            ];
        })->values();
        $storedVoiceTableData = $storedVoices->map(function ($voice) {
            return [
                'id' => $voice->id,
                'title' => $voice->title,
                'original_name' => $voice->original_name,
                'file_size' => $voice->file_size,
                'created_at' => optional($voice->created_at)->toIso8601String(),
                'status' => $voice->status,
            ];
        })->values();
    @endphp
    @if(!$gateway)
        <div class="alert alert-warning alert-dismissible fade show" role="alert">
            <strong>Warning!</strong> No active voice gateway is configured. Please <a href="{{ route('voice-gateway.create') }}">add and enable a voice gateway</a> first.
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif

    <form action="" method="POST" id="voiceForm" enctype="multipart/form-data">

        @csrf

        <div class="card">
            <div class="card-body">
                @if($gateway)
                    <div class="alert alert-info mb-2 d-flex justify-content-between align-items-center flex-wrap">
                        <div>
                            <i class="fas fa-info-circle"></i> Using Gateway: <strong>{{ $gateway->name }}</strong>
                        </div>
                        <div class="text-right mt-2 mt-sm-0">
                            Convert to <strong>gsm | wav</strong> format →
                            <a href="https://g711.org" target="_blank" rel="noopener">https://g711.org</a>
                        </div>
                    </div>
                    <div class="alert alert-warning mb-3">
                        <i class="far fa-clock"></i>
                        অনুগ্রহ করে <strong>রাত ৮:০০ টার পরে</strong> কোন ভয়েস মেসেজ ক্যাম্পেইন চালাবেন না।
                    </div>
                @endif

                <div class="card card-secondary card-tabs">
                    <div class="card-header p-0 pt-1">
                        <ul class="nav nav-tabs" id="custom-tabs-one-tab" role="tablist">
                            <li class="nav-item">
                                <a class="nav-link @if ($single == false) active @endif"
                                    id="custom-tabs-one-auto-voice-tab" data-toggle="pill"
                                    href="#custom-tabs-one-auto-voice" role="tab">
                                    <i class="fas fa-users mr-1"></i> Batch Voice Send
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link @if ($single == true) active @endif"
                                    id="custom-tabs-one-single-voice-tab" data-toggle="pill"
                                    href="#custom-tabs-one-single-voice" role="tab">
                                    <i class="fas fa-user mr-1"></i> Single Voice Send
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" id="custom-tabs-user-send-voice-tab" data-toggle="pill"
                                    href="#custom-tabs-user-send-voice" role="tab">
                                    <i class="fas fa-user-tie mr-1"></i> User Voice Send
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" id="custom-tabs-reminder-voice-tab" data-toggle="pill"
                                    href="#custom-tabs-reminder-voice" role="tab">
                                    <i class="fas fa-bell mr-1"></i> Due Reminder Voice
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" id="voice-library-tab" data-toggle="pill"
                                    href="#voice-library" role="tab">
                                    <i class="fas fa-folder-open mr-1"></i> Voice Library
                                </a>
                            </li>
                        </ul>
                    </div>
                    <div class="card-body">
                        <div class="tab-content" id="custom-tabs-one-tabContent">
                            <div class="tab-pane fade @if ($single == false) show active @endif"
                                id="custom-tabs-one-auto-voice" role="tabpanel"
                                aria-labelledby="custom-tabs-one-auto-voice-tab">
                                <div class="container col-md-12">
                                    <div class="row mb-3">
                                        <div class="col-md-4">
                                            <label for="voice_source_batch" class="block text-sm font-medium text-gray-700">
                                                <i class="fas fa-random mr-1"></i> Voice Source <span class="text-danger">*</span>
                                            </label>
                                            <select class="form-control voice-source" id="voice_source_batch" @if(!$gateway) disabled @endif>
                                                <option value="upload" selected>Upload new voice</option>
                                                <option value="library" @if(!$hasUsableVoices) disabled @endif>Use saved voice</option>
                                            </select>
                                            <small class="form-text text-muted"><i class="fas fa-info-circle"></i>
                                                Switch between uploading a new audio file or selecting from the voice library.</small>
                                        </div>
                                        <div class="col-md-8" id="voice_upload_group_batch">
                                            <label for="voice" class="block text-sm font-medium text-gray-700">
                                                <i class="fas fa-file-audio mr-1"></i> Voice File <span class="text-danger">*</span>
                                            </label>
                                            <input type="file" name="voice" id="voice" class="form-control" accept="audio/*" required @if(!$gateway) disabled @endif>
                                            <small class="form-text text-muted"><i class="fas fa-info-circle"></i> Accepted formats: gsm | wav</small>
                                            <audio id="voicePreview" controls class="mt-2" style="display:none;"></audio>
                                            <div class="mt-2" id="save_voice_wrapper_batch">
                                                <div class="form-check">
                                                    <input type="checkbox" class="form-check-input save-to-library" id="save_voice_batch" @if(!$gateway) disabled @endif>
                                                    <label class="form-check-label" for="save_voice_batch">
                                                        Save this voice to the library for re-use
                                                    </label>
                                                </div>
                                                <input type="text" class="form-control mt-2 voice-title-input" id="voice_title_batch" placeholder="Library title (optional)" style="display:none;">
                                            </div>
                                        </div>
                                        <div class="col-md-8" id="voice_library_group_batch" style="display:none;">
                                            <label for="saved_voice_batch" class="block text-sm font-medium text-gray-700">
                                                <i class="fas fa-folder-open mr-1"></i> Saved Voice <span class="text-danger">*</span>
                                            </label>
                                            <select class="select2 form-control saved-voice-select" id="saved_voice_batch" @if(!$gateway) disabled @endif>
                                                <option value="">Select saved voice</option>
                                                @foreach ($usableVoices as $voice)
                                                    <option value="{{ $voice->id }}">{{ $voice->title ?? $voice->original_name }}</option>
                                                @endforeach
                                            </select>
                                            <small class="form-text text-muted"><i class="fas fa-info-circle"></i> Pick one of your stored voices.</small>
                                        </div>
                                    </div>

                                    <hr>

                                    <div class="row">
                                        <div class="form-group col-md-3">
                                            <label for="reseller_id" class="block text-sm font-medium text-gray-700">
                                                <i class="fas fa-building mr-1"></i> Reseller <span class="text-danger">*</span>
                                            </label>
                                            <select class="select2 form-control" name="reseller_id" id="reseller">
                                                <option value="">Select Reseller</option>
                                                @foreach ($reseller as $item)
                                                    <option value="{{ $item->id }}">{{ $item->name }}</option>
                                                @endforeach
                                            </select>
                                        </div>

                                        <div class="form-group col-md-3">
                                            <label for="pop_id"><i class="fas fa-network-wired mr-1"></i> POP</label>
                                            <select name="pop_id" id="pop" class="select2 form-control">
                                                <option value="all">All POP</option>
                                            </select>
                                        </div>
                                        <div class="form-group col-md-2">
                                            <label for="billing_cycle"><i class="fas fa-calendar-alt mr-1"></i> Billing Cycle</label>
                                            <select name="billing_cycle" id="billing_cycle" class="select2 form-control">
                                                <option value="all">All Billing Cycle</option>
                                                @foreach (explode(',', $confday) as $conf)
                                                    <option value="{{ $conf }}">{{ $conf }}</option>
                                                @endforeach
                                            </select>
                                        </div>

                                        <div class="form-group col-md-2">
                                            <label for="status"><i class="fas fa-toggle-on mr-1"></i> Status</label>
                                            <select name="status" id="status" class="select2 form-control" multiple>
                                                <option value="active">Active</option>
                                                <option value="deactive">Deactive</option>
                                                <option value="expired">Expired</option>
                                                <option value="disable">Disable</option>
                                            </select>
                                        </div>
                                        <div class="form-group col-md-2">
                                            <label for="due_filter"><i class="fas fa-money-bill-wave mr-1"></i> Due Filter</label>
                                            <select name="due_filter" id="due_filter" class="form-control">
                                                <option value="all" selected>All Customers</option>
                                                <option value="due">Due Customers Only</option>
                                                <option value="without_due">Without Due</option>
                                            </select>
                                            <small class="form-text text-muted"><i class="fas fa-info-circle"></i> Filter by customer due status</small>
                                        </div>
                                        <div class="form-group col-md-2">
                                            <label for="area"><i class="fas fa-map-marker-alt mr-1"></i> Area</label>
                                            <select name="area" id="area" class="select2 form-control" multiple>
                                                <option value="all" selected>All Area</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <button type="button" id="submit" class="btn btn-primary btn-lg float-right" @if(!$gateway) disabled @endif>
                                            <i class="fas fa-paper-plane mr-2"></i> Send Voice Broadcast
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="tab-pane fade @if ($single == true) show active @endif"
                                id="custom-tabs-one-single-voice" role="tabpanel"
                                aria-labelledby="custom-tabs-one-single-voice-tab">

                                <div class="container col-md-12">
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label for="voice_source_single" class="block text-sm font-medium text-gray-700">
                                                <i class="fas fa-random mr-1"></i> Voice Source <span class="text-danger">*</span>
                                            </label>
                                            <select class="form-control voice-source" id="voice_source_single" @if(!$gateway) disabled @endif>
                                                <option value="upload" selected>Upload new voice</option>
                                                <option value="library" @if(!$hasUsableVoices) disabled @endif>Use saved voice</option>
                                            </select>
                                            <small class="form-text text-muted"><i class="fas fa-info-circle"></i> Choose to upload a fresh file or reuse a saved one.</small>

                                            <div class="mt-2" id="voice_upload_group_single">
                                                <label for="voice_single" class="block text-sm font-medium text-gray-700">
                                                    <i class="fas fa-file-audio mr-1"></i> Voice File <span class="text-danger">*</span>
                                                </label>
                                                <input type="file" name="voice_single" id="voice_single" class="form-control" accept="audio/*" required @if(!$gateway) disabled @endif>
                                                <small class="form-text text-muted"><i class="fas fa-info-circle"></i> Accepted formats: gsm | wav.</small>
                                                <audio id="voice_singlePreview" controls class="mt-2" style="display:none;"></audio>
                                                <div class="mt-2" id="save_voice_wrapper_single">
                                                    <div class="form-check">
                                                        <input type="checkbox" class="form-check-input save-to-library" id="save_voice_single" @if(!$gateway) disabled @endif>
                                                        <label class="form-check-label" for="save_voice_single">
                                                            Save this voice to the library
                                                        </label>
                                                    </div>
                                                    <input type="text" class="form-control mt-2 voice-title-input" id="voice_title_single" placeholder="Library title (optional)" style="display:none;">
                                                </div>
                                            </div>
                                            <div class="mt-2" id="voice_library_group_single" style="display:none;">
                                                <label for="saved_voice_single" class="block text-sm font-medium text-gray-700">
                                                    <i class="fas fa-folder-open mr-1"></i> Saved Voice <span class="text-danger">*</span>
                                                </label>
                                                <select class="select2 form-control saved-voice-select" id="saved_voice_single" @if(!$gateway) disabled @endif>
                                                    <option value="">Select saved voice</option>
                                                    @foreach ($usableVoices as $voice)
                                                        <option value="{{ $voice->id }}">{{ $voice->title ?? $voice->original_name }}</option>
                                                    @endforeach
                                                </select>
                                                <small class="form-text text-muted"><i class="fas fa-info-circle"></i> Pick one of the stored voices.</small>
                                            </div>
                                        </div>

                                        <div class="col-md-6">
                                            <label for="number_single" class="block text-sm font-medium text-gray-700">
                                                <i class="fas fa-mobile-alt mr-1"></i> Phone Number <span class="text-danger">*</span>
                                            </label>
                                            <input type="text" class="form-control" id="number_single" minlength="11"
                                                placeholder="88017xxxxxxxx"
                                                value="@if ($client) {{ $client->clientsinfo->contact_no }} @endif"
                                                name="number_single" required>
                                            <small class="form-text text-muted">Enter 11 digit mobile number</small>
                                        </div>
                                    </div>

                                    <hr>

                                    <div class="form-group">
                                        <button type="button" id="submit_single" class="btn btn-primary btn-lg float-right" @if(!$gateway) disabled @endif>
                                            <i class="fas fa-paper-plane mr-2"></i> Send Voice
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <div class="tab-pane fade" id="custom-tabs-user-send-voice" role="tabpanel"
                                aria-labelledby="custom-tabs-user-send-voice-tab">

                                <div class="container col-md-12">
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label for="voice_source_user" class="block text-sm font-medium text-gray-700">
                                                <i class="fas fa-random mr-1"></i> Voice Source <span class="text-danger">*</span>
                                            </label>
                                            <select class="form-control voice-source" id="voice_source_user" @if(!$gateway) disabled @endif>
                                                <option value="upload" selected>Upload new voice</option>
                                                <option value="library" @if(!$hasUsableVoices) disabled @endif>Use saved voice</option>
                                            </select>
                                            <small class="form-text text-muted"><i class="fas fa-info-circle"></i> Upload a new file or select one from the library.</small>

                                            <div class="mt-2" id="voice_upload_group_user">
                                                <label for="voice_user" class="block text-sm font-medium text-gray-700">
                                                    <i class="fas fa-file-audio mr-1"></i> Voice File <span class="text-danger">*</span>
                                                </label>
                                                <input type="file" name="voice_user" id="voice_user" class="form-control" accept="audio/*" required @if(!$gateway) disabled @endif>
                                                <small class="form-text text-muted"><i class="fas fa-info-circle"></i> Accepted formats: gsm | wav.</small>
                                                <audio id="voice_userPreview" controls class="mt-2" style="display:none;"></audio>
                                                <div class="mt-2" id="save_voice_wrapper_user">
                                                    <div class="form-check">
                                                        <input type="checkbox" class="form-check-input save-to-library" id="save_voice_user" @if(!$gateway) disabled @endif>
                                                        <label class="form-check-label" for="save_voice_user">
                                                            Save this voice to the library
                                                        </label>
                                                    </div>
                                                    <input type="text" class="form-control mt-2 voice-title-input" id="voice_title_user" placeholder="Library title (optional)" style="display:none;">
                                                </div>
                                            </div>

                                            <div class="mt-2" id="voice_library_group_user" style="display:none;">
                                                <label for="saved_voice_user" class="block text-sm font-medium text-gray-700">
                                                    <i class="fas fa-folder-open mr-1"></i> Saved Voice <span class="text-danger">*</span>
                                                </label>
                                                <select class="select2 form-control saved-voice-select" id="saved_voice_user" @if(!$gateway) disabled @endif>
                                                    <option value="">Select saved voice</option>
                                                @foreach ($usableVoices as $voice)
                                                        <option value="{{ $voice->id }}">{{ $voice->title ?? $voice->original_name }}</option>
                                                    @endforeach
                                                </select>
                                                <small class="form-text text-muted"><i class="fas fa-info-circle"></i> Select any stored voice.</small>
                                            </div>
                                        </div>

                                        <div class="col-md-6">
                                            <label for="users" class="block text-sm font-medium text-gray-700">
                                                <i class="fas fa-users mr-1"></i> Select Users <span class="text-danger">*</span>
                                            </label>
                                            <select name="users" id="users" class="select2 form-control" required multiple @if(!$gateway) disabled @endif>
                                                <option value="all_user">All Users</option>
                                                <option value="all_manager">All Managers</option>
                                                @foreach ($users as $user)
                                                    <option value="{{ $user->id }}">{{ $user->name }}</option>
                                                @endforeach
                                            </select>
                                            <small class="form-text text-muted">Select specific users or choose all</small>
                                        </div>
                                    </div>

                                    <hr>

                                    <div class="form-group">
                                        <button type="button" id="send_user_voice" class="btn btn-primary btn-lg float-right" @if(!$gateway) disabled @endif>
                                            <i class="fas fa-paper-plane mr-2"></i> Send Voice to Users
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <div class="tab-pane fade" id="custom-tabs-reminder-voice" role="tabpanel"
                                aria-labelledby="custom-tabs-reminder-voice-tab">
                                <div class="container col-md-8">
                                    <div class="row mb-3">
                                        <div class="col-md-7">
                                            <label for="voice_source_reminder" class="block text-sm font-medium text-gray-700">
                                                <i class="fas fa-random mr-1"></i> Voice Source <span class="text-danger">*</span>
                                            </label>
                                            <select class="form-control voice-source" id="voice_source_reminder" @if(!$gateway) disabled @endif>
                                                <option value="upload" selected>Upload new voice</option>
                                                <option value="library" @if(!$hasUsableVoices) disabled @endif>Use saved voice</option>
                                            </select>
                                            <small class="form-text text-muted"><i class="fas fa-info-circle"></i> Send reminders using a fresh upload or a stored audio.</small>
                                            <div class="mt-2" id="voice_upload_group_reminder">
                                                <label for="voice_reminder" class="block text-sm font-medium text-gray-700">
                                                    <i class="fas fa-file-audio mr-1"></i> Reminder Voice File <span class="text-danger">*</span>
                                                </label>
                                                <input type="file" name="voice_reminder" id="voice_reminder"
                                                    class="form-control" accept="audio/*" required @if(!$gateway) disabled @endif>
                                                <small class="form-text text-muted"><i class="fas fa-info-circle"></i> Accepted formats: gsm | wav.</small>
                                                <audio id="voice_reminderPreview" controls class="mt-2" style="display:none;"></audio>
                                                <div class="mt-2" id="save_voice_wrapper_reminder">
                                                    <div class="form-check">
                                                        <input type="checkbox" class="form-check-input save-to-library" id="save_voice_reminder" @if(!$gateway) disabled @endif>
                                                        <label class="form-check-label" for="save_voice_reminder">
                                                            Save this voice to the library
                                                        </label>
                                                    </div>
                                                    <input type="text" class="form-control mt-2 voice-title-input" id="voice_title_reminder" placeholder="Library title (optional)" style="display:none;">
                                                </div>
                                            </div>
                                            <div class="mt-2" id="voice_library_group_reminder" style="display:none;">
                                                <label for="saved_voice_reminder" class="block text-sm font-medium text-gray-700">
                                                    <i class="fas fa-folder-open mr-1"></i> Saved Voice <span class="text-danger">*</span>
                                                </label>
                                                <select class="select2 form-control saved-voice-select" id="saved_voice_reminder" @if(!$gateway) disabled @endif>
                                                    <option value="">Select saved voice</option>
                                                    @foreach ($usableVoices as $voice)
                                                        <option value="{{ $voice->id }}">{{ $voice->title ?? $voice->original_name }}</option>
                                                    @endforeach
                                                </select>
                                                <small class="form-text text-muted"><i class="fas fa-info-circle"></i> Pick from stored reminder voices.</small>
                                            </div>
                                        </div>
                                        <div class="col-md-5">
                                            <label for="days_before" class="block text-sm font-medium text-gray-700">
                                                <i class="fas fa-calendar-minus mr-1"></i> Days Before Expire <span class="text-danger">*</span>
                                            </label>
                                            <input type="number" class="form-control" id="days_before" name="days_before"
                                                placeholder="e.g. 3" min="1" max="60" value="3" required @if(!$gateway) disabled @endif>
                                            <small class="form-text text-muted">Send reminders to customers expiring within these many days.</small>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <button type="button" id="send_reminder_voice"
                                            class="btn btn-primary btn-lg float-right" @if(!$gateway) disabled @endif>
                                            <i class="fas fa-bell mr-2"></i> Send Due Reminder Voice
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <div class="tab-pane fade" id="voice-library" role="tabpanel" aria-labelledby="voice-library-tab">
                                <div class="container col-md-12">
                                    <div class="row">
                                        <div class="col-md-5">
                                            <h5 class="mb-3"><i class="fas fa-upload mr-1"></i> Store New Voice</h5>
                                            <div class="form-group">
                                                <label for="library_voice_title" class="block text-sm font-medium text-gray-700">
                                                    <i class="fas fa-heading mr-1"></i> Title (optional)
                                                </label>
                                                <input type="text" id="library_voice_title" class="form-control" placeholder="e.g. Renewal Reminder">
                                            </div>
                                            <div class="form-group">
                                                <label for="library_voice_file" class="block text-sm font-medium text-gray-700">
                                                    <i class="fas fa-file-audio mr-1"></i> Voice File <span class="text-danger">*</span>
                                                </label>
                                                <input type="file" id="library_voice_file" class="form-control" accept="audio/*">
                                                <small class="form-text text-muted"><i class="fas fa-info-circle"></i> Upload gsm | wav</small>
                                                <audio id="library_voice_preview" controls class="mt-2" style="display:none;"></audio>
                                            </div>
                                            <button type="button" id="store_voice_library" class="btn btn-success" @if(!$gateway) disabled @endif>
                                                <i class="fas fa-save mr-2"></i> Save to Voice Library
                                            </button>
                                        </div>
                                        <div class="col-md-7">
                                            <h5 class="mb-3"><i class="fas fa-list mr-1"></i> Saved Voices</h5>
                                            <div class="table-responsive">
                                                <table class="table table-bordered table-hover" id="voice_library_table">
                                                    <thead class="thead-light">
                                                        <tr>
                                                            <th>ID</th>
                                                            <th>Name</th>
                                                            <th>Size</th>
                                                            <th>Added</th>
                                                            <th>Status</th>
                                                            <th class="text-center">Actions</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        @forelse ($storedVoices as $voice)
                                                            <tr data-id="{{ $voice->id }}" data-status="{{ $voice->status }}">
                                                                <td class="text-monospace">#{{ $voice->id }}</td>
                                                                <td>
                                                                    <strong>{{ $voice->title ?? $voice->original_name }}</strong>
                                                                    <div class="small text-muted">{{ $voice->original_name }}</div>
                                                                </td>
                                                                <td>
                                                                    @if ($voice->file_size)
                                                                        {{ number_format($voice->file_size / 1024, 1) }} KB
                                                                    @else
                                                                        N/A
                                                                    @endif
                                                                </td>
                                                                <td>{{ optional($voice->created_at)->format('d M Y, h:i A') }}</td>
                                                                <td>
                                                                    @if ($voice->status === \App\Models\VoiceBroadcast::STATUS_ENABLED)
                                                                        <span class="badge badge-success">Enabled</span>
                                                                    @else
                                                                        <span class="badge badge-secondary">Disabled</span>
                                                                    @endif
                                                                </td>
                                                                <td class="text-center">
                                                                    <button type="button" class="btn btn-primary btn-sm use-saved-voice" data-id="{{ $voice->id }}" @if ($voice->status !== \App\Models\VoiceBroadcast::STATUS_ENABLED) disabled @endif>
                                                                        <i class="fas fa-check mr-1"></i> Use
                                                                    </button>
                                                                    <button type="button" class="btn btn-warning btn-sm toggle-voice-status" data-id="{{ $voice->id }}" data-next-status="{{ $voice->status === \App\Models\VoiceBroadcast::STATUS_ENABLED ? \App\Models\VoiceBroadcast::STATUS_DISABLED : \App\Models\VoiceBroadcast::STATUS_ENABLED }}">
                                                                        <i class="fas fa-exchange-alt mr-1"></i> {{ $voice->status === \App\Models\VoiceBroadcast::STATUS_ENABLED ? 'Disable' : 'Enable' }}
                                                                    </button>
                                                                    <button type="button" class="btn btn-danger btn-sm delete-voice-btn" data-id="{{ $voice->id }}">
                                                                        <i class="fas fa-trash mr-1"></i> Delete
                                                                    </button>
                                                                </td>
                                                            </tr>
                                                        @empty
                                                            <tr class="empty-row">
                                                                <td colspan="6" class="text-center text-muted">
                                                                    No voice saved yet. Upload one using the form on the left.
                                                                </td>
                                                            </tr>
                                                        @endforelse
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                        </div>
                    </div>

                </div>

            </div>

        </div>

    </form>
    <style>
        #processing {
            background: rgba(0, 0, 0, .5);
            height: 100vh;
            width: 100%;
            text-align: center;
            color: #fff;
            top: 0;
            padding-top: 50vh%;
            position: fixed;
            z-index: 999;
        }
    </style>
@endsection

@section('ajax')
    <script type="text/javascript">
        $(function() {
            const voiceScopeConfig = {
                batch: { fileInput: '#voice' },
                single: { fileInput: '#voice_single' },
                user: { fileInput: '#voice_user' },
                reminder: { fileInput: '#voice_reminder' }
            };

            const csrfToken = '{{ csrf_token() }}';

            let availableVoices = @json($storedVoiceOptions);
            let allVoices = @json($storedVoiceTableData);
            const libraryStoreUrl = '{{ route('voice-library.store') }}';
            const libraryDeleteRouteTemplate = '{{ route('voice-library.destroy', ['voiceBroadcast' => '__VOICE_ID__']) }}';
            const voiceStatusRouteTemplate = '{{ route('voice-library.toggle-status', ['voiceBroadcast' => '__VOICE_ID__']) }}';
            const emptyTableMarkup = '<tr class="empty-row"><td colspan="6" class="text-center text-muted">No voice saved yet. Upload one using the form on the left.</td></tr>';

            function toggleVoiceSource(scope) {
                const sourceSelect = $('#voice_source_' + scope);
                if (!sourceSelect.length) {
                    return;
                }
                const source = sourceSelect.val();
                const uploadGroup = $('#voice_upload_group_' + scope);
                const libraryGroup = $('#voice_library_group_' + scope);
                const saveWrapper = $('#save_voice_wrapper_' + scope);

                if (source === 'library') {
                    uploadGroup.hide();
                    libraryGroup.show();
                    saveWrapper.hide();
                } else {
                    uploadGroup.show();
                    libraryGroup.hide();
                    saveWrapper.show();
                }
            }

            function toggleVoiceTitle(scope) {
                const wrapper = $('#voice_title_' + scope);
                const checkbox = $('#save_voice_' + scope);
                if (!wrapper.length || !checkbox.length) {
                    return;
                }

                if (checkbox.is(':checked')) {
                    wrapper.show();
                } else {
                    wrapper.hide().val('');
                }
            }

            function syncLibraryAvailability() {
                const hasVoices = availableVoices.length > 0;
                $('.voice-source option[value="library"]').prop('disabled', !hasVoices);
                if (!hasVoices) {
                    $.each(voiceScopeConfig, function(scope) {
                        const select = $('#voice_source_' + scope);
                        if (select.length && select.val() === 'library') {
                            select.val('upload');
                            toggleVoiceSource(scope);
                        }
                    });
                }
            }

            function appendVoicePayload(formData, scope) {
                const config = voiceScopeConfig[scope];
                const sourceSelect = $('#voice_source_' + scope);
                if (!config || !sourceSelect.length) {
                    toastr.error('Voice configuration missing. Please refresh the page.', 'Error');
                    return false;
                }

                const source = sourceSelect.val();
                formData.append('voice_source', source);

                if (source === 'library') {
                    const selected = $('#saved_voice_' + scope).val();
                    if (!selected) {
                        toastr.error('Please select a saved voice from the library.', 'Missing Voice');
                        return false;
                    }
                    formData.append('voice_asset_id', selected);
                    formData.append('save_to_library', 0);
                    return true;
                }

                const fileInput = $(config.fileInput)[0];
                if (!fileInput || !fileInput.files || !fileInput.files[0]) {
                    toastr.error('Please upload a voice file first.', 'Missing Voice');
                    return false;
                }
                formData.append('voice', fileInput.files[0]);

                const saveCheckbox = $('#save_voice_' + scope);
                if (saveCheckbox.length && saveCheckbox.is(':checked')) {
                    formData.append('save_to_library', 1);
                    formData.append('voice_title', $('#voice_title_' + scope).val());
                } else {
                    formData.append('save_to_library', 0);
                }

                return true;
            }

            function resetVoiceInputs(scope) {
                const config = voiceScopeConfig[scope];
                if (!config) {
                    return;
                }
                const fileInput = $(config.fileInput);
                if (fileInput.length) {
                    fileInput.val('').trigger('change');
                }

                $('#saved_voice_' + scope).val('').trigger('change');
                $('#save_voice_' + scope).prop('checked', false);
                $('#voice_title_' + scope).val('').hide();
                const sourceSelect = $('#voice_source_' + scope);
                if (sourceSelect.length) {
                    sourceSelect.val('upload');
                    toggleVoiceSource(scope);
                }
            }

            function formatFileSize(bytes) {
                if (!bytes) {
                    return 'N/A';
                }
                if (bytes >= 1024 * 1024) {
                    return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
                }
                return (bytes / 1024).toFixed(1) + ' KB';
            }

            function formatDateTime(dateString) {
                if (!dateString) {
                    return '';
                }
                const parsed = new Date(dateString);
                if (isNaN(parsed.getTime())) {
                    return dateString;
                }
                return parsed.toLocaleString();
            }

            function renderVoiceRow(voice) {
                const label = voice.title || voice.label || voice.original_name || '';
                const original = voice.original_name || '';
                const size = formatFileSize(voice.file_size);
                const createdAt = formatDateTime(voice.created_at);
                const isEnabled = voice.status === 'enabled';
                const badgeClass = isEnabled ? 'badge-success' : 'badge-secondary';
                const badgeText = isEnabled ? 'Enabled' : 'Disabled';
                const toggleText = isEnabled ? 'Disable' : 'Enable';
                const nextStatus = isEnabled ? 'disabled' : 'enabled';
                const disabledAttr = isEnabled ? '' : 'disabled';

                return `
                    <tr data-id="${voice.id}" data-status="${voice.status}">
                        <td class="text-monospace">#${voice.id}</td>
                        <td>
                            <strong>${label}</strong>
                            <div class="small text-muted">${original}</div>
                        </td>
                        <td>${size}</td>
                        <td>${createdAt}</td>
                        <td><span class="badge ${badgeClass}">${badgeText}</span></td>
                        <td class="text-center">
                            <button type="button" class="btn btn-primary btn-sm use-saved-voice" data-id="${voice.id}" ${disabledAttr}>
                                <i class="fas fa-check mr-1"></i> Use
                            </button>
                            <button type="button" class="btn btn-warning btn-sm toggle-voice-status" data-id="${voice.id}" data-next-status="${nextStatus}">
                                <i class="fas fa-exchange-alt mr-1"></i> ${toggleText}
                            </button>
                            <button type="button" class="btn btn-danger btn-sm delete-voice-btn" data-id="${voice.id}">
                                <i class="fas fa-trash mr-1"></i> Delete
                            </button>
                        </td>
                    </tr>
                `;
            }

            function upsertVoiceRecord(voice) {
                const index = allVoices.findIndex(function(item) {
                    return item.id === voice.id;
                });
                if (index > -1) {
                    allVoices[index] = voice;
                } else {
                    allVoices.push(voice);
                }
            }

            function removeVoiceRecord(id) {
                allVoices = allVoices.filter(function(item) {
                    return item.id !== id;
                });
            }

            function refreshVoiceRow(voice) {
                const tbody = $('#voice_library_table tbody');
                const row = tbody.find('tr[data-id="' + voice.id + '"]');
                const markup = renderVoiceRow(voice);
                if (row.length) {
                    row.replaceWith(markup);
                } else {
                    addVoiceToTable(voice);
                }
            }

            function addVoiceToTable(voice) {
                const tbody = $('#voice_library_table tbody');
                tbody.find('.empty-row').remove();
                upsertVoiceRecord(voice);
                tbody.prepend(renderVoiceRow(voice));
            }

            function removeVoiceFromTable(id) {
                const tbody = $('#voice_library_table tbody');
                tbody.find('tr[data-id="' + id + '"]').remove();
                removeVoiceRecord(id);
                if (tbody.children().length === 0) {
                    tbody.append(emptyTableMarkup);
                }
            }

            function addVoiceOption(voice) {
                const label = voice.title || voice.label || voice.original_name;
                $('.saved-voice-select').each(function() {
                    const select = $(this);
                    if (select.find('option[value="' + voice.id + '"]').length === 0) {
                        select.append('<option value="' + voice.id + '">' + label + '</option>');
                    }
                });
                availableVoices.push({ id: voice.id, label: label });
                syncLibraryAvailability();
            }

            function removeVoiceOption(id) {
                $('.saved-voice-select option[value="' + id + '"]').remove();
                availableVoices = availableVoices.filter(function(item) {
                    return item.id !== id;
                });
                syncLibraryAvailability();
            }

            function selectVoiceInForms(id) {
                if (!id) {
                    return;
                }
                $('.voice-source').each(function() {
                    $(this).val('library').trigger('change');
                });
                $('.saved-voice-select').val(id).trigger('change');
                toastr.success('Saved voice selected. Switch to the desired tab and send.', 'Voice Ready');
            }

            function showProcessing() {
                hideProcessing();
                $('body').prepend('<div id="processing">processing.....</div>');
            }

            function hideProcessing() {
                $('#processing').remove();
            }

            function getErrorMessage(xhr) {
                if (xhr.responseJSON) {
                    if (xhr.responseJSON.message) {
                        return xhr.responseJSON.message;
                    }
                    if (xhr.responseJSON.error) {
                        return xhr.responseJSON.error;
                    }
                }
                return 'Something went wrong. Please try again.';
            }

            $.each(voiceScopeConfig, function(scope) {
                toggleVoiceSource(scope);
                $('#voice_source_' + scope).on('change', function() {
                    toggleVoiceSource(scope);
                });
                $('#save_voice_' + scope).on('change', function() {
                    toggleVoiceTitle(scope);
                });
            });

            syncLibraryAvailability();

            $('#reseller').on('change', function(e) {
                e.preventDefault();
                showProcessing();
                $.ajax({
                    type: 'get',
                    url: '{{ route('getResellerAreaPop') }}',
                    data: {
                        id: $(this).val()
                    },
                    success: function(result) {
                        $('#pop').empty();
                        $('#pop').append('<option value="all"> All Pop </option>');
                        result.pops.forEach(element => {
                            $('#pop').append('<option value="' + element.id + '">' + element.popname + '</option>');
                        });

                        $('#area').empty();
                        $('#area').append('<option value="all" selected> All Area </option>');
                        result.areas.forEach(element => {
                            if (element !== "") {
                                $('#area').append('<option value="' + element + '">' + element + '</option>');
                            }
                        });
                    },
                    complete: function() {
                        hideProcessing();
                    }
                });
            });

            $('#submit').on('click', function(e) {
                e.preventDefault();

                let formData = new FormData();
                if (!appendVoicePayload(formData, 'batch')) {
                    return;
                }

                formData.append('reseller_id', $('#reseller').val());
                formData.append('pop_id', $('#pop').val());

                let selectedStatuses = $('#status').val() || [];
                selectedStatuses.forEach(function(value) {
                    formData.append('status[]', value);
                });

                let selectedAreas = $('#area').val() || [];
                selectedAreas.forEach(function(value) {
                    formData.append('areas[]', value);
                });

                formData.append('billing_cycle', $('#billing_cycle').val());
                formData.append('due_filter', $('#due_filter').val());
                formData.append('singel_number', null);

                if (!confirm('Are you sure you want to send this voice broadcast?')) {
                    return;
                }

                showProcessing();

                $.ajax({
                    type: 'post',
                    url: '{{ route('sendVoiceToSelected') }}',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(result) {
                        if (result.error) {
                            toastr.error(result.error, 'Error');
                        }
                        if (result.success) {
                            toastr.success(result.success, 'Success');
                            $('.select2').each(function() {
                                $(this).val("").trigger("change");
                            });
                            resetVoiceInputs('batch');
                        }
                    },
                    error: function(xhr) {
                        toastr.error(getErrorMessage(xhr), 'Error');
                    },
                    complete: function() {
                        hideProcessing();
                    }
                });
            });

            $('#submit_single').on('click', function(e) {
                e.preventDefault();

                let formData = new FormData();
                if (!appendVoicePayload(formData, 'single')) {
                    return;
                }
                formData.append('singel_number', $('#number_single').val());

                if (!confirm('Are you sure you want to send this voice?')) {
                    return;
                }

                showProcessing();

                $.ajax({
                    type: 'post',
                    url: '{{ route('sendVoiceToSelected') }}',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(result) {
                        if (result.error) {
                            toastr.error(result.error, 'Error');
                        }
                        if (result.success) {
                            toastr.success(result.success, 'Success');
                            $('#number_single').val('');
                            resetVoiceInputs('single');
                        }
                    },
                    error: function(xhr) {
                        toastr.error(getErrorMessage(xhr), 'Error');
                    },
                    complete: function() {
                        hideProcessing();
                    }
                });
            });

            $('#send_user_voice').on('click', function() {
                let formData = new FormData();
                if (!appendVoicePayload(formData, 'user')) {
                    return;
                }

                const selectedUsers = $('#users').val() || [];
                selectedUsers.forEach(function(userId) {
                    formData.append('users[]', userId);
                });

                if (!confirm('Are you sure you want to send voice to the selected users?')) {
                    return;
                }

                showProcessing();

                $.ajax({
                    type: 'post',
                    url: '{{ route('sendVoiceToSelectedUser') }}',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(result) {
                        if (result.error) {
                            toastr.error(result.error, 'Error');
                        }
                        if (result.success) {
                            toastr.success(result.success, 'Success');
                            $("#users").val("").trigger("change");
                            resetVoiceInputs('user');
                        }
                    },
                    error: function(xhr) {
                        toastr.error(getErrorMessage(xhr), 'Error');
                    },
                    complete: function() {
                        hideProcessing();
                    }
                });
            });

            $('#send_reminder_voice').on('click', function(e) {
                e.preventDefault();

                let formData = new FormData();
                if (!appendVoicePayload(formData, 'reminder')) {
                    return;
                }
                formData.append('days_before', $('#days_before').val());

                if (!confirm('Send reminder voice to due customers?')) {
                    return;
                }

                showProcessing();

                $.ajax({
                    type: 'post',
                    url: '{{ route('sendVoiceReminder') }}',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(result) {
                        if (result.error) {
                            toastr.error(result.error, 'Error');
                        }
                        if (result.success) {
                            toastr.success(result.success, 'Success');
                            resetVoiceInputs('reminder');
                        }
                    },
                    error: function(xhr) {
                        toastr.error(getErrorMessage(xhr), 'Error');
                    },
                    complete: function() {
                        hideProcessing();
                    }
                });
            });

            $('#store_voice_library').on('click', function() {
                const fileInput = $('#library_voice_file')[0];
                if (!fileInput || !fileInput.files[0]) {
                    toastr.error('Please choose an audio file to store.', 'Missing File');
                    return;
                }

                let formData = new FormData();
                formData.append('_token', csrfToken);
                formData.append('voice', fileInput.files[0]);
                formData.append('title', $('#library_voice_title').val());

                showProcessing();

                $.ajax({
                    type: 'post',
                    url: libraryStoreUrl,
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(result) {
                        if (result.error) {
                            toastr.error(result.error, 'Error');
                        }
                        if (result.success) {
                            toastr.success(result.success, 'Saved');
                            addVoiceToTable(result.voice);
                            addVoiceOption(result.voice);
                            $('#library_voice_file').val('').trigger('change');
                            $('#library_voice_title').val('');
                            $('#library_voice_preview').hide().attr('src', '');
                        }
                    },
                    error: function(xhr) {
                        toastr.error(getErrorMessage(xhr), 'Error');
                    },
                    complete: function() {
                        hideProcessing();
                    }
                });
            });

            function buildLibraryDeleteUrl(id) {
                return libraryDeleteRouteTemplate.replace('__VOICE_ID__', id);
            }

            function buildVoiceStatusUrl(id) {
                return voiceStatusRouteTemplate.replace('__VOICE_ID__', id);
            }

            $(document).on('click', '.delete-voice-btn', function() {
                const id = $(this).data('id');
                if (!id) {
                    return;
                }
                if (!confirm('Remove this voice from the library?')) {
                    return;
                }

                showProcessing();

                $.ajax({
                    type: 'post',
                    url: buildLibraryDeleteUrl(id),
                    data: {
                        _method: 'DELETE',
                        _token: csrfToken
                    },
                    success: function(result) {
                        if (result.error) {
                            toastr.error(result.error, 'Error');
                        } else {
                            toastr.success(result.success || 'Voice removed.', 'Removed');
                            removeVoiceFromTable(id);
                            removeVoiceOption(id);
                        }
                    },
                    error: function(xhr) {
                        toastr.error(getErrorMessage(xhr), 'Error');
                    },
                    complete: function() {
                        hideProcessing();
                    }
                });
            });

            $(document).on('click', '.toggle-voice-status', function() {
                const id = $(this).data('id');
                const nextStatus = $(this).data('next-status');
                if (!id || !nextStatus) {
                    return;
                }

                showProcessing();

                $.ajax({
                    type: 'post',
                    url: buildVoiceStatusUrl(id),
                    data: {
                        _method: 'PATCH',
                        _token: csrfToken,
                        status: nextStatus
                    },
                    success: function(result) {
                        if (result.error) {
                            toastr.error(result.error, 'Error');
                            return;
                        }
                        if (result.voice) {
                            const voice = result.voice;
                            refreshVoiceRow(voice);
                            if (voice.status === 'enabled') {
                                addVoiceOption(voice);
                            } else {
                                removeVoiceOption(voice.id);
                            }
                        }
                        if (result.success) {
                            toastr.success(result.success, 'Status Updated');
                        }
                    },
                    error: function(xhr) {
                        toastr.error(getErrorMessage(xhr), 'Error');
                    },
                    complete: function() {
                        hideProcessing();
                    }
                });
            });

            $(document).on('click', '.use-saved-voice', function() {
                const id = $(this).data('id');
                selectVoiceInForms(id);
                $('#custom-tabs-one-auto-voice-tab').tab('show');
            });
        });
    </script>

    <script>
        // Audio preview for all voice file inputs
        $('input[type="file"][accept="audio/*"]').on('change', function() {
            const file = this.files[0];
            const previewId = $(this).attr('id') + 'Preview';
            let preview = $('#' + previewId);

            if (preview.length === 0) {
                preview = $('<audio id="' + previewId + '" controls class="mt-2" style="display:none;">Your browser does not support the audio element.</audio>');
                $(this).after(preview);
            }

            if (file && file.type.startsWith('audio/')) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.attr('src', e.target.result);
                    preview.show();
                };
                reader.readAsDataURL(file);
            } else {
                preview.hide();
            }
        });
    </script>
@endsection

