<!DOCTYPE html>
<html lang="en">
<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>الرئيسيه</span> /
            <span>العملاء</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>جهه الاتصال</span>
              </div>
              <div class="item" data-num="2">
                <i class="fa-regular fa-pen-to-square"></i>
                <span>ارسل رساله</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>رقم الهاتف</h5>
                        <span> اختر رقم هاتف محدد لارسال الرسالة</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">رقم الهاتف</label>
                            <input type="number" id="phoneNum" placeholder="أدخل رقم الهاتف هنا"/>
                          </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>ادخل الجلسه</h5>
                          <span> اختر جلسه محددة لارسال الرسائل منها</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">الجلسات</label>
                            <select name="" id="customersId">
                              @foreach($sessions as $session ) 
                                <option value="{{ $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>المجموعة</h5>
                        <span> اختر مجموعة ليتم استخدامها كجهة ارسال</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">
                          الهاتف الاساسى فقط
                        </div>
                        <div class="input_item">
                          <label for="group_select">المجموعه</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">ادخل الرسالة المراد استخدامها</label>
                <textarea name="" id="ae" placeholder="أدخل رسالتك هنا"></textarea>
              </div>
              <div class="input_file">
                <label for="file-image">
                  <span>ارفاق صوره</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">موافق</button>
                <button class="btn_close btn btn-secondary" type="button">الغاء</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">اضافه هاتف</h5>
        <form onsubmit="return false;">
          <div class="input_item">
            <label for="phonenum">رقم الهاتف</label>
            <input type="number" id="phonenum" placeholder="أدخل رقم الهاتف هنا"/>
          </div>
          <button id="submitAddPhoneBtn" class="btn btn-primary" type="button">موافق</button>
          <button class="btn btn-close-modal" type="button">الغاء</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">المجموعات</h5>
        <form onsubmit="return false;">
          <div class="input_item">
            <label for="group_select_modal">اختر مجموعه</label>
            <select name="" id="group_select_modal">
              <option value="default"></option>
              <option value="allclients">كل العملاء</option>
              @foreach($datas as $data ) 
                <option value="{{ $data->id }}">{{ $data->name }}</option>
              @endforeach
            </select>
          </div>
          <button id="submitSelectGroupBtn" class="btn btn-primary" type="button">موافق</button>
          <button class="btn btn-close-modal" type="button">الغاء</button>
        </form>
      </div>
    </div>

    <!-- Modal for Confirmation (similar to the second code) -->
    <div id="confirmationModal" class="custom-modal">
      <div class="custom-modal-content">
        <span class="close">&times;</span>
        <h5>تأكيد العملية</h5>
        <p>هل أنت متأكد من إرسال الرسالة؟</p>
        <button class="btn btn-primary" id="confirmSendMessage">موافق</button>
        <button class="btn btn-close-modal" id="cancelSendMessage">الغاء</button>
      </div>
    </div>

    <!-- 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() {
        // Data object to hold form data
        var data = {
          toPhone: '',    // Recipient's phone number (from phoneNum input)
          phone: '',      // Sender's phone number (from customersId select)
          msg: '',        // Message content
          groupId: '',    // Selected group ID
        };

        // Handle Send Message Form Submission
        const sendMessageBtn = document.getElementById('submitSendMessageBtn');
        const confirmationModal = document.getElementById('confirmationModal');
        const closeModals = document.querySelectorAll('.custom-modal .close, .btn-close-modal');

        sendMessageBtn.addEventListener('click', function() {
          if (!data.toPhone || !data.msg || !data.phone) { // Ensure all required fields are filled
            alert("يرجى ملء جميع الحقول المطلوبة.");
            return;
          }
          // Show the confirmation modal
          confirmationModal.style.display = 'block';
          document.body.classList.add('modal-open');
        });

        // Close all modals when close button or cancel button is clicked
        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');
          });
        });

        // Handle Confirm Send Message
        const confirmSendMessageBtn = document.getElementById('confirmSendMessage');

        confirmSendMessageBtn.addEventListener('click', function() {
          confirmationModal.style.display = 'none';
          document.body.classList.remove('modal-open');
          sendMessage();
        });

        function sendMessage() {
          var sendmsg = {
            'toPhone': data.toPhone, // Recipient's phone number
            'phone': data.phone,     // Sender's phone number
            'msg': data.msg,
            'groupId': data.groupId
          };
          
          console.log('Sending Message:', sendmsg); // Debugging line

          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('تم ارسال الرسالة بنجاح.');

              // Proceed with post-data-message-grp fetch
              return 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)
              });
            } else {
              console.error('SendMessageGroup Error:', body);
              const errorMessage = body.message || 'حدث خطأ غير متوقع.';
              const errorDetails = body.error ? JSON.stringify(body.error) : '';
              alert(`فشل في ارسال الرسالة. ${errorMessage} ${errorDetails}`);
              throw new Error('SendMessageGroup failed');
            }
          })
          .then(response => response.json())
          .then(responseData => {
            console.log('Post-data-message-grp Success:', responseData);
            alert('تم تحديث الرسائل بنجاح.');
          })
          .catch(error => {
            console.error('Error:', error);
            alert('حدث خطأ أثناء ارسال الرسالة.');
          });
        }

        // Handle input changes
        const phonenumInput = document.getElementById('phoneNum'); // Upper input for toPhone
        const msgInput = document.getElementById('ae');
        const groupSelect = document.getElementById('group_select_modal');

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

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

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

        // Handle select change for sender's phone
        const customersSelect = document.getElementById('customersId');
        customersSelect.addEventListener('change', function() {
          const selectedOption = this.options[this.selectedIndex];
          data.phone = selectedOption.value.trim(); // Sender's phone number from dropdown
          console.log('Sender Phone:', data.phone);
        });

        // Handle modal buttons for Adding Phone
        const addPhoneModal = document.getElementById('addPhoneModal');
        const submitAddPhoneBtn = document.getElementById('submitAddPhoneBtn');

        submitAddPhoneBtn.addEventListener('click', function() {
          const phoneNumber = document.getElementById('phonenum').value.trim();
          if (!phoneNumber) {
            alert("يرجى إدخال رقم الهاتف.");
            return;
          }
          // Implement AJAX request to add phone if necessary
          console.log('Adding Phone Number:', phoneNumber);
          // Close the modal
          addPhoneModal.style.display = 'none';
          document.body.classList.remove('modal-open');
          // Optionally reset the form
          addPhoneModal.querySelector('form').reset();
        });

        // Handle modal buttons for Selecting Group
        const selectGroupModal = document.getElementById('selectGroupModal');
        const submitSelectGroupBtn = document.getElementById('submitSelectGroupBtn');

        submitSelectGroupBtn.addEventListener('click', function() {
          const selectedGroup = document.getElementById('group_select_modal').value;
          if (!selectedGroup || selectedGroup === 'default') {
            alert("يرجى اختيار مجموعة.");
            return;
          }
          // Implement AJAX request to select group if necessary
          console.log('Selected Group ID:', selectedGroup);
          // Close the modal
          selectGroupModal.style.display = 'none';
          document.body.classList.remove('modal-open');
        });

        // Prevent interaction with background when modal is open
        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');
            }
          });
        }

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

        // Additional functionality for checkboxes if needed
        const checkboxes = document.querySelectorAll('input[type="checkbox"]');
        checkboxes.forEach((checkbox) => {
          checkbox.addEventListener('change', function() {
            if (this.checked) {
              const row = this.closest('tr');
              // Ensure your table has at least 3 columns
              const phoneCell = row.cells[2]; // Adjust index as per your table's column
              if (phoneCell) {
                const phone = phoneCell.textContent.trim();
                data.toPhone = phone;
                console.log('Selected Phone from Table:', phone);
                // Optionally, uncheck other checkboxes if only one selection is allowed
                checkboxes.forEach(cb => {
                  if (cb !== this) cb.checked = false;
                });
              }
            }
          });
        });
      });
    </script>
</body>
</html> make it get the second option or second input be updated every selected option per selection and make it work before sending request