<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}" dir="{{ app()->getLocale() == 'ar' ? 'rtl' : 'ltr' }}">

<head>
  <meta name="csrf-token" content="{{ csrf_token() }}">

  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>{{ __('Sas Radius Pro Dashboard') }}</title>
  <link rel="stylesheet" href="{{ asset('css/style.css') }}" />
  <!-- Bootstrap -->
  <link rel="stylesheet" href="{{ asset('css/bootstrap.css') }}" />
  <script src="{{ asset('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" />
  <style>
    /* Your Custom CSS for Modals (Refer to the styles mentioned above) */
    .custom-modal {
      display: none;
      position: fixed;
      z-index: 1000;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: auto;
      background-color: rgba(0, 0, 0, 0.5);
    }

    .custom-modal-content {
      background-color: #fefefe;
      margin: 10% auto;
      padding: 20px;
      border: 1px solid #888;
      width: 80%;
      max-width: 500px;
      border-radius: 8px;
      position: relative;
      animation-name: animatetop;
      animation-duration: 0.4s;
    }

    @keyframes animatetop {
      from {
        opacity: 0;
        transform: translateY(-50px);
      }

      to {
        opacity: 1;
        transform: translateY(0);
      }
    }

    .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;
    }

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

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

    .btn-close {
      background-color: #6c757d;
      color: white;
    }
  </style>
  <!-- Font Awesome (Duplicate Link Removed) -->
</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 -->
          </div>
          <div class="logo_header">
            <img src="{{ asset('images/logo.png') }}" alt="{{ __('logo') }}" loading="lazy" />
          </div>
          <div class="input_search">
            <input type="text" placeholder="{{ __('Search...') }}" />
            <!-- Search Icon SVG -->
          </div>
        </div>
        <div class="right">
          @include('include.translation')
          <div class="notfication">
            <div class="head">
              <div class="icon">
                <!-- Notification Icon SVG -->
              </div>
            </div>
          </div>
          <div class="nav_item">
            <div class="head">
              <img
                class="img_profile"
                src="{{ asset('images/user-1.jpg') }}"
                alt="{{ __('user_profile') }}"
                loading="lazy" />
            </div>
            @include('include.profile')
          </div>
        </div>
      </div>

      <div class="message_settings">
        <div class="head">
          <h4>{{ __('Message Settings') }}</h4>
        </div>
        <div class="content">
          <form id="messageSettingsForm">
            <!-- Country Code Selection -->
            <div class="input_select">
              <label for="country_code">{{ __('Country Code') }}</label>
              <select name="country_code" id="country_code">
                <option value="egypt" {{ (isset($configData['country_code']) && $configData['country_code'] == 'egypt') ? 'selected' : '' }}>{{ __('Egypt') }}</option>
                <option value="libya" {{ (isset($configData['country_code']) && $configData['country_code'] == 'libya') ? 'selected' : '' }}>{{ __('Libya') }}</option>
                <option value="iraq" {{ (isset($configData['country_code']) && $configData['country_code'] == 'iraq') ? 'selected' : '' }}>{{ __('Iraq') }}</option>
                <option value="uae" {{ (isset($configData['country_code']) && $configData['country_code'] == 'uae') ? 'selected' : '' }}>{{ __('UAE') }}</option>
                <option value="saudi_arabia" {{ (isset($configData['country_code']) && $configData['country_code'] == 'saudi_arabia') ? 'selected' : '' }}>{{ __('Saudi Arabia') }}</option>
              </select>
            </div>

            <!-- Messaging Service Switch -->
            <div class="switch_section">
              <div class="form-check form-switch">
                <label class="form-check-label" for="message-services">{{ __('Messaging Service') }}</label>
                <input
                  id="message-services"
                  class="form-check-input"
                  type="checkbox"
                  role="switch"
                  data-num="1"
                  name="message-services"
                  {{ isset($configData['message-services']) && $configData['message-services'] ? 'checked' : '' }} />
              </div>
            </div>

            <!-- Message Settings Section 1 -->
            <div class="message_settings_section" data-num="1" style="{{ isset($configData['message-services']) && $configData['message-services'] ? '' : 'display:none;' }}">
              <!-- Additional keys info -->
              <!-- Content here -->
            </div>

            <!-- About to Expire Subscription Switch -->
            <div class="switch_section">
              <div class="form-check form-switch">
                <label class="form-check-label" for="messaging-service2">{{ __('About to Expire Subscription') }}</label>
                <input
                  class="form-check-input"
                  type="checkbox"
                  role="switch"
                  id="messaging-service2"
                  data-num="2"
                  name="messaging-service2"
                  {{ isset($configData['messaging-service2']) && $configData['messaging-service2'] ? 'checked' : '' }} />
              </div>
            </div>

            <!-- Message Settings Section 2 -->
            <div class="message_settings_section" data-num="2" style="{{ isset($configData['messaging-service2']) && $configData['messaging-service2'] ? '' : 'display:none;' }}">
              <div class="input_item">
                <label for="activation_message">{{ __('Activation Message') }}</label>
                <textarea name="activation_message" id="activation_message">{{ $configData['activation_message'] ?? '' }}</textarea>
              </div>
            </div>

            <!-- Upon Subscription Expiry Switch -->
            <div class="switch_section">
              <div class="form-check form-switch">
                <label class="form-check-label" for="messaging-service3">{{ __('Upon Subscription Expiry') }}</label>
                <input
                  class="form-check-input"
                  type="checkbox"
                  role="switch"
                  id="messaging-service3"
                  data-num="3"
                  name="messaging-service3"
                  {{ isset($configData['messaging-service3']) && $configData['messaging-service3'] ? 'checked' : '' }} />
              </div>
            </div>

            <!-- Message Settings Section 3 -->
            <div class="message_settings_section" data-num="3" style="{{ isset($configData['messaging-service3']) && $configData['messaging-service3'] ? '' : 'display:none;' }}">
              <div class="input_select">
                <label for="warning_before">{{ __('Warning Before') }}</label>
                <select name="warning_before" id="warning_before">
                  <option value="1" {{ (isset($configData['warning_before']) && $configData['warning_before'] == '1') ? 'selected' : '' }}>{{ __('1 day') }}</option>
                  <option value="2" {{ (isset($configData['warning_before']) && $configData['warning_before'] == '2') ? 'selected' : '' }}>{{ __('2 days') }}</option>
                  <option value="3" {{ (isset($configData['warning_before']) && $configData['warning_before'] == '3') ? 'selected' : '' }}>{{ __('3 days') }}</option>
                  <option value="4" {{ (isset($configData['warning_before']) && $configData['warning_before'] == '4') ? 'selected' : '' }}>{{ __('4 days') }}</option>
                  <option value="5" {{ (isset($configData['warning_before']) && $configData['warning_before'] == '5') ? 'selected' : '' }}>{{ __('5 days') }}</option>
                </select>
              </div>
              <div class="input_item">
                <label for="expiry_message">{{ __('Expiry Message') }}</label>
                <textarea name="expiry_message" id="expiry_message">{{ $configData['expiry_message'] ?? '' }}</textarea>
              </div>
            </div>

            <!-- Aggressive Messaging Switch -->
            <div class="switch_section">
              <div class="form-check form-switch">
                <label class="form-check-label" for="messaging-service4">{{ __('Aggressive Messaging') }}</label>
                <input
                  class="form-check-input"
                  type="checkbox"
                  role="switch"
                  id="messaging-service4"
                  data-num="4"
                  name="messaging-service4"
                  {{ isset($configData['messaging-service4']) && $configData['messaging-service4'] ? 'checked' : '' }} />
              </div>
            </div>

            <!-- Aggressive Messaging Alerts -->
            <div class="alert alert-info mt-3" style="{{ isset($configData['messaging-service4']) && $configData['messaging-service4'] ? '' : 'display:none;' }}">
              <strong>
                {{ __('Aggressive messaging is a type of messaging that allows you to send messages instantly at the moment an operation occurs. It allows you to use many options and provide more data for sending, in addition to the ability to select a phone of your choice to receive real-time operation data.') }}
              </strong>
            </div>
            <div class="alert alert-warning" style="{{ isset($configData['messaging-service4']) && $configData['messaging-service4'] ? '' : 'display:none;' }}">
              <strong>
                {{ __('Please note that this feature uses the SAS webhook. Therefore, if you activate it, it will replace the old settings. For example, monitoring functionality in SAS Pro or any application will send system operations data directly to WhatsApp instead.') }}
              </strong>
            </div>

            <!-- Message Settings Section 4 -->
            <div class="message_settings_section" data-num="4" style="{{ isset($configData['messaging-service4']) && $configData['messaging-service4'] ? '' : 'display:none;' }}">
              <div class="top">
                <div class="input_item" style="max-width: 300px; width: 100%">
                  <label for="personal_phone">{{ __('Personal Phone') }}</label>
                  <input type="number" id="personal_phone" name="personal_phone" value="{{ $configData['personal_phone'] ?? '' }}" />
                </div>

                <div class="container_input">
                  <div class="switch_section">
                    <div class="form-check form-switch">
                      <label class="form-check-label" for="messaging-service5">{{ __('Messaging Service') }}</label>
                      <input
                        class="form-check-input"
                        type="checkbox"
                        role="switch"
                        id="messaging-service5"
                        name="messaging-service5"
                        {{ isset($configData['messaging-service5']) && $configData['messaging-service5'] ? 'checked' : '' }} />
                    </div>
                  </div>
                  <small>
                    {{ __('When this option is activated, the connected personal phone will be used.') }}
                  </small>
                </div>
              </div>

              <!-- Switches within Aggressive Messaging -->
              <div class="switchs row">
                <!-- Left Column Switches -->
                <div class="col-12 col-md-6">
                  <!-- Switch 1 -->
                  <div class="switch_item">
                    <div class="form-check form-switch">
                      <label class="form-check-label" for="switch1">{{ __('Upon Subscription Activation') }}</label>
                      <input
                        class="form-check-input"
                        type="checkbox"
                        role="switch"
                        id="switch1"
                        name="switch1"
                        {{ isset($configData['switch1']) && $configData['switch1'] ? 'checked' : '' }} />
                    </div>
                  </div>
                  <!-- Add other switches similarly -->
                </div>

                <!-- Right Column Switches -->
                <div class="col-12 col-md-6">
                  <!-- Switch 7 -->
                  <div class="switch_item">
                    <div class="form-check form-switch">
                      <label class="form-check-label" for="switch7">{{ __('Upon Adding or Removing Consumption Capacities (GB) for Client') }}</label>
                      <input
                        class="form-check-input"
                        type="checkbox"
                        role="switch"
                        id="switch7"
                        name="switch7"
                        {{ isset($configData['switch7']) && $configData['switch7'] ? 'checked' : '' }} />
                    </div>
                  </div>
                  <!-- Add other switches similarly -->
                </div>
              </div>

              <!-- Additional Keys -->
              <div class="col-md-12 text-center my-2">
                <h6 class="alert alert-info text-center">
                  <strong>{{ __('Additional keys you can use') }}</strong>
                </h6>
                <!-- Keys List -->
              </div>

              <!-- Inputs and Textareas -->
              <div class="input_item">
                <label for="messagemenu">{{ __('Menu Message') }}</label>
                <input type="text" placeholder="" id="messagemenu" name="messagemenu" value="{{ $configData['messagemenu'] ?? '' }}" />
              </div>
              <div class="input_item">
                <label for="accountinformationdata">{{ __('Account Information Message') }}</label>
                <textarea name="account_information" id="accountinformationdata">{{ $configData['account_information'] ?? '' }}</textarea>
              </div>
            </div>

            <!-- Enable Account Balance Display Switch -->
            <div class="switch_section">
              <div class="form-check form-switch">
                <label class="form-check-label" for="messaging-service6">{{ __('Enable Account Balance Display') }}</label>
                <input
                  class="form-check-input"
                  type="checkbox"
                  role="switch"
                  id="messaging-service6"
                  data-num="6"
                  name="messaging-service6"
                  {{ isset($configData['messaging-service6']) && $configData['messaging-service6'] ? 'checked' : '' }} />
              </div>
            </div>

            <!-- Message Settings Section 6 -->
            <div class="message_settings_section" data-num="6" style="{{ isset($configData['messaging-service6']) && $configData['messaging-service6'] ? '' : 'display:none;' }}">
              <div class="row">
                <div class="col-12 col-md-6">
                  <div class="input_item">
                    <label for="messagemenu4">{{ __('Menu Message') }}</label>
                    <input type="text" placeholder="" id="messagemenu4" name="messagemenu4" value="{{ $configData['messagemenu4'] ?? '' }}" />
                  </div>
                </div>
                <div class="col-12 col-md-6">
                  <div class="input_item">
                    <label for="msgactvcardsucess">{{ __('Successful Card Activation Message') }}</label>
                    <textarea name="msgactvcardsucess" id="msgactvcardsucess">{{ $configData['msgactvcardsucess'] ?? '' }}</textarea>
                  </div>
                </div>
                <!-- Continue for other inputs and textareas -->
              </div>
            </div>

            <!-- Enable Card Charging Switch -->
            <div class="switch_section">
              <div class="form-check form-switch">
                <label class="form-check-label" for="messaging-service7">{{ __('Enable Card Charging') }}</label>
                <input
                  class="form-check-input"
                  type="checkbox"
                  role="switch"
                  id="messaging-service7"
                  data-num="7"
                  name="messaging-service7"
                  {{ isset($configData['messaging-service7']) && $configData['messaging-service7'] ? 'checked' : '' }} />
              </div>
            </div>

            <!-- Message Settings Section 7 -->
            <div class="message_settings_section" data-num="7" style="{{ isset($configData['messaging-service7']) && $configData['messaging-service7'] ? '' : 'display:none;' }}">
              <!-- Additional keys and inputs -->
            </div>

            <!-- Submit Button -->
            <div class="text-center mt-4">
              <button type="submit" class="btn btn-primary">{{ __('Save Settings') }}</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </main>

  <!-- Confirmation Modal -->
  <div id="confirmationModal" class="custom-modal">
    <div class="custom-modal-content">
      <span class="close">&times;</span>
      <h5>{{ __('Operation Confirmation') }}</h5>
      <p>{{ __('Settings have been saved successfully!') }}</p>
      <button class="btn btn-primary close-modal">{{ __('Confirm') }}</button>
    </div>
  </div>
  <!-- End Modal Add Group -->

  <script src="{{ asset('js/boxs-header.js') }}"></script>
  <script src="{{ asset('js/sidebar.js') }}"></script>
  <script src="{{ asset('js/nav-profile.js') }}"></script>
  <script>
    function collectFormData() {
      const formData = {};

      const addToFormData = (key, value) => {
        if (formData[key]) {
          if (!Array.isArray(formData[key])) {
            formData[key] = [formData[key]];
          }
          formData[key].push(value);
        } else {
          formData[key] = value;
        }
      };

      document.querySelectorAll('input, select, textarea').forEach(element => {
        const key = element.id || element.name;

        if (!key) return;

        switch (element.type) {
          case 'checkbox':
          case 'radio':
            if (element.checked) {
              addToFormData(key, element.value || 'on');
            }
            break;
          case 'select-one':
            addToFormData(key, element.value);
            break;
          case 'select-multiple':
            Array.from(element.selectedOptions).forEach(option => {
              addToFormData(key, option.value);
            });
            break;

          case 'textarea':
            addToFormData(key, element.value);
            break;
          default:
            addToFormData(key, element.value);
        }
      });

      return formData;
    }

    function sendFormData(url) {
      const formData = collectFormData();
      fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
          },
          body: JSON.stringify(formData),
        })
        .then(response => response.json())
        .then(data => {
          if (data.success) {
            showModal(confirmationModal);
            // Optionally, reset inputs or perform other actions
          } else {

          }
        })
        .catch((error) => {
          console.error('{{ __("Error:") }}', error);
        });
    }

    function debounce(func, delay) {
      let timeoutId;
      return function(...args) {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => func.apply(this, args), delay);
      };
    }

    const debouncedSendFormData = debounce(() => sendFormData('/api/data-sas'), 300);

    document.addEventListener('DOMContentLoaded', () => {
      document.querySelectorAll('input, select, textarea').forEach(element => {
        element.addEventListener('change', () => {
          console.log(collectFormData());
          debouncedSendFormData();
        });
        if (element.type !== 'checkbox' && element.type !== 'radio' && element.type !== 'file') {
          element.addEventListener('input', () => {
            console.log(collectFormData());
            debouncedSendFormData();
          });
        }
      });

      const switchesSections = document.querySelectorAll(".switch_section input[type='checkbox']");
      const messageSettingsSections = document.querySelectorAll(".message_settings_section");

      switchesSections.forEach((input, index) => {
        input.addEventListener("change", () => {
          const dataNum = input.getAttribute("data-num");
          const messageSection = document.querySelector(`.message_settings_section[data-num="${dataNum}"]`);
          if (messageSection) {
            messageSection.classList.toggle("active", input.checked);
          }
          console.log(collectFormData());
          debouncedSendFormData();
        });
      });

      const submitButton = document.getElementById('btnadd');
      const cancelButton = document.querySelector('.btn_close');

      // Modal Functionality
      const confirmationModal = document.getElementById('confirmationModal');
      const closeModalElements = confirmationModal.querySelectorAll('.close, .close-modal');

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

      function hideModal(modal) {
        modal.style.display = 'none';
        document.body.classList.remove('modal-open');
      }

      closeModalElements.forEach(element => {
        element.addEventListener('click', () => {
          hideModal(confirmationModal);
        });
      });

      window.addEventListener('click', function(event) {
        if (event.target == confirmationModal) {
          hideModal(confirmationModal);
        }
      });

      // Handle form submission
      submitButton.addEventListener('click', function(event) {
        event.preventDefault(); // Prevent default button behavior

        // Collect data from inputs
        const dataToSend = collectFormData();

        // Send data via fetch
        fetch('/bot-preferences', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            },
            body: JSON.stringify(dataToSend),
          })
          .then(response => response.json())
          .then(data => {
            if (data.success) {
              showModal(confirmationModal);
              // Optionally, reset inputs
              // document.getElementById('yourFormId').reset();
            } else {

            }
          })
          .catch(error => {
            console.error('{{ __("Error:") }}', error);
          });
      });

      cancelButton.addEventListener('click', function(event) {
        hideModal(confirmationModal);
      });
    });

    document.addEventListener('DOMContentLoaded', function() {
      const table = document.querySelector('table');
      const selectAllCheckbox = document.getElementById('selectAllcheckbox');
      const checkboxes = document.querySelectorAll('input[type="checkbox"].row-checkbox');
      const deleteButton = document.getElementById('deletebtn');

      const deleteConfirmationModal = document.getElementById('deleteConfirmationModal');
      const closeDeleteModalElements = deleteConfirmationModal ?
        deleteConfirmationModal.querySelectorAll('.close, #cancelDelete') : [];
      const confirmDeleteButton = document.getElementById('confirmDelete');

      // Translated Strings
      const alertSelectClients = "{{ __('Please select at least one client to delete.') }}";
      const alertDeleteSuccess = "{{ __('Selected clients have been successfully deleted.') }}";
      const alertDeleteError = "{{ __('Error deleting clients: ') }}";
      const alertUnknownError = "{{ __('An error occurred while deleting clients.') }}";

      let selectedPhones = new Set();

      function showModal(modal) {
        if (modal) {
          modal.style.display = 'block';
          document.body.classList.add('modal-open');
        } else {
          console.error('{{ __("Modal element not provided.") }}');
        }
      }

      function hideModal(modal) {
        if (modal) {
          modal.style.display = 'none';
          document.body.classList.remove('modal-open');
        } else {
          console.error('{{ __("Modal element not provided.") }}');
        }
      }

      function setupDeleteModal() {
        if (!deleteConfirmationModal) {
          console.error('{{ __("Element with ID \"deleteConfirmationModal\" not found.") }}');
          return;
        }

        closeDeleteModalElements.forEach(element => {
          element.addEventListener('click', () => hideModal(deleteConfirmationModal));
        });

        if (confirmDeleteButton) {
          confirmDeleteButton.addEventListener('click', () => {
            hideModal(deleteConfirmationModal);
            deleteSelectedRows();
          });
        } else {
          console.error('{{ __("Element with ID \"confirmDelete\" not found.") }}');
        }

        if (deleteButton) {
          deleteButton.addEventListener('click', function(event) {
            event.preventDefault();
            if (selectedPhones.size > 0) {
              showModal(deleteConfirmationModal);
            } else {}
          });
        } else {
          console.error('{{ __("Element with ID \"deletebtn\" not found.") }}');
        }
      }

      function deleteSelectedRows() {
        console.log('Phones to delete:', Array.from(selectedPhones));
        fetch('/deletecustomers', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            },
            body: JSON.stringify({
              phones: Array.from(selectedPhones)
            })
          })
          .then(response => response.json())
          .then(data => {
            if (data.success) {
              selectedPhones.forEach(phone => {
                const rows = document.querySelectorAll('tbody tr');
                for (let row of rows) {
                  if (row.cells[1] && row.cells[1].textContent.trim() === phone) {
                    row.remove();
                    break;
                  }
                }
              });
              selectedPhones.clear();
              if (deleteButton) deleteButton.disabled = true;
              checkboxes.forEach(checkbox => {
                checkbox.checked = false;
              });
            } else {}
          })
          .catch(error => {
            console.error('Error:', error);
            window.location.href = '/user-clients';
          });
      }

      function setupCheckboxes() {
        if (!selectAllCheckbox) {
          console.error('{{ __("Element with ID \"selectAllcheckbox\" not found.") }}');
          return;
        }

        if (!checkboxes.length) {
          console.error('{{ __("No checkboxes found.") }}');
          return;
        }

        selectAllCheckbox.addEventListener('change', function() {
          checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
            const row = checkbox.closest('tr');
            const phone = row.cells[3].textContent.trim(); // Phone is in cell index 3
            if (this.checked) {
              selectedPhones.add(phone);
            } else {
              selectedPhones.delete(phone);
            }
          });
          if (deleteButton) deleteButton.disabled = selectedPhones.size === 0;
        });

        checkboxes.forEach(checkbox => {
          checkbox.addEventListener('change', function() {
            const row = this.closest('tr');
            const phone = row.cells[3].textContent.trim(); // Phone is in cell index 3

            if (this.checked) {
              selectedPhones.add(phone);
            } else {
              selectedPhones.delete(phone);
            }
            deleteButton.disabled = selectedPhones.size === 0;
          });
        });
      }

      setupCheckboxes();
      setupDeleteModal();
      console.log(pdata);

      function sendreqprofile() {
        fetch('/handleprofilegroupdata', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            },
            body: JSON.stringify(pdata)
          })
          .then(response => response.json())
          .then(data => {
            console.log('{{ __("Profile data sent successfully:") }}', data);
          })
          .catch(error => {
            console.error('{{ __("Error sending profile data:") }}', error);
          });
      }

      const viewIdBtn = document.getElementById('aview');
      console.log('viewIdBtn:', viewIdBtn);
      if (viewIdBtn) {
        viewIdBtn.addEventListener('click', function() {
          console.log('Button clicked!');
          console.log(pdata);
          sendreqprofile();
        });
      } else {
        console.error('{{ __("Button with id \"aview\" not found.") }}');
      }

      function che() {
        const checkboxes = document.querySelectorAll('tbody input[type="checkbox"]');
        checkboxes.forEach(checkbox => {
          checkbox.addEventListener('change', function() {
            const row = this.closest('tr');
            const namee = row.cells[1].textContent.trim();
            const option = row.cells[2].textContent.trim();
            const phonenum = row.cells[3].textContent.trim();
            console.log(phonenum);
            const data = {
              'name': namee,
              'option': option,
              'phone': phonenum,
            };
            console.log(data);
            fetch('/viewclient', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
              },
              body: JSON.stringify(data)
            });
          });
        });
      }

      che();
    });

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

    let data = {
      choice: '{{ __("default") }}'
    };

    function sendDataToServer(choice) {
      fetch('/change-group', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
          },
          body: JSON.stringify({
            choice: choice
          })
        })
        .then(response => response.json())
        .then(result => {
          console.log('{{ __(key: "Success:") }}', result);
        })
        .catch(error => {
          console.error('{{ __("Error:") }}', error);
        });
    }

    document.getElementById('formGroup').addEventListener('submit', function(event) {
      event.preventDefault();
    });

    document.getElementById('group_select').addEventListener('change', function() {
      const selectedValue = this.value;

      switch (selectedValue) {
        case 'default':
          data.choice = '{{ __("No Group") }}';
          console.log("{{ __('Default selected') }}");
          break;
        case 'allclients':
          data.choice = '{{ __("All Clients") }}';
          break;
        default:
          data.choice = '{{ __("default") }}';
          console.log("{{ __('Unexpected value, setting to default') }}");
      }
      sendDataToServer(data.choice);
    });
  </script>

  <script>
    document.addEventListener('DOMContentLoaded', function() {
      // Local Storage Management for Inputs
      let textInputs = document.querySelectorAll('input[type="text"], textarea');
      let inputs = {};

      textInputs.forEach(input => {
        const idInput = input.getAttribute('id');

        if (idInput) {
          const savedValue = localStorage.getItem(idInput);
          if (savedValue) {
            input.value = savedValue;
            inputs[idInput] = savedValue;
          }

          input.addEventListener('input', function(event) {
            const value = event.target.value.trim();
            if (value !== "") {
              inputs[idInput] = value;
              localStorage.setItem(idInput, value);
            } else {
              delete inputs[idInput];
              localStorage.removeItem(idInput);
            }
            console.log(inputs);
          });
        }
      });

      // Switch Sections Management
      const switchesSections = document.querySelectorAll(".switch_section input[type='checkbox']");
      const messageSettingsSections = document.querySelectorAll(".message_settings_section");

      switchesSections.forEach((input, index) => {
        // Load saved state
        const savedState = localStorage.getItem(input.id);
        if (savedState === 'true') {
          input.checked = true;
          messageSettingsSections[index].style.display = 'block';
        } else {
          input.checked = false;
          messageSettingsSections[index].style.display = 'none';
        }

        input.addEventListener("change", () => {
          if (input.checked) {
            messageSettingsSections[index].style.display = 'block';
          } else {
            messageSettingsSections[index].style.display = 'none';
          }
          localStorage.setItem(input.id, input.checked);
        });
      });

      // Modal Functionality
      const confirmationModal = document.getElementById('confirmationModal');
      const closeModalElements = confirmationModal.querySelectorAll('.close, .close-modal');

      // Function to show modal
      function showModal(modal) {
        modal.style.display = 'block';
        document.body.classList.add('modal-open');
      }

      // Function to hide modal
      function hideModal(modal) {
        modal.style.display = 'none';
        document.body.classList.remove('modal-open');
      }

      // Event listeners for closing the modal
      closeModalElements.forEach(element => {
        element.addEventListener('click', () => {
          hideModal(confirmationModal);
        });
      });

      // Close the modal when clicking outside of the modal content
      window.addEventListener('click', function(event) {
        if (event.target == confirmationModal) {
          hideModal(confirmationModal);
        }
      });

      // Close modal on 'Esc' key press
      document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape' && confirmationModal.style.display === 'block') {
          hideModal(confirmationModal);
        }
      });

      // Handle form submission
      const submitButton = document.getElementById('btnadd');
      const cancelButton = document.querySelector('.btn_close');

      submitButton.addEventListener('click', function(event) {
        event.preventDefault(); // Prevent default button behavior

        // Collect data from inputs
        const dataToSend = collectFormData();

        // Send data via fetch
        sendFormData('/api/data-sas'); // The function already collects data internally
      });

      cancelButton.addEventListener('click', function(event) {
        hideModal(confirmationModal);
      });
    });
  </script>
</body>

</html> ident all this code and fix syntax error such as style="{{}}" it gives syntax error in php laravel } expected, etc  heres the bckend code   public function showsasbotconfig()
    {
        try {
            // Get the authenticated user's ID
            $userId = Auth::id();
    
            // Fetch the configuration data for the user
            $config = DB::table('sasmsgconfigs')
                ->where('idIdentity', $userId)
                ->first();
    
            // If no config is found, initialize an empty array or default values
            $configData = [];
            if ($config) {
                $configData = json_decode($config->config_data, true);
            }
    
            // Pass the data to the view
            return view('bot-saas', ['configData' => $configData]);
    
        } catch (\Exception $e) {
            Log::error("Error fetching configuration: " . $e->getMessage());
    
            // Optionally, you can redirect back with an error message
            return redirect()->back()->withErrors(['error' => 'An error occurred while fetching the configuration.']);
        }
    }