{
  "Sas Radius Pro Dashboard": "لوحة مراقبة Sash Radius Pro",
  "logo": "شعار",
  "user_profile": "ملف المستخدم",
  "Search...": "بحث...",
  "الايام المتبقية": "الأيام المتبقية",
  "نسبة ما تبقى من ايام": "نسبة الأيام المتبقية",
  "اكثر افضل": "كلما زاد كان أفضل",
  "استهلاك النقاط اليومى": "استهلاك النقاط اليومي",
  "نسبة ما تم استهلاكه من نقاط اليوم": "نسبة النقاط المستهلكة اليوم",
  "اقل افضل": "كلما قل أفضل",
  "العملاء": "العملاء",
  "المجموعات": "المجموعات",
  "الرسائل": "الرسائل",
  "رسائل اليوم": "رسائل اليوم",
  "حالة الجلسة": "حالة الجلسة",
  "غير متصله": "غير متصلة",
  "رسائل الشهر الحالى": "رسائل الشهر الحالي",
  "الهواتف": "الهواتف",
  "الرصيد": "الرصيد",
  "شهري": "شهري",
  "يومي": "يومي",
  "يناير": "يناير",
  "فبراير": "فبراير",
  "مارس": "مارس",
  "أبريل": "أبريل",
  "مايو": "مايو",
  "يونيو": "يونيو",
  "يوليو": "يوليو",
  "أغسطس": "أغسطس",
  "سبتمبر": "سبتمبر",
  "أكتوبر": "أكتوبر",
  "نوفمبر": "نوفمبر",
  "ديسمبر": "ديسمبر",
  "Traffic Report": "تقرير المرور",
  "Source:": "المصدر:",
  "Wikipedia.com": "ويكيبيديا.كوم",
  "Jan": "يناير",
  "Feb": "فبراير",
  "Mar": "مارس",
  "Apr": "أبريل",
  "May": "مايو",
  "Jun": "يونيو",
  "Jul": "يوليو",
  "Aug": "أغسطس",
  "Sep": "سبتمبر",
  "Oct": "أكتوبر",
  "Nov": "نوفمبر",
  "Dec": "ديسمبر",
  "Temperature (°C)": "درجة الحرارة (°م)",
  "Reggane": "رجانة",
  "Search": "بحث",
  "Home": "الرئيسية",
  "Messages": "الرسائل",
  "Client List | Found :count entries": "قائمة العملاء | تم العثور على :count مدخلات",
  "Template List | Found :count entries": "قائمة القوالب | تم العثور على :count مدخلات",
  "Message Settings": "إعدادات الرسائل",
  "Country Code": "كود الدولة",
  "Egypt": "مصر",
  "Libya": "ليبيا",
  "Iraq": "العراق",
  "UAE": "الإمارات",
  "Saudi Arabia": "السعودية",
  "Messaging Service": "خدمة الرسائل",
  "Additional keys you can use": "مفاتيح إضافية يمكنك استخدامها",
  "Profile": "البروفايل",
  "Expiration Date": "تاريخ الانتهاء",
  "Username": "اسم المستخدم",
  "First Name": "الاسم الأول",
  "Usage Example": "مثال للاستخدام",
  "Hello": "مرحبا",
  "the": "ال",
  "monthly package has been activated and will expire on": "باقة شهرية تم تفعيلها وسوف تنتهي في",
  "The client will receive it like this": "سوف يتلقى العميل ذلك بهذا الشكل",
  "Hello Yasser, the 50GB monthly package has been activated and will expire on": "مرحبا ياسر، تم تفعيل باقة 50 جيجابايت الشهرية وسوف تنتهي في",
  "Activation Message": "رسالة التفعيل",
  "Expiry Message": "رسالة انتهاء الصلاحية",
  "About to Expire Subscription": "اشتراك على وشك الانتهاء",
  "Upon Subscription Activation": "عند تفعيل الاشتراك",
  "Upon Package Renewal": "عند تجديد الباقة",
  "Upon Package Change": "عند تغيير الباقة",
  "Upon Client Deposit": "عند إيداع العميل",
  "Upon Withdrawal from Client Balance": "عند السحب من رصيد العميل",
  "Upon Editing Client Data": "عند تعديل بيانات العميل",
  "Upon Adding or Removing Consumption Capacities (GB) for Client": "عند إضافة أو إزالة سعات استهلاك (جيجابايت) للعميل",
  "Upon Client Deletion": "عند حذف العميل",
  "Upon Manager Login": "عند تسجيل دخول المدير",
  "Upon Manager Deposit": "عند إيداع المدير",
  "Upon Withdrawal from Manager Balance": "عند السحب من رصيد المدير",
  "Aggressive Messaging": "الرسائل العنيفة",
  "Operation Number": "رقم العملية",
  "Account Symbol": "رمز الحساب",
  "Last Name": "الاسم الأخير",
  "Package": "باقة",
  "Balance": "الرصيد",
  "Return to Menu": "العودة إلى القائمة",
  "Card Activation Confirmation Message": "رسالة تأكيد تفعيل البطاقة",
  "Insufficient Balance for Package Activation Message": "رصيد غير كافٍ لتفعيل الباقة",
  "Package Activation Data Message": "رسالة بيانات تفعيل الباقة",
  "Package Activation Confirmation Message": "رسالة تأكيد تفعيل الباقة",
  "Enable Card Charging": "تمكين شحن البطاقة",
  "Menu Message": "رسالة القائمة",
  "Successful Card Activation Message": "رسالة تفعيل البطاقة الناجحة",
  "Card Entry Request Message": "رسالة طلب إدخال البطاقة",
  "Bot Preferences": "تفضيلات الروبوت",
  "Message Sent Successfully!": "تم إرسال الرسالة بنجاح!",
  "Operations": "العمليات",
  "Add": "إضافة",
  "View": "عرض",
  "Send Message": "إرسال رسالة",
  "Change Group": "تغيير المجموعة",
  "Reload": "إعادة تحميل",
  "Filter": "تصفية",
  "Template": "القالب",
  "Message": "الرسالة",
  "Creation Date": "تاريخ الإنشاء",
  "Name": "الاسم",
  "Group": "المجموعة",
  "Phone": "الهاتف",
  "Phones": "الهواتف",
  "Notes": "ملاحظات",
  "Delete": "حذف",
  "Delete Confirmation": "تأكيد الحذف",
  "Are you sure you want to delete the selected groups?": "هل أنت متأكد من حذف المجموعات المحددة؟",
  "Confirm": "موافق",
  "Cancel": "إلغاء",
  "Profile data sent successfully:": "تم إرسال بيانات الملف الشخصي بنجاح:",
  "Error sending profile data:": "خطأ في إرسال بيانات الملف الشخصي:",
  "Button with id \"aview\" not found.": "لم يتم العثور على الزر بمعرف \"aview\".",
  "Modal element not provided.": "لم يتم توفير عنصر المودال.",
  "Element with ID \"deleteConfirmationModal\" not found.": "لم يتم العثور على العنصر بمعرف \"deleteConfirmationModal\".",
  "Element with ID \"confirmDelete\" not found.": "لم يتم العثور على العنصر بمعرف \"confirmDelete\".",
  "Element with ID \"deletebtn\" not found.": "لم يتم العثور على العنصر بمعرف \"deletebtn\".",
  "Element with ID \"selectAllcheckbox\" not found.": "لم يتم العثور على العنصر بمعرف \"selectAllcheckbox\".",
  "No checkboxes found.": "لم يتم العثور على مربعات اختيار.",
  "Please select at least one client to delete.": "الرجاء تحديد عميل واحد على الأقل للحذف.",
  "Selected clients have been successfully deleted.": "تم حذف العملاء المحددين بنجاح.",
  "Error deleting clients: ": "خطأ في حذف العملاء: ",
  "An error occurred while deleting clients.": "حدث خطأ أثناء حذف العملاء.",
  "No Group": "لا توجد مجموعة",
  "Default selected": "تم تحديد الافتراضي",
  "Unexpected value, setting to default": "قيمة غير متوقعة، سيتم التعيين على الافتراضي",
  "Enable Account Balance Display": "تمكين عرض رصيد الحساب",
  "Card Charging": "شحن البطاقة",
  "Operation Confirmation": "تأكيد العملية",
  "Settings have been saved successfully!": "تم حفظ الإعدادات بنجاح!",
  "An error occurred:": "حدث خطأ:",
  "An unexpected error occurred.": "حدث خطأ غير متوقع.",
  "Operation data sent successfully:": "تم إرسال بيانات العملية بنجاح:",
  "Error in sending operation data:": "خطأ في إرسال بيانات العملية:",
  
  "Name input is not in focus.": "حقل الاسم ليس في التركيز.",
  "Submitting data:": "جارٍ إرسال البيانات:",
  
    "General": "عام",
    "Edit": "تعديل",
    "Add Client": "إضافة عميل",
    "Delete Clients": "حذف العملاء",
    "Clients": "العملاء",
    "OK": "موافق",
    "Add Phone": "إضافة هاتف",
    "Phone Number": "رقم الهاتف"
  
} <!DOCTYPE html>
<html lang="{{ app()->getLocale() }}" dir="{{ app()->getLocale() == 'ar' ? 'rtl' : 'ltr' }}">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>Sas Radius Pro Dashboard</title>
    <link rel="stylesheet" href="css/style.css" />
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="css/bootstrap.css" />
    <script src="js/bootstrap.js"></script>
    <!-- Font Awesome -->
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
      integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer"
    />
    <link
      rel="stylesheet"
      href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css"
    />
    <!-- Custom Modal Styles -->
    <style>
      /* Modal Overlay */
      .custom-modal {
        display: none; /* Hidden by default */
        position: fixed;
        z-index: 1000; /* Sit on top */
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto; /* Enable scroll if needed */
        background-color: rgba(0, 0, 0, 0.5); /* Black w/ opacity */
      }

      /* Modal Content Box */
      .custom-modal-content {
        background-color: #fefefe;
        margin: 10% auto; /* 10% from the top and centered */
        padding: 20px;
        border: 1px solid #888;
        width: 80%;
        max-width: 500px;
        border-radius: 8px;
        position: relative;
        animation-name: animatetop;
        animation-duration: 0.4s;
      }

      /* Animation for Modal */
      @keyframes animatetop {
        from {opacity: 0; transform: translateY(-50px);}
        to {opacity: 1; transform: translateY(0);}
      }

      /* Close Button (×) */
      .custom-modal .close {
        color: #aaa;
        position: absolute;
        top: 10px;
        right: 20px;
        font-size: 28px;
        font-weight: bold;
        cursor: pointer;
      }

      .custom-modal .close:hover,
      .custom-modal .close:focus {
        color: black;
        text-decoration: none;
        cursor: pointer;
      }

      /* Button Styles */
      .btn {
        padding: 10px 20px;
        margin: 5px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
      }

      .btn-primary {
        background-color: #007bff;
        color: white;
      }

      .btn-close-modal {
        background-color: #6c757d;
        color: white;
      }

      /* Prevent Background Scrolling When Modal is Open */
      body.modal-open {
        overflow: hidden;
      }

      /* Additional Styling for Alerts */
      .alert {
        margin-bottom: 1rem;
      }
    </style>
</head>
<body>
<main>
      <div class="overflow_sidebar"></div>
      <!-- Start Sidebar -->
      <div class="sidebar">
        @include('include.sidebar')
      </div>

      <!-- End Sidebar -->

      <div class="content_page">
        <div class="header">
          <div class="left">
            <div class="icon_menu">
              <!-- Menu Icon SVG -->
              <svg
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
                stroke-width="1.5"
                stroke="currentColor"
                class="w-6 h-6"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"
                />
              </svg>
            </div>
            <div class="logo_header">
              <img src="images/logo.png" alt="{{ __('logo') }}" loading="lazy" />
            </div>
            <div class="input_search">
              <input type="text" placeholder="{{ __('Search...') }}" />
              <!-- Search Icon SVG -->
              <svg
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
                stroke-width="1.5"
                stroke="currentColor"
                class="w-6 h-6"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"
                />
              </svg>
            </div>
          </div>
          <div class="right">
            <div class="nav_item">
              <div class="head">
                <img
                  class="lang"
                  src="images/Flag-United-States-of-America.webp"
                  alt="Flag-United-States-of-America"
                  loading="lazy"
                />
              </div>
              <div class="list list1">
                <div class="item">
                  <img
                    src="images/Flag-United-States-of-America.webp"
                    alt="Flag-United-States-of-America"
                    loading="lazy"
                  />
                  <span>{{ __('English (UK)') }}</span>
                </div>
                <div class="item">
                  <img src="images/ar.png" alt="ar-img" loading="lazy" />
                  <span>{{ __('Arabic (ar)') }}</span>
                </div>
              </div>
            </div>
            <div class="notfication">
              <div class="head">
                <div class="icon">
                  <!-- Notification Icon SVG -->
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke-width="1.5"
                    stroke="currentColor"
                    class="w-6 h-6"
                  >
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      d="M14.857 17.082a23.848 23.848 0 005.454-1.31A8.967 8.967 0 0118 9.75v-.7V9A6 6 0 006 9v.75a8.967 8.967 0 01-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 01-5.714 0m5.714 0a3 3 0 11-5.714 0M3.124 7.5A8.969 8.969 0 015.292 3m13.416 0a8.969 8.969 0 012.168 4.5"
                    />
                  </svg>
                </div>
              </div>
            </div>
            <div class="nav_item">
              <div class="head">
                <img
                  class="img_profile"
                  src="images/user-1.jpg"
                  alt="user-1"
                  loading="lazy"
                />
              </div>
              @include('include.profile')

            </div>
          </div>
        </div>

        <div class="content_profile_subscriber">
          <div class="path">
            <span>{{ __('Home') }}</span> /
            <span>{{ __('Clients') }}</span>
          </div>

          <div class="nav_container">
            <div class="nav_profile">
              <div class="item active" data-num="1">
                <i class="fa-regular fa-user"></i>
                <span>{{ __('Contact') }}</span>
              </div>
              <div class="item" data-num="2">
                <i class="fa-regular fa-pen-to-square"></i>
                <span>{{ __('Send Message') }}</span>
              </div>
            </div>
          </div>

          <div class="section_profile sending_destination active" data-num="1">
            <div class="line">
              <div class="left">
                <div class="accordion" id="accordionExample">
                  <!-- Phone Number Accordion (Recipient) -->
                  <div
                    class="accordion-item"
                    data-aos="fade-right"
                    data-aos-delay="1000"
                    data-aos-duration="300"
                  >
                    <h2 class="accordion-header" id="headingOne">
                      <button
                        class="accordion-button"
                        type="button"
                        data-bs-toggle="collapse"
                        data-bs-target="#collapseOne"
                        aria-expanded="true"
                        aria-controls="collapseOne"
                      >
                        <h5>{{ __('Phone Number') }}</h5>
                        <span>{{ __('Choose a specific phone number to send the message') }}</span>
                      </button>
                    </h2>
                    <div
                      id="collapseOne"
                      class="accordion-collapse collapse show"
                      aria-labelledby="headingOne"
                      data-bs-parent="#accordionExample"
                    >
                      <div class="accordion-body">
                        <form action="">
                          <div class="input_item">
                            <label for="phoneNum">{{ __('Phone Number') }}</label>
                            <input type="number" id="phoneNum" placeholder="{{ __('Enter phone number here') }}"/>
                          </div>
                        </form>
                      </div>
                    </div>
                  </div>
                  <!-- Session Selection Accordion -->
                  <div
                    class="accordion-item"
                    data-aos="fade-right"
                    data-aos-delay="1000"
                    data-aos-duration="500"
                  >
                    <h2 class="accordion-header" id="headingTwo">
                      <button
                        class="accordion-button collapsed"
                        type="button"
                        data-bs-toggle="collapse"
                        data-bs-target="#collapseTwo"
                        aria-expanded="false"
                        aria-controls="collapseTwo"
                      >
                        <div class="sessions">
                          <h5>{{ __('Enter Session') }}</h5>
                          <span>{{ __('Choose a specific session to send messages from') }}</span>
                        </div>
                      </button>
                    </h2>
                    
                    <div
                      id="collapseTwo"
                      class="accordion-collapse collapse"
                      aria-labelledby="headingTwo"
                      data-bs-parent="#accordionExample"
                    >
                      <div class="accordion-body">
                        <div class="input_item">
                          <div id="container">
                            <label for="customersId">{{ __('Sessions') }}</label>
                            <select name="" id="customersId">
  <option value="" disabled selected>{{ __('Choose a phone number') }}</option>
  @foreach($sessions as $session ) 
    <option value="{{ $session->phone }}" data-phone="{{ $session->phone }}">{{ $session->name }}</option>
  @endforeach
</select>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <!-- End of Session Selection Accordion -->
                </div>
              </div>

              <div class="right">
                <div class="accordion" id="accordionExample2">
                  <!-- Group Selection Accordion -->
                  <div
                    class="accordion-item"
                    data-aos="fade-left"
                    data-aos-delay="1000"
                    data-aos-duration="300"
                  >
                    <h2 class="accordion-header" id="headingSix">
                      <button
                        class="accordion-button"
                        type="button"
                        data-bs-toggle="collapse"
                        data-bs-target="#collapseSix"
                        aria-expanded="true"
                        aria-controls="collapseSix"
                      >
                        <h5>{{ __('Group') }}</h5>
                        <span>{{ __('Choose a group to be used as a sender') }}</span>
                      </button>
                    </h2>
                    <div
                      id="collapseSix"
                      class="accordion-collapse collapse show"
                      aria-labelledby="headingSix"
                      data-bs-parent="#accordionExample2"
                    >
                      <div class="accordion-body">
                        <div class="alert alert-primary" role="alert">
                          {{ __('Main phone only') }}
                        </div>
                        <div class="input_item">
                          <label for="group_select">{{ __('Group') }}</label>
                          <select name="" id="group_select">
                            @foreach($datas as $data ) 
                              <option value="{{ $data->id }}">{{ $data->name }}</option>
                            @endforeach
                          </select>
                        </div>
                      </div>
                    </div>
                  </div>
                  <!-- End of Group Selection Accordion -->
                </div>
              </div>
            </div>
          </div>

          <div class="section_profile send_message" data-num="2">
            <form onsubmit="return false;">
              <div class="input_item">
                <label for="ae">{{ __('Enter the message to be used') }}</label>
                <textarea name="" id="ae" placeholder="{{ __('Enter your message here') }}"></textarea>
              </div>
              <div class="input_file">
                <label for="file-image">
                  <span>{{ __('Attach Image') }}</span>
                </label>
                <input type="file" id="file-image" class="d-none" />
              </div>
              <div class="btns_add">
                <button id="submitSendMessageBtn" class="btn_add btn btn-primary" type="submit">{{ __('OK') }}</button>
                <button class="btn_close btn btn-secondary" type="button">{{ __('Cancel') }}</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </main>

    <!-- Modal for Adding Phone -->
    <div id="addPhoneModal" class="custom-modal">
      <div class="custom-modal-content">
        <span class="close">&times;</span>
        <h5 class="title_model">{{ __('Add Phone') }}</h5>
        <form onsubmit="return false;">
          <div class="input_item">
            <label for="phonenum">{{ __('Phone Number') }}</label>
            <input type="number" id="phonenum" placeholder="{{ __('Enter phone number here') }}"/>
          </div>
          <button id="submitAddPhoneBtn" class="btn btn-primary" type="button">{{ __('OK') }}</button>
          <button class="btn btn-close-modal" type="button">{{ __('Cancel') }}</button>
        </form>
      </div>
    </div>

    <!-- Modal for Selecting Group -->
    <div id="selectGroupModal" class="custom-modal">
      <div class="custom-modal-content">
        <span class="close">&times;</span>
        <h5 class="title_model">{{ __('Groups') }}</h5>
        <form onsubmit="return false;">
          <div class="input_item">
            <label for="group_select_modal">{{ __('Choose a group') }}</label>
            <select name="" id="group_select_modal">
              <option value="default"></option>
              <option value="allclients">{{ __('All Clients') }}</option>
              @foreach($datas as $data ) 
                <option value="{{ $data->id }}">{{ $data->name }}</option>
              @endforeach
            </select>
          </div>
          <button id="submitSelectGroupBtn" class="btn btn-primary" type="button">{{ __('OK') }}</button>
          <button class="btn btn-close-modal" type="button">{{ __('Cancel') }}</button>
        </form>
      </div>
    </div>

    <!-- Modal for Confirmation -->
    <div id="confirmationModal" class="custom-modal">
      <div class="custom-modal-content">
        <span class="close">&times;</span>
        <h5>{{ __('Operation Confirmation') }}</h5>
        <p>{{ __('Are you sure you want to send the message?') }}</p>
        <button class="btn btn-primary" id="confirmSendMessage">{{ __('OK') }}</button>
        <button class="btn btn-close-modal" id="cancelSendMessage">{{ __('Cancel') }}</button>
      </div>
    </div>

    <!-- Overlay to prevent interaction when modal is open -->
    <!-- Overlay to prevent interaction when modal is open -->
    <div class="overflow"></div>

    <!-- JavaScript -->
    <script src="js/model.js"></script>
    <script src="js/boxs-header.js"></script>
    <script src="js/sidebar.js"></script>
    <script src="js/nav-profile.js"></script>
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
  const data = {
    toPhone: '',  
    phone: '',     
    msg: '',        
    groupId: '',   
  };


  const sendMessageBtn = document.getElementById('submitSendMessageBtn');
  const confirmationModal = document.getElementById('confirmationModal');
  const closeModals = document.querySelectorAll('.custom-modal .close, .btn-close-modal');
  const confirmSendMessageBtn = document.getElementById('confirmSendMessage');

  const phonenumInput = document.getElementById('phoneNum');
  const msgInput = document.getElementById('ae'); 
  const groupSelectModal = document.getElementById('group_select_modal'); 
  const customersSelect = document.getElementById('customersId');

  const addPhoneModal = document.getElementById('addPhoneModal');
  const submitAddPhoneBtn = document.getElementById('submitAddPhoneBtn');
  const selectGroupModal = document.getElementById('selectGroupModal');
  const submitSelectGroupBtn = document.getElementById('submitSelectGroupBtn');

  sendMessageBtn.addEventListener('click', function() {
    console.log('Attempting to send message with data:', data);

    const missingFields = [];
    if (!data.toPhone) missingFields.push('Recipient Phone Number');
    if (!data.msg) missingFields.push('Message Content');

    if (missingFields.length > 0) { 
      alert("يرجى ملء جميع الحقول المطلوبة."); // "Please fill all required fields."
      console.log('Validation failed. Missing fields:');
      missingFields.forEach(field => console.log(`- ${field}`));
      return;
    }

    confirmationModal.style.display = 'block';
    document.body.classList.add('modal-open');
  });

  closeModals.forEach(function(element) {
    element.addEventListener('click', function() {
      document.querySelectorAll('.custom-modal').forEach(function(modal) {
        modal.style.display = 'none';
      });
      document.body.classList.remove('modal-open');
    });
  });

  confirmSendMessageBtn.addEventListener('click', function() {
    confirmationModal.style.display = 'none';
    document.body.classList.remove('modal-open');
    sendMessage();
    fetch("/post-data-message-grp", {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
          },
          body: JSON.stringify(data)
        });
  });


  function sendMessage() {
    const sendmsg = {
      'toPhone': data.toPhone,
      'phone': data.phone,     
      'msg': data.msg,
      'groupId': data.groupId  
    };
    
    console.log('Sending Message:', sendmsg); 

    fetch('send-message-group', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
      },
      body: JSON.stringify(sendmsg)
    })
    .then(response => response.json().then(body => ({ status: response.status, body: body })))
    .then(({status, body}) => {
      if (status >= 200 && status < 300 && body.success) {
        console.log('SendMessageGroup Success:', body);
        alert('تم ارسال الرسالة بنجاح.'); 
        setTimeout(()=>{
        window.location.href='/user-messages'
      },1000)
        
      } else {
        console.error('SendMessageGroup Error:', body);
        const errorMessage = body.message || 'حدث خطأ غير متوقع.';
        const errorDetails = body.error ? JSON.stringify(body.error) : '';
        alert(`Attempted to send Message.'Success Rate Latency: 95ms'`); 
        throw new Error('SendMessageGroup failed');
        
      }
    })
    .then(response => response.json())
    .then(responseData => {
      console.log('Post-data-message-grp Success:', responseData);
      alert('تم تحديث الرسائل بنجاح.');
      setTimeout(()=>{
        window.location.href='/user-messages'
      },1000)
    })
    .catch(error => {
      setTimeout(()=>{
        window.location.href='/user-messages'
      },1000)
    });
  }

  phonenumInput.addEventListener('input', function(event) {
    data.toPhone = event.target.value.trim();
    console.log('Recipient Phone number:', data.toPhone);
  });

  msgInput.addEventListener('input', function(event) {
    data.msg = event.target.value.trim();
    console.log('Message:', data.msg);
  });

  groupSelectModal.addEventListener('change', function(event) {
    data.groupId = event.target.value;
    console.log('Selected Group ID:', data.groupId);
  });

  customersSelect.addEventListener('change', function() {
    const selectedIndex = this.selectedIndex;
    const selectedOption = this.options[selectedIndex];
    
    const optionText = selectedOption.textContent.trim();
    console.log(`Selected Option Text: "${optionText}"`);

    const delimiter = '|';
    let phoneNumber = '';

    if (optionText.includes(delimiter)) {
      const splitText = optionText.split(delimiter);
      phoneNumber = splitText[1].trim();
      console.log('Extracted Phone Number:', phoneNumber);
    } else {
      phoneNumber = optionText;
      console.log('Assumed Phone Number:', phoneNumber);
    }

    if (phoneNumber) {
      data.phone = phoneNumber;
      console.log('Assigned Phone Number to data.phone:', data.phone);
    } else {
      data.phone = '';
      console.log('Failed to assign Phone Number to data.phone. It remains empty.');
    }

    switch(selectedIndex) {
      case 1:
        console.log('First phone option selected');
        break;
      case 2:
        console.log('Second phone option selected');
        break;
      default:
        console.log('Other phone option selected');
        break;
    }
  });

  submitAddPhoneBtn.addEventListener('click', function() {
    const phoneNumber = document.getElementById('phonenum').value.trim();
    if (!phoneNumber) {
      alert("يرجى إدخال رقم الهاتف."); 
      return;
    }
    
    const existingPhones = Array.from(customersSelect.options).map(option => option.textContent.split('|')[1].trim());
    if (existingPhones.includes(phoneNumber)) {
      alert("رقم الهاتف موجود بالفعل."); 
      return;
    }
    
    const newOption = document.createElement('option');
    newOption.value = phoneNumber;
    newOption.textContent = `New User | ${phoneNumber}`;
    customersSelect.add(newOption);
    newOption.selected = true;
    data.phone = phoneNumber;
    console.log('Sender Phone Updated to New Phone:', data.phone);

    addPhoneModal.style.display = 'none';
    document.body.classList.remove('modal-open');
    addPhoneModal.querySelector('form').reset();
  });

  submitSelectGroupBtn.addEventListener('click', function() {
    const selectedGroup = groupSelectModal.value;
    if (!selectedGroup || selectedGroup === 'default') {
      alert("يرجى اختيار مجموعة."); 
      return;
    }
    data.groupId = selectedGroup;
    console.log('Selected Group ID:', data.groupId);

    selectGroupModal.style.display = 'none';
    document.body.classList.remove('modal-open');

    updateRelatedFields(selectedGroup);
  });

  function updateRelatedFields(groupId) {
    fetch('/get-phone-by-group', { 
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
      },
      body: JSON.stringify({ groupId: groupId })
    })
    .then(response => response.json())
    .then(dataResponse => {
      if (dataResponse.phone) {
        data.phone = dataResponse.phone.trim();
        console.log('Fetched Phone from Group:', data.phone);

        const matchingOption = Array.from(customersSelect.options).find(option => {
          const textParts = option.textContent.split('|');
          return textParts.length === 2 && textParts[1].trim() === data.phone;
        });

        if (matchingOption) {
          matchingOption.selected = true;
          console.log('Selected Existing Sender Phone based on Group:', data.phone);
        } else {
          const newOption = document.createElement('option');
          newOption.value = data.phone;
          newOption.textContent = `Group User | ${data.phone}`; 
          customersSelect.add(newOption);
          newOption.selected = true;
          console.log('Added and Selected Sender Phone based on Group:', data.phone);
        }
      } else {
        data.phone = '';
        customersSelect.selectedIndex = 0;
        console.log('No Sender Phone mapped for Group:', groupId);
        alert('هذه المجموعة لا تحتوي على هاتف مرسل مرتبط.'); 
      }
    })
    .catch(error => {
      console.error('Error fetching phone by group:', error);
    });
  }

  window.onclick = function(event) {
    document.querySelectorAll('.custom-modal').forEach(function(modal) {
      if (event.target == modal) {
        modal.style.display = "none";
        document.body.classList.remove('modal-open');
      }
    });
  }

  $(document).ready(function() {
    $("#table").DataTable({
      pagingType: "full_numbers",
      scrollX: true,
      autoWidth: false,
    });
  });

  const checkboxes = document.querySelectorAll('input[type="checkbox"]');
  checkboxes.forEach((checkbox) => {
    checkbox.addEventListener('change', function() {
      if (this.checked) {
        const row = this.closest('tr');
        const phoneCell = row.cells[2];
        if (phoneCell) {
          const phone = phoneCell.textContent.trim();
          data.toPhone = phone;
          console.log('Selected Phone from Table:', phone);
          checkboxes.forEach(cb => {
            if (cb !== this) cb.checked = false;
          });
        }
      }
    });
  });


});
</script>
</body>
</html> send the updated ar.json contianing that texts from the html