@extends('dashboard.includes.master')
@section('title', 'Create New Message')
@section('css')
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<!-- Select2 CSS -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.snow.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
<style>
    :root {
        /* 🎨 New Premium Color Palette */
        --primary: #4F46E5;
        /* Indigo */
        --primary-light: #818CF8;
        /* Light Indigo */
        --primary-dark: #3730A3;
        /* Dark Indigo */
        --secondary: #7C3AED;
        /* Purple */
        --accent: #06B6D4;
        /* Cyan */
        --success: #10B981;
        --danger: #EF4444;
        --warning: #F59E0B;
        --light: #F9FAFB;
        --dark: #111827;
        --gray-50: #F9FAFB;
        --gray-100: #F3F4F6;
        --gray-200: #E5E7EB;
        --gray-300: #D1D5DB;
        --gray-700: #374151;
        --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
        --shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.05);
        --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.05);
        --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        --border-radius: 16px;
    }

    body {
        font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        background-color: #F9FAFB;
        color: var(--dark);
    }

    .container-fluid {
        max-width: 1400px;
        margin: 0 auto;
    }

    .custom-card {
        border: none;
        border-radius: var(--border-radius);
        box-shadow: var(--shadow-lg);
        background: white;
        transition: var(--transition);
        margin-bottom: 2rem;
    }

    .custom-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.05);
    }

    .card-header {
        background: linear-gradient(135deg, var(--primary), var(--secondary));
        color: white;
        border-radius: var(--border-radius) var(--border-radius) 0 0 !important;
        padding: 1.5rem 2rem;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .card-header h5 {
        font-weight: 600;
        font-size: 1.25rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    h6 {
        color: var(--primary-dark);
        font-weight: 600;
        letter-spacing: 0.25px;
        font-size: 1.1rem;
        margin-bottom: 1rem;
    }

    .form-label {
        font-weight: 500;
        color: var(--gray-700);
        margin-bottom: 0.5rem;
        font-size: 0.95rem;
        display: flex;
        align-items: center;
        gap: 0.3rem;
    }

    .form-label i {
        color: var(--primary);
        font-size: 1rem;
    }

    .form-label-subject {
        color: var(--primary);
        font-weight: 600;
        font-size: 0.95rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        background: rgba(79, 70, 229, 0.05);
        padding: 0.5rem 1rem;
        border-radius: 12px;
        border-left: 4px solid var(--primary);
    }

    .form-control,
    .form-select {
        border: 2px solid var(--gray-200);
        border-radius: 12px;
        padding: 0.75rem 1rem;
        transition: var(--transition);
        font-size: 0.95rem;
        background: white;
    }

    .form-control:focus,
    .form-select:focus {
        border-color: var(--primary);
        box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        background: white;
    }



    .form-check-input:checked+label {
        background-color: #c1bfe1;
        border-color: var(--primary);
        border-radius: 11px;
        padding: 0 6px;
    }

    .btn {
        border-radius: 12px;
        padding: 0.6rem 1.2rem;
        font-weight: 500;
        transition: var(--transition);
        border: none;
    }

    .btn-outline-primary {
        border: 2px solid var(--primary);
        color: var(--primary);
        background: transparent;
    }

    .btn-outline-primary:hover {
        background: var(--primary);
        color: white;
        transform: translateY(-1px);
        box-shadow: var(--shadow);
    }

    .btn-info {
        background: linear-gradient(135deg, var(--primary), var(--secondary));
        color: white;
        border: none;
    }

    .btn-info:hover {
        background: linear-gradient(135deg, var(--primary-dark), #5B21B6);
        transform: translateY(-1px);
        box-shadow: var(--shadow);
    }

    .btn-light {
        background: var(--gray-50);
        border: 1px solid var(--gray-200);
        color: var(--gray-700);
    }

    .btn-light:hover {
        background: var(--gray-100);
        transform: translateY(-1px);
    }

    /* Send Button */
    .send-button {
        background: linear-gradient(135deg, #EF4444, #DC2626);
        color: white;
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 1.5rem;
        box-shadow: var(--shadow);
        transition: var(--transition);
        border: none;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .send-button:hover {
        transform: scale(1.1) rotate(3deg);
        box-shadow: 0 10px 25px rgba(239, 68, 68, 0.4);
    }

    .send-button:active {
        transform: scale(0.95);
    }

    /* Editor Section */
    .editor-section {
        background: white;
        border-radius: var(--border-radius);
        border: 1px solid var(--gray-200);
        box-shadow: var(--shadow-sm);
        padding: 1.5rem;
        margin: 2rem 0;
    }

    /* Toolbar */
    #toolbar-container {
        background: var(--gray-50);
        padding: 12px;
        border-radius: 12px 12px 0 0;
        border: 1px solid var(--gray-200);
        border-bottom: none;
        margin-bottom: 0;
        display: flex;
        flex-wrap: wrap;
        gap: 4px;
    }

    .ql-toolbar button,
    .ql-toolbar select {
        border-radius: 8px !important;
        margin: 2px !important;
        border: 1px solid var(--gray-300) !important;
        background: white !important;
        color: var(--gray-700) !important;
        transition: var(--transition) !important;
    }

    .ql-toolbar button:hover,
    .ql-toolbar select:hover {
        background: var(--primary) !important;
        color: white !important;
        border-color: var(--primary) !important;
        transform: translateY(-1px);
    }

    .ql-toolbar button.ql-active,
    .ql-toolbar select.ql-active {
        background: var(--primary) !important;
        color: white !important;
    }

    /* Editor */
    #editor {
        border: 1px solid var(--gray-200);
        border-top: none;
        border-radius: 0 0 12px 12px;
        min-height: 300px;
        height: auto;
        max-height: 60vh;
        overflow-y: auto;
        transition: var(--transition);
        padding: 1.5rem;
        background: white;
        font-family: 'Inter', sans-serif;
        line-height: 1.6;
    }

    #editor:focus-within {
        border-color: var(--primary);
        box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
    }

    /* Preview Container */
    #preview-container {
        border: 1px solid var(--gray-200);
        padding: 20px;
        min-height: 200px;
        background: white;
        border-radius: 12px;
        margin-top: 1rem;
        box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.03);
        display: none;
    }

    /* Attachments Section */
    .attachments-section {
        background: linear-gradient(135deg, rgba(79, 70, 229, 0.03), rgba(124, 58, 237, 0.03));
        border: 1px solid var(--gray-200);
        border-radius: var(--border-radius);
        padding: 1.5rem;
        margin-top: 2rem;
        position: relative;
    }

    .section-title {
        background: linear-gradient(135deg, rgba(79, 70, 229, 0.05), rgba(124, 58, 237, 0.05));
        padding: 1rem 1.5rem;
        border-radius: var(--border-radius);
        margin: 2rem 0 1.5rem;
        font-weight: 600;
        color: var(--primary-dark);
        display: flex;
        align-items: center;
        gap: 0.75rem;
        border-left: 4px solid var(--primary);
    }

    .section-title i {
        background: var(--primary);
        color: white;
        width: 36px;
        height: 36px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1rem;
    }

    .select2-container .select2-selection--multiple {
        border: 2px solid var(--gray-200) !important;
        border-radius: 12px !important;
        padding: 0.5rem 0.75rem !important;
        background: white !important;
        max-height: 100px !important;
        overflow-y: auto !important;
    }

    .select2-container--default .select2-selection--multiple:focus {
        border-color: var(--primary) !important;
        box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1) !important;
    }

    .select2-container--default .select2-selection--multiple .select2-selection__choice {
        background-color: var(--primary) !important;
        /* Indigo */
        color: white !important;
        border: none !important;
        border-radius: 8px !important;
        padding: 0.3rem 0.7rem !important;
        font-size: 0.85rem !important;
        margin: 0.25rem 0.25rem 0.25rem 0 !important;
        display: inline-block;
        line-height: 1.2;
    }

    .select2-container--default .select2-selection--multiple .select2-selection__choice__remove {
        color: rgba(255, 255, 255, 0.8) !important;
        margin-left: 0.5rem !important;
        font-size: 0.8rem !important;
        cursor: pointer;
    }

    .select2-container--default .select2-selection--multiple .select2-selection__choice__remove:hover {
        color: white !important;
    }

    /* Alerts */
    .alert {
        border-radius: 12px;
        border: none;
        padding: 1rem 1.5rem;
        font-weight: 500;
        margin: 1rem 0;
        border-left: 4px solid;
    }

    .alert-success {
        background: rgba(16, 185, 129, 0.1);
        border-left-color: #10B981;
        color: #065F46;
    }

    .alert-danger {
        background: rgba(239, 68, 68, 0.1);
        border-left-color: #EF4444;
        color: #991B1B;
    }

    /* Small Action Buttons */
    .small-action {
        margin-top: 12px;
        display: flex;
        gap: 0.5rem;
        align-items: center;
    }

    .select-all-indicator {
        font-size: 0.85rem;
        color: var(--primary);
        font-weight: 500;
        background: rgba(79, 70, 229, 0.1);
        padding: 0.25rem 0.75rem;
        border-radius: 20px;
        border: 1px solid rgba(79, 70, 229, 0.2);
    }

    .load-more-btn {
        background: var(--gray-50);
        border: 1px dashed var(--gray-300);
        color: var(--gray-700);
        font-size: 0.9rem;
        border-radius: 8px;
    }

    .load-more-btn:hover {
        background: var(--primary);
        color: white;
        border-style: solid;
        transform: translateY(-1px);
    }

    /* Responsive */
    @media (max-width: 768px) {
        .card-header {
            flex-direction: column;
            gap: 1rem;
            text-align: center;
        }

        .send-button {
            width: 50px;
            height: 50px;
            font-size: 1.25rem;
            margin: 1rem auto 0;
        }

        .section-title {
            font-size: 1rem;
        }

        .form-label {
            font-size: 0.9rem;
        }
    }

    /* Loader */
    .loader {
        display: none;
        text-align: center;
        padding: 2rem;
    }

    .loader div {
        width: 20px;
        height: 20px;
        background: var(--primary);
        border-radius: 50%;
        display: inline-block;
        margin: 0 5px;
        animation: bounce 1.4s infinite ease-in-out both;
    }

    .loader div:nth-child(1) {
        animation-delay: -0.32s;
    }

    .loader div:nth-child(2) {
        animation-delay: -0.16s;
    }

    @keyframes bounce {

        0%,
        80%,
        100% {
            transform: scale(0);
        }

        40% {
            transform: scale(1);
        }
    }

    /* Micro-interactions */
    .form-control,
    .form-select,
    .btn {
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }

    .form-control:hover,
    .form-select:hover {
        border-color: var(--primary-light);
    }

    /* Card Body Padding */
    .card-body {
        padding: 2rem !important;
    }

    /* Form Spacing */
    .row>[class*="col"] {
        padding: 0.5rem;
    }

    /* Preview Button */
    #preview-btn {
        background: var(--gray-100);
        border: 1px solid var(--gray-300);
        color: var(--gray-700);
        border-radius: 8px;
        padding: 0.5rem 1rem;
        font-weight: 500;
        transition: var(--transition);
    }

    #preview-btn:hover {
        background: var(--primary);
        color: white;
        border-color: var(--primary);
        transform: translateY(-1px);
    }

    iframe {
        width: 100%;
    }

    /* تحسينات لدعم RTL */
    .ql-editor {
        direction: ltr;
        /* افتراضي */
        text-align: left;
        /* افتراضي */
    }

    /* عندما يتم تفعيل RTL */
    .ql-editor[style*="direction: rtl"] {
        direction: rtl;
        text-align: right;
    }

    /* تحسينات لشريط الأدوات في وضع RTL */
    .ql-toolbar {
        direction: ltr;
    }

    .ql-toolbar .ql-formats {
        direction: ltr;
    }

    /* لجعل قائمة الاختيار (Select) تعمل بشكل صحيح في RTL */
    .ql-picker {
        direction: ltr;
    }

    .ql-picker-label {
        direction: ltr;
    }

    .ql-picker-options {
        direction: ltr;
    }
</style>
@endsection
@section('content')
<div class="container-fluid py-4">
    <div class="row justify-content-center">
        <div class="col-xl-12">
            <div class="card custom-card">
                <div class="card-header">
                    <h5><i class="fas fa-envelope"></i> Create New Message</h5>
                    <button type="button" class="btn btn-sm btn-outline-light" onclick="toggleScheduleFields()">
                        <i class="fas fa-sync me-1"></i> Toggle Mode
                    </button>
                </div>
                @if(session('success'))
                <div class="alert alert-success alert-dismissible fade show mx-4 my-3" role="alert">
                    <i class="fas fa-check-circle me-2"></i> {{ session('success') }}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                @endif
                @if(session('error'))
                <div class="alert alert-danger alert-dismissible fade show mx-4 my-3" role="alert">
                    <i class="fas fa-exclamation-triangle me-2"></i> {{ session('error') }}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                @endif
                <div class="card-body">
                    <form action="{{ route('messages.resetStatus') }}" method="POST" onsubmit="return confirm('هل أنت متأكد من تحويل كل sent إلى pending؟');">
                        @if (session('success'))
                        <div class="alert alert-success mt-2">
                            {{ session('success') }}
                        </div>
                        @endif
                        @csrf
                        <button type="submit" class="btn btn-warning">
                            🔄 Reset status to **Pending**
                        </button>
                    </form>
                    <form action="{{ route('messages.resetFailedToPending') }}" method="POST" onsubmit="return confirm('هل أنت متأكد من تحويل كل failed إلى pending؟');">
                        @if (session('success'))
                        <div class="alert alert-success mt-2">
                            {{ session('success') }}
                        </div>
                        @endif
                        @csrf
                        <button type="submit" class="btn btn-warning">
                            🔄 Reset status failed to **Pending**
                        </button>
                    </form>
                    <!-- <a href="{{ route('check.statues') }}" class="btn btn-primary">change statues ahmed in db sent-> pending</a> -->
                    <a href="{{ route('check.mx') }}" class="btn btn-primary">🔍 check MX to all emails</a>


                    <form action="{{ route('message.store') }}" method="POST" enctype="multipart/form-data" id="mainForm">
                        @csrf
                        <!-- Send Mode -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <div class="bg-gradient-to-r from-indigo-50 to-purple-50 p-4 rounded-xl border border-indigo-100">
                                    <h6 class="mb-3"><i class="fas fa-paper-plane"></i> Send Mode</h6>
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="mode" id="modeNow" value="now" checked onchange="toggleScheduleFields()">
                                        <label class="form-check-label" for="modeNow"><i class="fas fa-bolt me-1"></i> Immediate Send</label>
                                    </div>
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="mode" id="modeSchedule" value="schedule" onchange="toggleScheduleFields()">
                                        <label class="form-check-label" for="modeSchedule"><i class="fas fa-clock me-1"></i> Scheduled Send</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- Schedule Fields -->
                        <div id="scheduleFields" style="display: none;">
                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <label class="form-label"><i class="fas fa-tag"></i> Schedule Label</label>
                                    <input type="text" name="label" class="form-control" placeholder="e.g. Summer Campaign">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label"><i class="far fa-calendar-alt"></i> Start Date</label>
                                    <input type="datetime-local" name="start_at" class="form-control">
                                </div>
                                <div class="col-md-4 d-flex align-items-end">
                                    <button type="button" class="btn btn-info w-100">
                                        <i class="fas fa-calculator me-1"></i> Auto Calculate Duration
                                    </button>
                                </div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label class="form-label"><i class="fas fa-hourglass-half"></i> Duration Value</label>
                                    <input type="number" name="duration_value" class="form-control" min="1" placeholder="e.g. 24">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label"><i class="fas fa-ruler"></i> Time Unit</label>
                                    <select name="duration_unit" class="form-control">
                                        <option value="">Select Time Unit</option>
                                        <option value="hours">Hours</option>
                                        <option value="days">Days</option>
                                        <option value="weeks">Weeks</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="section-title">
                            <i class="fas fa-cogs"></i> Message Settings
                        </div>
                        <div class="row gy-4">
                            <!-- Sender Name -->
                            <div class="col-xl-4 col-lg-6 col-md-6 col-sm-12">
                                <label for="name" class="form-label"><i class="fas fa-user"></i> Sender Name</label>
                                <select id="name" multiple="multiple" class="form-control" name="sender_id[]">
                                    @foreach($senders as $sender)
                                    <option value="{{ $sender->id }}">{{ $sender->name }}</option>
                                    @endforeach
                                </select>
                                @error('sender_id') <span class="text-danger">{{ $message }}</span> @enderror
                            </div>
                            <!-- Sender Email -->
                            <div class="col-xl-4 col-lg-6 col-md-6 col-sm-12">
                                <label for="email" class="form-label"><i class="fas fa-envelope"></i> Sender Email</label>
                                <select class="form-control" name="sender_email[]" id="email" multiple disabled>
                                    <option value="">Select sender name first</option>
                                </select>
                                @error('sender_email') <span class="text-danger">{{ $message }}</span> @enderror
                            </div>
                            <!-- Category -->
                            <div class="col-xl-4 col-lg-6 col-md-6 col-sm-12">
                                <label for="category_id" class="form-label"><i class="fas fa-folder"></i> Category</label>
                                <select class="form-control" name="category_id[]" id="category_id" multiple>
                                    @foreach($categories as $category)
                                    <option value="{{ $category->id }}">{{ $category->name }}</option>
                                    @endforeach
                                </select>
                                @error('category_id') <span class="text-danger">{{ $message }}</span> @enderror
                            </div>
                            <!-- Subcategory -->
                            <div class="col-xl-4 col-lg-6 col-md-6 col-sm-12">
                                <label for="subcategory" class="form-label"><i class="fas fa-folder-open"></i> Subcategory</label>
                                <select class="form-control" name="sub_category_id[]" id="subcategory" multiple disabled>
                                    <option value="">Select category first</option>
                                </select>
                                @error('sub_category_id') <span class="text-danger">{{ $message }}</span> @enderror
                            </div>
                            <!-- Receivers -->
                            <div class="col-xl-4 col-lg-6 col-md-6 col-sm-12">
                                <label for="data_excel_id" class="form-label"><i class="fas fa-users"></i> Receivers</label>
                                <select id="data_excel_id" name="data_excel_id[]" multiple="multiple" class="form-control"></select>


                                <div class="input-group mt-2" style="max-width: 300px;">
                                    <input type="number" id="countNumber" class="form-control" placeholder="ادخل العدد" min="1">
                                    <button class="btn btn-primary" type="button" onclick="selectCustom()">اختيار</button>
                                    <button class="btn btn-danger" type="button" onclick="clearAll()">إلغاء الكل</button>
                                </div>


                                <div class="small-action">
                                    <button type="button" id="select_visible" class="btn btn-sm btn-outline-primary">
                                        <i class="fas fa-check-square me-1"></i> Select Visible
                                    </button>
                                    <span id="select_all_info" class="select-all-indicator">0 Selected</span>
                                </div>
                                <button type="button" id="load_more" class="btn btn-sm btn-light load-more-btn" style="display:none;">
                                    <i class="fas fa-spinner me-1"></i> Load More
                                </button>
                                @error('data_excel_id') <span class="text-danger">{{ $message }}</span> @enderror
                            </div>
                            <!-- Template -->
                            <div class="col-xl-4 col-lg-6 col-md-6 col-sm-12">
                                <label for="templete" class="form-label-subject">
                                    <i class="fas fa-palette"></i> Select from Templates
                                </label>
                                <select class="form-control" name="templete" id="templete">
                                    <option value="">Select a template</option>
                                    <!-- @foreach($tempeletes as $tempelete)
                                    <option value="{{ $tempelete }}">{{ $tempelete->subject }}</option>
                                    @endforeach -->
                                    @foreach($tempeletes as $tempelete)
                                    <option value="{{ json_encode(['subject' => $tempelete->subject, 'body' => $tempelete->body]) }}">
                                        {{ $tempelete->subject }}
                                    </option>
                                    @endforeach
                                </select>
                                @error('subject') <span class="text-danger">{{ $message }}</span> @enderror
                            </div>
                            <!-- Subject -->
                            <div class="col-xl-4 col-lg-6 col-md-6 col-sm-12">
                                <label for="subject" class="form-label"><i class="fas fa-heading"></i> Subject</label>
                                <input type="text" class="form-control" id="subject" name="subject" placeholder="Enter message subject">
                                @error('subject') <span class="text-danger">{{ $message }}</span> @enderror
                            </div>
                        </div>
                        <!-- Editor Section -->
                        <div class="editor-section mt-4">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h6 class="mb-0"><i class="fas fa-pencil-alt"></i> Message Content</h6>
                                <button type="button" id="preview-btn" class="btn">
                                    <i class="fas fa-eye me-1"></i> Preview
                                </button>
                                <span id="codingToggleBtn" class="btn btn-primary"> Add-Coding</span>
                                <span id="useString" class="btn btn-primary"> Add-String</span>
                            </div>
                            <textarea id="content" style="display:none;"></textarea>
                            <textarea name="content" id="contnentCode" placeholder="Enter your HTML code here..." class="form-control" style="margin-top:10px; display:none;" rows="12"></textarea>
                            <!-- Toolbar -->
                            <div id="toolbar-container"></div>
                            <div id="editor"></div>

                            <!-- with click previews -->
                            <div id="preview-container"></div>
                        </div>
                        <!-- Attachments Section -->
                        <div class="attachments-section mt-4">
                            <div class="row align-items-center justify-content-between">
                                <div class="col-md-8">
                                    <label for="file" class="form-label"><i class="fas fa-paperclip"></i> Attachments</label>
                                    <input type="file" class="form-control" id="file" name="file">
                                    @error('file') <span class="text-danger">{{ $message }}</span> @enderror
                                </div>
                                <div class="col-md-1 justify-content-end">
                                    <button type="submit" class="send-button" title="Send Message">
                                        <i class="fas fa-paper-plane"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
@section('js')
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<!-- Select2 JS -->
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/xml.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js  "></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/xml.min.js  "></script>
<script type="text/javascript">
    function selectCustom() {
        const limit = $('#countNumber').val();
        const categories = $('#category_id').val();

        if (!limit || limit < 1) {
            toastr.warning("من فضلك ادخل عدداً صحيحاً");
            return;
        }
        if (!categories || categories.length === 0) {
            toastr.error("يجب اختيار تصنيف (Category) أولاً لجلب البيانات منه");
            return;
        }

        const btn = $('button[onclick="selectCustom()"]');
        const originalText = btn.text();
        btn.prop('disabled', true).text('جاري الجلب...');

        $.ajax({
            url: '{{ route("receivers.get_top_ids") }}', // المسار الذي يعيد id و text
            method: 'GET',
            data: {
                limit: limit,
                category_ids: categories
            },
            success: function(resp) {
                const $select = $('#data_excel_id');
                if (resp.length === 0) {
                    toastr.info("لا توجد مستلمين متاحين في هذه الأقسام");
                } else {
                    resp.forEach(item => {
                        // نتحقق إذا كان الإيميل موجوداً بالفعل لتجنب التكرار
                        if ($select.find("option[value='" + item.id + "']").length === 0) {
                            // نستخدم item.text (الإيميل) لضمان عدم ظهور null
                            let newOption = new Option(item.text, item.id, true, true);
                            $select.append(newOption);
                        } else {
                            $select.find("option[value='" + item.id + "']").prop('selected', true);
                        }
                    });
                    $select.trigger('change');
                    toastr.success('تم اختيار ' + resp.length + ' مستلم بنجاح');
                }
            },
            error: function() {
                toastr.error('حدث خطأ أثناء الاتصال بالسيرفر، تأكد من وجود المسار');
            },
            complete: function() {
                btn.prop('disabled', false).text(originalText);
            }
        });
    }

    // ====== Send Mode Toggle ======
    function toggleScheduleFields() {
        const scheduleFields = document.getElementById('scheduleFields');
        const modeSchedule = document.getElementById('modeSchedule');
        if (modeSchedule && scheduleFields) {
            scheduleFields.style.display = modeSchedule.checked ? 'block' : 'none';
        }
    }
    // Auto Calculate Duration
    function calculateDuration() {
        const senders = $('#name').val()?.length || 0;
        const receivers = $('#data_excel_id').val()?.length || 0;
        if (senders === 0 || receivers === 0) {
            alert('Please select senders and receivers first');
            return;
        }
        fetch('/dashboard/message/calculate-duration', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                },
                body: JSON.stringify({
                    sender_count: senders,
                    receiver_count: receivers
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success && data.duration) {
                    document.querySelector('input[name="duration_value"]').value = data.duration.value;
                    document.querySelector('select[name="duration_unit"]').value = data.duration.unit;
                    if (data.message) alert(data.message);
                }
            })
            .catch(() => alert('Error calculating duration'));
    }
    // ====== Full Script (Select2 + Quill + Receivers Paging) ======
    document.addEventListener('DOMContentLoaded', function() {
        // -------- utilities --------
        function debounce(fn, wait) {
            let t;
            return function(...a) {
                clearTimeout(t);
                t = setTimeout(() => fn.apply(this, a), wait);
            };
        }

        function safeJSONParse(val) {
            try {
                return JSON.parse(val);
            } catch (e) {
                return null;
            }
        }

        function keyOf(arr) {
            try {
                return JSON.stringify((arr || []).slice().sort());
            } catch (e) {
                return String(arr);
            }
        }
        toastr.options = {
            closeButton: true,
            progressBar: true,
            positionClass: 'toast-top-right'
        };
        // // -------- quill with preview ----------
        // let quill = null;
        // try {
        //     hljs.configure({
        //         languages: ['html', 'xml']
        //     });
        //     quill = new Quill('#editor', {
        //         modules: {
        //             clipboard: {
        //                 matchVisual: false
        //             },
        //             toolbar: '#toolbar-container',

        //         },
        //         placeholder: 'Enter your HTML or text here...',
        //         theme: 'snow'
        //     });
        //     // console.log('Quill initialized');

        // } catch (e) {
        //     console.error('Quill init error', e);
        // }
        // -------- quill with preview ----------
        // let quill = null;
        // try {
        //     hljs.configure({
        //         languages: ['html', 'xml']
        //     });

        //     // إنشاء كائن لتحديد الاتجاه بناءً على المحتوى
        //     const DirectionModule = {
        //         name: 'direction',
        //         init: function(quill) {
        //             // دالة لتحديد ما إذا كان النص يحتوي على أحرف عربية أو فارسية
        //             function isRtlText(text) {
        //                 // نمط يتطابق مع الأحرف العربية والفارسية
        //                 return /[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/.test(text);
        //             }

        //             // مراقبة تغييرات النص
        //             quill.on('text-change', function() {
        //                 const text = quill.getText();
        //                 const hasRtl = isRtlText(text);

        //                 // الحصول على العقدة الجذرية للنص
        //                 const root = quill.root;

        //                 // ضبط اتجاه النص
        //                 if (hasRtl) {
        //                     root.style.direction = 'rtl';
        //                     root.style.textAlign = 'right'; // اختياري: محاذاة إلى اليمين
        //                 } else {
        //                     root.style.direction = 'ltr';
        //                     root.style.textAlign = 'left'; // اختياري: محاذاة إلى اليسار
        //                 }
        //             });
        //         }
        //     };

        //     quill = new Quill('#editor', {
        //         modules: {
        //             clipboard: {
        //                 matchVisual: false
        //             },
        //             toolbar: '#toolbar-container',
        //             // إضافة وحدة الاتجاه الجديدة
        //             direction: DirectionModule
        //         },
        //         placeholder: 'Enter your HTML or text here...',
        //         theme: 'snow'
        //     });
        //     console.log('Quill initialized');
        // } catch (e) {
        //     console.error('Quill init error', e);
        // }
        // -------- quill with preview ----------
        let quill = null;
        try {
            // ✅ تعريف أدوات Quill الكاملة
            const toolbarOptions = [
                [{
                    'font': []
                }],
                [{
                    'size': ['small', false, 'large', 'huge']
                }],
                ['bold', 'italic', 'underline', 'strike'],
                [{
                    'color': []
                }, {
                    'background': []
                }],
                [{
                    'script': 'sub'
                }, {
                    'script': 'super'
                }],
                [{
                    'header': [1, 2, 3, 4, 5, 6, false]
                }],
                [{
                    'align': []
                }, {
                    'direction': 'rtl'
                }],
                ['blockquote', 'code-block'],
                [{
                    'list': 'ordered'
                }, {
                    'list': 'bullet'
                }, {
                    'indent': '-1'
                }, {
                    'indent': '+1'
                }],
                ['link', 'image', 'video'],
                ['clean']
            ];
            hljs.configure({
                languages: ['html', 'xml', 'javascript', 'css']
            });
            quill = new Quill('#editor', {
                modules: {
                    toolbar: toolbarOptions,
                    // ✅ دعم Syntax Highlighting لو حابب
                    syntax: true
                },
                placeholder: 'اكتب محتوى رسالتك هنا...',
                theme: 'snow'
            });
            console.log('Quill initialized with full toolbar');
        } catch (e) {
            console.error('Quill init error', e);
        }
        const contentTextarea = document.getElementById('content');
        const Textarea = document.getElementById('contnentCode');
        const previewBtn = document.getElementById('preview-btn');
        const previewContainer = document.getElementById('preview-container');
        const editorContainer = document.getElementById('editor');
        let isPreviewMode = false;

        function isHtmlContent(text) {
            return /<[a-z][\s\S]*>/i.test(text.trim());
        }

        function isFullHtmlDocument(text) {
            return (/<!DOCTYPE\s+html>/i.test(text.trim()) || /<html[\s\S]*>/i.test(text.trim()));
        }

        function renderHtmlInIframe(htmlContent, container) {
            let iframe = container.querySelector('#preview-iframe');
            if (!iframe) {
                iframe = document.createElement('iframe');
                iframe.id = 'preview-iframe';
                container.appendChild(iframe);
            }
            const doc = iframe.contentDocument || iframe.contentWindow.document;
            doc.open();
            doc.write(htmlContent);
            doc.close();
        }
        if (previewBtn) {
            previewBtn.addEventListener('click', function(event) {
                event.preventDefault();
                isPreviewMode = !isPreviewMode;
                if (isPreviewMode) {
                    previewBtn.innerHTML = '<i class="fas fa-edit me-1"></i> Edit';
                    editorContainer.style.display = 'none';
                    previewContainer.style.display = 'block';
                    const rawText = quill.getText().trim();
                    if (isHtmlContent(rawText)) {
                        if (isFullHtmlDocument(rawText)) {
                            renderHtmlInIframe(rawText, previewContainer);
                        } else {
                            previewContainer.innerHTML = rawText;
                        }
                    } else {
                        previewContainer.innerHTML = quill.root.innerHTML;
                    }
                } else {
                    previewBtn.innerHTML = '<i class="fas fa-eye me-1"></i> Preview';
                    editorContainer.style.display = 'block';
                    previewContainer.style.display = 'none';
                    previewContainer.innerHTML = '';
                }
            });
        }

        // لما المستخدم يضغط على زر "Preview"
        if (quill) {
            quill.on('text-change', function() {
                contentTextarea.value = quill.root.innerHTML || '';
            });
        }
        // -------- Initialize Select2 ----------
        function initializeSelect2() {
            const config = {
                placeholder: "Select...",
                allowClear: true,
                width: '100%',
                multiple: true,
                closeOnSelect: false // <-- مهم جدًا
            };
            $('#name, #email, #category_id, #subcategory, #data_excel_id').each(function() {
                if (!$(this).hasClass('select2-hidden-accessible')) {
                    $(this).select2(config);
                    // console.log('Select2 initialized for:', this.id);
                }
            });
        }
        // Initialize after DOM ready
        $(document).ready(function() {
            initializeSelect2();
        });
        // -------- ajax setup ----------
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        // caches & xhr holders
        const subcategoryCache = {}; // key(categories) -> subcategories
        const receiversCache = {}; // key(categories, page) -> { results, more, total }
        let subcatXhr = null;
        let receiversXhr = null;
        let senderEmailsXhr = null;
        // paging state
        let currentPage = 1;
        const perPage = 1000;
        // helper to set options for select2
        function setOptionsSelect2($select, items, valueKey = 'id', labelKey = 'email', placeholder = 'None') {
            if (!items || items.length === 0) {
                $select.empty().append(`<option value="">${placeholder}</option>`);
                $select.prop('disabled', true);
                $select.trigger('change');
                return;
            }
            $select.empty();
            items.forEach(it => {
                const v = it[valueKey] ?? '';
                const label = it[labelKey] ?? it.text ?? it.email ?? '';
                $select.append(`<option value="${v}">${label}</option>`);
            });
            $select.prop('disabled', false);
            $select.trigger('change'); // Important for Select2
        }
        // -------- update sender emails ----------
        function updateSenderEmailsInternal() {
            const selectedSenders = $('#name').val() || [];
            const $email = $('#email');
            if (!selectedSenders.length) {
                setOptionsSelect2($email, [], 'id', 'email', 'Select sender name first');
                return;
            }
            if (senderEmailsXhr && senderEmailsXhr.readyState !== 4) senderEmailsXhr.abort();
            senderEmailsXhr = $.ajax({
                url: '{{ route("get.subcategories.receivers.senders") }}',
                method: 'GET',
                data: {
                    sender_ids: selectedSenders
                },
                success: function(response) {
                    const list = response.senders || [];
                    setOptionsSelect2($email, list, 'id', 'email', 'No emails available');
                    const ids = list.map(s => s.id);
                    if (ids.length) {
                        $email.val(ids).trigger('change');
                    }
                },
                error: function(xhr) {
                    if (xhr.statusText === 'abort') return;
                    console.error('sender emails error', xhr);
                }
            });
        }
        const debouncedUpdateSenderEmails = debounce(updateSenderEmailsInternal, 200);
        // -------- fetch subcategories ----------
        function loadSubcategories(categories) {
            const $sub = $('#subcategory');
            if (!categories || !categories.length) {
                setOptionsSelect2($sub, [], 'id', 'name', 'Select category first');
                return;
            }
            const key = keyOf(categories);
            if (subcategoryCache[key]) {
                setOptionsSelect2($sub, subcategoryCache[key], 'id', 'name', 'No subcategories');
                return;
            }
            if (subcatXhr && subcatXhr.readyState !== 4) subcatXhr.abort();
            subcatXhr = $.ajax({
                url: '{{ route("get.subcategories.receivers.senders") }}',
                method: 'GET',
                data: {
                    category_ids: categories
                },
                success: function(resp) {
                    const subs = resp.subcategories || [];
                    subcategoryCache[key] = subs;
                    setOptionsSelect2($sub, subs, 'id', 'name', 'No subcategories available');
                },
                error: function(xhr) {
                    if (xhr.statusText === 'abort') return;
                    console.error('subcategories error', xhr);
                }
            });
        }
        // -------- receivers paged ----------
        function receiversCacheKey(categories, page) {
            return JSON.stringify({
                cats: (categories || []).slice().sort(),
                p: page || 1
            });
        }

        function loadReceiversPage(page = 1, replace = true) {
            const categories = $('#category_id').val() || [];
            if (!categories.length) {
                setOptionsSelect2($('#data_excel_id'), [], 'id', 'email', 'Select category first');
                $('#load_more').hide();
                $('#select_all_info').text('');
                return;
            }
            const key = receiversCacheKey(categories, page);
            if (receiversCache[key]) {
                const cached = receiversCache[key];
                if (replace) {
                    setOptionsSelect2($('#data_excel_id'), cached.results, 'id', 'email', 'No receivers available');
                } else {
                    const $sel = $('#data_excel_id');
                    const existingValues = $sel.val() || [];
                    cached.results.forEach(r => {
                        if (!existingValues.includes(String(r.id))) {
                            const option = new Option(r.email, r.id, false, false);
                            $sel.append(option);
                        }
                    });
                    $sel.trigger('change');
                }
                if (cached.more) {
                    $('#load_more').show().data('next-page', page + 1);
                } else {
                    $('#load_more').hide();
                }
                return;
            }
            if (receiversXhr && receiversXhr.readyState !== 4) receiversXhr.abort();
            receiversXhr = $.ajax({
                url: '{{ route("receivers.search") }}',
                method: 'GET',
                data: {
                    category_ids: categories,
                    page: page,
                    per_page: perPage
                },
                dataType: 'json',
                success: function(resp) {
                    const items = resp.results || [];
                    const more = resp.pagination && resp.pagination.more ? true : false;
                    receiversCache[key] = {
                        results: items,
                        more: more,
                        total: resp.total || 0
                    };
                    if (replace) {
                        setOptionsSelect2($('#data_excel_id'), items, 'id', 'email', 'No receivers available');
                    } else {
                        const $sel = $('#data_excel_id');
                        const existingValues = $sel.val() || [];
                        items.forEach(it => {
                            if (!existingValues.includes(String(it.id))) {
                                const option = new Option(it.email, it.id, false, false);
                                $sel.append(option);
                            }
                        });
                        $sel.trigger('change');
                    }
                    if (more) {
                        $('#load_more').show().data('next-page', page + 1);
                    } else {
                        $('#load_more').hide();
                    }
                },
                error: function(xhr) {
                    if (xhr.statusText === 'abort') return;
                    console.error('receivers error', xhr);
                    toastr.error('Error loading receivers');
                }
            });
        }

        // load more click
        $('#load_more').on('click', function() {
            const next = $(this).data('next-page') || 1;
            loadReceiversPage(next, false);
        });
        // when category changes: load subcategories then first page of receivers
        $('#category_id').on('change', function() {
            const cats = $(this).val() || [];
            $('#select_all_info').text('');
            loadSubcategories(cats);
            currentPage = 1;
            loadReceiversPage(1, true);
        });
        // select visible
        $('#select_visible').on('click', function() {
            const $sel = $('#data_excel_id');
            const allOptions = $sel.find('option').map(function() {
                return $(this).val();
            }).get();
            $sel.val(allOptions).trigger('change');
            $('#select_all_info').text('Selected visible items');
        });
        //********************************************************************************
        // $('#templete').on('change', function() {
        //     const raw = $(this).val();
        //     const item = safeJSONParse(raw);

        //     if (!item) return;

        //     // ✅ الصحيح: تغيير قيمة حقل الموضوع (subject) الحقيقي
        //     $('#subject').val(item.subject ?? '').trigger('change');

        //     if (quill) {
        //         quill.root.innerHTML = item.body ?? '';
        //         contentTextarea.value = item.body ?? '';
        //     }
        // });

        $('#templete').on('change', function() {
            const raw = $(this).val();
            const item = safeJSONParse(raw);
            if (!item) return;

            // ✅ 1. ضع الموضوع في حقل subject
            $('#subject').val(item.subject ?? '').trigger('change');

            // ✅ 2. عرض الكود في textarea (وضع الكود)
            const codeTextarea = document.getElementById('contnentCode');
            if (codeTextarea) {
                codeTextarea.value = item.body ?? '';
                codeTextarea.style.display = 'block'; // يظهر textarea
                document.getElementById('editor').style.display = 'none'; // يخفي Quill
                document.getElementById('toolbar-container').style.display = 'none';
                // document.getElementById('content').style.display = 'none'; // textarea المخفي الأصلي
            }
        });
        //********************************************************************************

        $('#mainForm').on('submit', function() {
            const codeTextarea = document.getElementById('contnentCode');
            if (codeTextarea && codeTextarea.style.display !== 'none') {
                // وضع الكود نشط
                document.getElementById('content').value = codeTextarea.value;
            } else if (quill) {
                // وضع Quill نشط
                document.getElementById('content').value = quill.root.innerHTML;
            }
        });
        $('#name').on('change', debouncedUpdateSenderEmails);
        debouncedUpdateSenderEmails();




        // function selectCustom() {
        //     const limit = parseInt(document.getElementById("countNumber").value);
        //     const select = document.getElementById("data_excel_id");
        //     console.log('limit:', limit, 'options length:', select.options.length);

        //     if (!limit || limit < 1) {
        //         alert("من فضلك ادخل رقم صحيح");
        //         return;
        //     }

        //     // ✅ خد كل الـ options اللي ظاهرة دلوقتي
        //     const allOptions = Array.from(select.options);
        //     const actualLimit = Math.min(limit, allOptions.length); // ✅ خد الأقل بين المطلوب والظاهر

        //     for (let i = 0; i < allOptions.length; i++) {
        //         allOptions[i].selected = (i < actualLimit);
        //     }

        //     // ✅ حدّث Select2 لو مستخدم
        //     if (typeof $(select).select2 === 'function') {
        //         $(select).trigger('change');
        //     }

        //     // ✅ عرض عدد المختارين
        //     document.getElementById('select_all_info').textContent = `${actualLimit} Selected`;
        // }

        // function clearAll() {
        //     const select = document.getElementById("data_excel_id");
        //     for (let option of select.options) {
        //         option.selected = false;
        //     }
        // }

        document.getElementById("codingToggleBtn").addEventListener("click", function() {
            document.getElementById('contnentCode').name = 'content';
            let div = document.getElementById("contnentCode");

            if (div.style.display === "none") {
                div.style.display = "block"; // يظهر
                contentTextarea.style.display = "none";
                contentTextarea.value = null;
                document.getElementById('editor').style.display = 'none'; // يخفي Quill
                document.getElementById('toolbar-container').style.display = 'none';
            } else {
                div.style.display = "none"; // يخفي
            }
        });
        document.getElementById('useString').addEventListener('click', function() {
            document.getElementById('content').name = 'content';
            document.getElementById('contnentCode').name = '';
            document.getElementById('contnentCode').style.display = 'none';
            document.getElementById('editor').style.display = 'block'; // يخفي Quill
            document.getElementById('toolbar-container').style.display = 'block';
            // document.getElementById('content').style.display = 'block'; // textarea 
        });
    });
</script>
@endsection



<!-- <script type="text/javascript">
    // 1. الدوال العالمية (Global Functions) - يجب أن تكون خارج DOMContentLoaded لتعمل مع onclick
    
    // التبديل بين وضع الإرسال الفوري والمجدول
    function toggleScheduleFields() {
        const scheduleFields = document.getElementById('scheduleFields');
        const modeSchedule = document.getElementById('modeSchedule');
        if (modeSchedule && scheduleFields) {
            scheduleFields.style.display = modeSchedule.checked ? 'block' : 'none';
        }
    }

    // حساب المدة تلقائياً بناءً على عدد المرسين والمستقبلين
    function calculateDuration() {
        const senders = $('#name').val()?.length || 0;
        const receivers = $('#data_excel_id').val()?.length || 0;
        if (senders === 0 || receivers === 0) {
            alert('Please select senders and receivers first');
            return;
        }
        fetch('/dashboard/message/calculate-duration', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                },
                body: JSON.stringify({
                    sender_count: senders,
                    receiver_count: receivers
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success && data.duration) {
                    document.querySelector('input[name="duration_value"]').value = data.duration.value;
                    document.querySelector('select[name="duration_unit"]').value = data.duration.unit;
                    if (data.message) alert(data.message);
                }
            })
            .catch(() => alert('Error calculating duration'));
    }

    // وظيفة اختيار عدد محدد من الإيميلات بناءً على الكاتيجوري
    function selectCustom() {
        const limit = $('#countNumber').val();
        const categories = $('#category_id').val();

        if (!limit || limit < 1) {
            toastr.warning("من فضلك ادخل عدداً صحيحاً");
            return;
        }
        if (!categories || categories.length === 0) {
            toastr.error("يجب اختيار تصنيف (Category) أولاً لجلب البيانات منه");
            return;
        }

        const btn = $('button[onclick="selectCustom()"]');
        const originalText = btn.text();
        btn.prop('disabled', true).text('جاري الجلب...');

        $.ajax({
            url: '{{ route("receivers.get_top_ids") }}', // المسار الذي يعيد id و text
            method: 'GET',
            data: {
                limit: limit,
                category_ids: categories
            },
            success: function(resp) {
                const $select = $('#data_excel_id');
                if (resp.length === 0) {
                    toastr.info("لا توجد مستلمين متاحين في هذه الأقسام");
                } else {
                    resp.forEach(item => {
                        // نتحقق إذا كان الإيميل موجوداً بالفعل لتجنب التكرار
                        if ($select.find("option[value='" + item.id + "']").length === 0) {
                            // نستخدم item.text (الإيميل) لضمان عدم ظهور null
                            let newOption = new Option(item.text, item.id, true, true);
                            $select.append(newOption);
                        } else {
                            $select.find("option[value='" + item.id + "']").prop('selected', true);
                        }
                    });
                    $select.trigger('change');
                    toastr.success('تم اختيار ' + resp.length + ' مستلم بنجاح');
                }
            },
            error: function() {
                toastr.error('حدث خطأ أثناء الاتصال بالسيرفر، تأكد من وجود المسار');
            },
            complete: function() {
                btn.prop('disabled', false).text(originalText);
            }
        });
    }

    // إلغاء كل الاختيارات
    function clearAll() {
        $('#data_excel_id').val(null).trigger('change');
        $('#select_all_info').text('0 Selected');
    }

    // 2. الدوال التي تعمل بعد تحميل الصفحة (DOMContentLoaded)
    document.addEventListener('DOMContentLoaded', function() {
        
        // -------- utilities --------
        function debounce(fn, wait) {
            let t;
            return function(...a) {
                clearTimeout(t);
                t = setTimeout(() => fn.apply(this, a), wait);
            };
        }

        function safeJSONParse(val) {
            try { return JSON.parse(val); } catch (e) { return null; }
        }

        toastr.options = {
            closeButton: true,
            progressBar: true,
            positionClass: 'toast-top-right'
        };

        // -------- quill initialized ----------
        let quill = null;
        try {
            const toolbarOptions = [
                [{'font': []}],
                [{'size': ['small', false, 'large', 'huge']}],
                ['bold', 'italic', 'underline', 'strike'],
                [{'color': []}, {'background': []}],
                [{'script': 'sub'}, {'script': 'super'}],
                [{'header': [1, 2, 3, 4, 5, 6, false]}],
                [{'align': []}, {'direction': 'rtl'}],
                ['blockquote', 'code-block'],
                [{'list': 'ordered'}, {'list': 'bullet'}, {'indent': '-1'}, {'indent': '+1'}],
                ['link', 'image', 'video'],
                ['clean']
            ];
            hljs.configure({ languages: ['html', 'xml', 'javascript', 'css'] });
            quill = new Quill('#editor', {
                modules: { toolbar: toolbarOptions, syntax: true },
                placeholder: 'اكتب محتوى رسالتك هنا...',
                theme: 'snow'
            });
        } catch (e) { console.error('Quill init error', e); }

        const contentTextarea = document.getElementById('content');
        const previewBtn = document.getElementById('preview-btn');
        const previewContainer = document.getElementById('preview-container');
        const editorContainer = document.getElementById('editor');
        let isPreviewMode = false;

        // -------- Select2 تهيئة المستلمين (AJAX Search) ----------
        $('#data_excel_id').select2({
            placeholder: "ابحث عن إيميل...",
            allowClear: true,
            closeOnSelect: false,
            ajax: {
                url: '{{ route("receivers.search") }}',
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    return {
                        q: params.term,
                        category_ids: $('#category_id').val(),
                        page: params.page || 1
                    };
                },
                processResults: function (data) {
                    return {
                        results: data.results.map(item => ({ id: item.id, text: item.email || item.text })),
                        pagination: { more: data.pagination.more }
                    };
                }
            }
        });

        // تحديث العداد عند أي تغيير في الاختيارات
        $('#data_excel_id').on('change', function() {
            let count = $(this).val() ? $(this).val().length : 0;
            $('#select_all_info').text(count + " Selected");
        });

        // تهيئة باقي عناصر Select2
        $('#name, #email, #category_id, #subcategory').select2({
            placeholder: "Select...",
            allowClear: true,
            closeOnSelect: false,
            width: '100%'
        });

        $.ajaxSetup({
            headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
        });

        // -------- وظائف القوالب والمحرر ----------
        $('#templete').on('change', function() {
            const raw = $(this).val();
            const item = safeJSONParse(raw);
            if (!item) return;
            $('#subject').val(item.subject ?? '').trigger('change');
            if (document.getElementById('contnentCode').style.display !== 'none') {
                $('#contnentCode').val(item.body ?? '');
            } else if (quill) {
                quill.root.innerHTML = item.body ?? '';
            }
        });

        // التبديل بين وضع الكود والنص المرئي
        document.getElementById("codingToggleBtn").addEventListener("click", function() {
            $('#contnentCode').show().attr('name', 'content');
            $('#editor, .ql-toolbar').hide();
        });

        document.getElementById('useString').addEventListener('click', function() {
            $('#contnentCode').hide().attr('name', '');
            $('#editor, .ql-toolbar').show();
        });

        // عند إرسال الفورم، تأكد من نقل المحتوى لـ textarea المخفي
        $('#mainForm').on('submit', function() {
            if ($('#contnentCode').is(':visible')) {
                $('#content').val($('#contnentCode').val());
            } else if (quill) {
                $('#content').val(quill.root.innerHTML);
            }
        });

        // تحديث إيميلات المرسل
        $('#name').on('change', function() {
            const selectedSenders = $(this).val() || [];
            if (!selectedSenders.length) {
                $('#email').empty().prop('disabled', true).trigger('change');
                return;
            }
            $.get('{{ route("get.subcategories.receivers.senders") }}', { sender_ids: selectedSenders }, function(response) {
                const $email = $('#email');
                $email.empty().prop('disabled', false);
                response.senders.forEach(s => {
                    $email.append(new Option(s.email, s.id, true, true));
                });
                $email.trigger('change');
            });
        });

        // معاينة المحتوى
        if (previewBtn) {
            previewBtn.addEventListener('click', function(e) {
                e.preventDefault();
                isPreviewMode = !isPreviewMode;
                if (isPreviewMode) {
                    previewBtn.innerHTML = '<i class="fas fa-edit me-1"></i> Edit';
                    $(editorContainer).hide();
                    $(previewContainer).show().html($('#contnentCode').is(':visible') ? $('#contnentCode').val() : quill.root.innerHTML);
                } else {
                    previewBtn.innerHTML = '<i class="fas fa-eye me-1"></i> Preview';
                    $(editorContainer).show();
                    $(previewContainer).hide();
                }
            });
        }
    });
</script> -->
