   <%- header %>
   <!-- pre-rendered navbar inserted -->
   <main class="dashboard-main">
     <%- navbar %>
     <!-- pre-rendered navbar inserted -->

<style>
  .notification-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }

  #audienceSelect{
    border: 1px solid grey;
    border-radius: 8px;
    padding: 10px;
  }
  .card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
    padding: 24px;
    margin-bottom: 24px;
  }

  .section-title {
    font-size: 18px;
    font-weight: 600;
    color: #374151;
    margin-bottom: 16px;
  }

  .radio-group {
    display: flex;
    gap: 24px;
    margin-bottom: 20px;
  }

  .radio-option {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
  }

  .radio-option input {
    width: 18px;
    height: 18px;
    cursor: pointer;
  }

  .dropdown-container {
    position: relative;
    margin-bottom: 20px;
  }

  .dropdown-button {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 16px;
    background: #f3f4f6;
    border: 1px solid #d1d5db;
    border-radius: 8px;
    width: 100%;
    cursor: pointer;
    transition: all 0.2s;
  }

  .dropdown-button:hover {
    background: #e5e7eb;
  }

  .dropdown-menu {
    position: absolute;
    top: 100%;
    left: 0;
    width: 100%;
    max-height: 300px;
    overflow-y: auto;
    background: white;
    border: 1px solid #d1d5db;
    border-radius: 8px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    z-index: 10;
    display: none;
    margin-top: 4px;
  }

  .dropdown-menu.show {
    display: block;
  }

  .search-box {
    padding: 5px;
    position: sticky;
    top: -16px;
    z-index: 999;
    background-color: #fff;
    border-bottom: 1px solid #e5e7eb;
  }

  .search-box input {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #d1d5db;
    border-radius: 6px;
  }

  .dropdown-list {
    padding: 0;
    margin: 0;
    list-style: none;
  }

  .dropdown-item {
    padding: 12px 16px;
    display: flex;
    align-items: center;
    gap: 12px;
    cursor: pointer;
    transition: background 0.2s;
  }

  .dropdown-item:hover {
    background: #f3f4f6;
  }

  .dropdown-item input {
    width: 18px;
    height: 18px;
    cursor: pointer;
  }

  .select-all {
    padding: 12px 16px;
    display: flex;
    position: sticky;
    bottom: -20px;
    align-items: center;
    background-color: #fff;
    gap: 8px;
    color: #3b82f6;
    font-weight: 500;
    cursor: pointer;
    border-top: 1px solid #e5e7eb;
  }

  .form-group {
    margin-bottom: 20px;
  }

  .form-label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: #374151;
  }

  .form-input {
    width: 100%;
    padding: 10px 12px;
    border: 1px solid #d1d5db;
    border-radius: 8px;
    transition: border 0.2s;
  }

  .form-input:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
  }

  .form-textarea {
    width: 100%;
    padding: 12px;
    border: 1px solid #d1d5db;
    border-radius: 8px;
    min-height: 120px;
    resize: vertical;
  }

  .form-textarea:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
  }

  .submit-btn {
    background: #3b82f6;
    color: white;
    padding: 12px 24px;
    border: none;
    border-radius: 8px;
    font-weight: 500;
    cursor: pointer;
    transition: background 0.2s;
  }

  .submit-btn:hover {
    background: #2563eb;
  }

  .submit-btn:disabled {
    background: #9ca3af;
    cursor: not-allowed;
  }

  .hidden {
    display: none;
  }

  .audience-actions {
    display: grid;
    gap: 12px;
    margin-bottom: 16px;
  }

  .create-audience-btn {
    background: #10b981;
    color: white;
    padding: 10px 16px;
    border-radius: 8px;
    font-weight: 500;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 8px;
  }

  .create-audience-btn:hover {
    background: #059669;
  }

  .audience-select {
    width: 100%;
    padding: 10px 12px;
    border: 1px solid #d1d5db;
    border-radius: 8px;
  }

  .info-text {
    font-size: 14px;
    color: #6b7280;
    margin-top: 4px;
  }

  .badge {
    display: inline-block;
    padding: 4px 8px;
    background: #e5e7eb;
    border-radius: 999px;
    font-size: 12px;
    margin-left: 8px;
  }

  .loading-spinner {
    display: inline-block;
    width: 16px;
    height: 16px;
    border: 2px solid rgba(255, 255, 255, 0.3);
    border-radius: 50%;
    border-top-color: white;
    animation: spin 1s ease-in-out infinite;
  }

  .dropdown-menu * {
    pointer-events: auto;
  }

  @keyframes spin {
    to {
      transform: rotate(360deg);
    }
  }
</style>

 

  <div class="container pt-20">
    <%- include('../../partials/utils/title.ejs', {title: "Send SMS Manager"}) %>

    <% 
      const breadcrumbs = [
        { label: "Dashboard", href: "/admin/dashboard", icon: "bi bi-house-door" },
        { label: "Send SMS" }
      ];
    %>
    <%- include('../../partials/utils/breadcrumb.ejs', { breadcrumbs }) %>

    <div class="li-n mt-4">
      <div class="bg-white shadow-md rounded-lg" style="padding: 20px;">
        <!-- Audience Info -->
        <div class="space-y-4">
          <h3 class="text-lg font-medium text-gray-700">SMS INFO</h3>
          <hr/>

          <div class="flex flex-wrap gap-4">
            <% if (user.group_id !== 6) { %>
            <label class="flex items-center space-x-2">
              <input type="radio" name="audience" value="driver" class="form-radio form-check-input text-blue-600 audience-toggle" checked />
              <span>Driver</span>
            </label>
            <% } %>
            <% if (user.group_id !== 5) { %>
            <label class="flex items-center space-x-2">
              <input type="radio" name="audience" value="user" class="form-radio form-check-input text-blue-600 audience-toggle" <%= user.group_id === 6 ? 'checked' : '' %> />
              <span>User</span>
            </label>
            <% } %>
          </div>

          <div class="flex flex-wrap gap-4">
            <label class="flex items-center space-x-2">
              <input type="radio" name="selection" value="manual" class="form-radio form-check-input text-blue-600 selection-toggle" checked />
              <span>Manual Selection</span>
            </label>
            <label class="flex items-center space-x-2">
              <input type="radio" name="selection" value="audience" class="form-radio form-check-input text-blue-600 selection-toggle" />
              <span>Audience</span>
            </label>
          </div>

          <!-- Manual Selection UI -->
          <div id="manual-selection">
            <!-- Driver Select -->
            <div id="driver-select">
              <div class="dropdown-container">
                <label class="form-label">Select Driver(s)</label>
                <button id="dropdownDriverButton" class="dropdown-button">
                  <span id="driverButtonText">Select driver</span>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                    <path d="M6 9l6 6 6-6" />
                  </svg>
                </button>

                <div id="dropdownDriver" class="dropdown-menu">
                  <div class="search-box">
                    <input type="text" id="driver-search" placeholder="Search driver...">
                  </div>
                  <ul class="dropdown-list" id="driver-list">
                    <li class="dropdown-item">
                      <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                      </div>
                    </li>
                  </ul>
                  <div class="select-all" id="select-all-drivers">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                      <path d="M6.5 9a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9ZM8 10H5a5.006 5.006 0 0 0-5 5v2a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1v-2a5.006 5.006 0 0 0-5-5Zm11-3h-6a1 1 0 1 0 0 2h6a1 1 0 1 0 0-2Z" />
                    </svg>
                    Select all
                  </div>
                </div>
              </div>
            </div>

            <!-- User Select -->
            <div id="user-select" class="hidden">
              <div class="dropdown-container">
                <label class="form-label">Select User(s)</label>
                <button id="dropdownUserButton" class="dropdown-button">
                  <span id="userButtonText">Select user</span>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                    <path d="M6 9l6 6 6-6" />
                  </svg>
                </button>

                <div id="dropdownUser" class="dropdown-menu">
                  <div class="search-box">
                    <input type="text" id="user-search" placeholder="Search user...">
                  </div>
                  <ul class="dropdown-list" id="user-list">
                    <li class="dropdown-item">
                      <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                      </div>
                    </li>
                  </ul>
                  <div class="select-all" id="select-all-users">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                      <path d="M6.5 9a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9ZM8 10H5a5.006 5.006 0 0 0-5 5v2a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1v-2a5.006 5.006 0 0 0-5-5Zm11-3h-6a1 1 0 1 0 0 2h6a1 1 0 1 0 0-2Z" />
                    </svg>
                    Select all
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Audience Selection UI -->
          <div id="audience-selection" class="hidden mt-4">
            <div class="audience-select-container">
              <label class="form-label fw-semibold">Select Audience</label>
              <div class="audience-actions">
                <!-- Create Audience Buttons -->
                <a id="createDriverAudienceBtn" href="/admin/driver-audience" class="px-6 py-[10px] bg-green-600 text-white rounded-lg shadow hover:bg-green-700 transition">
                  Create Driver Audience
                </a>
                <a id="createUserAudienceBtn" href="/admin/rider-audience" class="px-6 py-[10px] bg-green-600 text-white rounded-lg shadow hover:bg-green-700 transition hidden">
                  Create User Audience
                </a>

                <!-- Select2 Dropdown with Search -->
                <select id="audienceSelect" class="w-full">
                  <option value="">Select an audience...</option>
                </select>
              </div>
            </div>
          </div>
        </div>

        <!-- SMS Info -->
        <div class="space-y-4 mt-4">

          <form id="form">

            <div>
              <label class="block font-medium text-gray-700">Message</label>
              <textarea rows="4" id="sms-message" name="smsMessage" maxlength="160" class="w-full px-2  border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500" placeholder="Enter SMS message (max 160 characters)"></textarea>
              <div id="sms-counter" class="character-counter">0/160 characters</div>
            </div>
          </form>

        </div>

        <div class="pt-4" style="display: flex; justify-content: end;">
          <button type="button" id="sendSmsBtn" class="py-[10px] bg-blue-600 text-white rounded-lg shadow hover:bg-blue-700 transition">Send SMS</button>
        </div>
      </div>
    </div>
  </div>
</main>

<script>
  // Define form configuration
  const formConfig = {
    formId: "form",
    fields: [{
        name: "smsMessage",
        type: "text",
        required: true,
        messages: {
          required: "Message is required"
        }
      },

    ]
  };
</script>

<script src="/js/validator/validation.js"></script>


<script>
  const pathParts = window.location.pathname.split('/');
  const preselectedAudienceId = pathParts[pathParts.length - 1]; // Gets "23" from "/admin/sendNotification/23"

  document.addEventListener('DOMContentLoaded', function() {
    // Global state
    const state = {
      drivers: [],
      users: [],
      driverAudiences: [],
      userAudiences: [],
      selectedDrivers: [],
      selectedUsers: []
    };

    // Initialize the page
    init();

    async function init() {
      // Load initial data
      await fetchDrivers();
      await fetchUsers();
      await fetchDriverAudiences();
      await fetchUserAudiences();

      // Set up event listeners
      setupEventListeners();

      // Auto-select audience if preselectedAudienceId is in the URL
      if (preselectedAudienceId && !isNaN(preselectedAudienceId)) {
        // Try to find the audience in driver or user lists
        const matchedDriverAudience = state.driverAudiences.find(
          a => String(a.audience_id) === preselectedAudienceId
        );
        const matchedUserAudience = state.userAudiences.find(
          a => String(a.audience_id) === preselectedAudienceId
        );

        if (matchedDriverAudience || matchedUserAudience) {
          const audienceType = matchedDriverAudience ? 'driver' : 'user';
          
          // Set the audience type radio button
          document.querySelector(`input[name="audience"][value="${audienceType}"]`).checked = true;
          toggleAudienceType(audienceType);
          
          // Set selection to "audience"
          document.querySelector('input[name="selection"][value="audience"]').checked = true;
          toggleSelectionType('audience');
          
          // Wait for UI to update then select the audience
          setTimeout(() => {
            const audienceSelect = document.getElementById('audienceSelect');
            if (audienceSelect) {
              for (let i = 0; i < audienceSelect.options.length; i++) {
                if (audienceSelect.options[i].value === preselectedAudienceId) {
                  audienceSelect.selectedIndex = i;
                  break;
                }
              }
              showToast(`Preselected ${audienceType} audience loaded`, 'success');
            }
          }, 100);
        }
      } else {
        // Default based on user group_id
        const userGroupId = <%= user.group_id %>;
        
        if (userGroupId === 6) {
          // Corporate admin - default to user
          const userRadio = document.querySelector('input[name="audience"][value="user"]');
          if (userRadio) {
            userRadio.checked = true;
            toggleAudienceType('user');
          }
        } else {
          // Company admin or super admin - default to driver
          const driverRadio = document.querySelector('input[name="audience"][value="driver"]');
          if (driverRadio) {
            driverRadio.checked = true;
            toggleAudienceType('driver');
          }
        }
        
        document.querySelector('input[name="selection"][value="manual"]').checked = true;
        toggleSelectionType('manual');
      }
    }

    function toggleAudienceType(type) {
      if (type === 'driver') {
        document.getElementById('driver-select').classList.remove('hidden');
        document.getElementById('user-select').classList.add('hidden');
        document.getElementById('createDriverAudienceBtn').classList.remove('hidden');
        document.getElementById('createUserAudienceBtn').classList.add('hidden');
      } else {
        document.getElementById('driver-select').classList.add('hidden');
        document.getElementById('user-select').classList.remove('hidden');
        document.getElementById('createDriverAudienceBtn').classList.add('hidden');
        document.getElementById('createUserAudienceBtn').classList.remove('hidden');
      }
      updateAudienceSelect(type);
    }

    function toggleSelectionType(type) {
      if (type === 'manual') {
        document.getElementById('manual-selection').classList.remove('hidden');
        document.getElementById('audience-selection').classList.add('hidden');
        // Ensure correct dropdown is visible for manual selection
        const audienceType = document.querySelector('input[name="audience"]:checked')?.value || 'driver';
        toggleAudienceType(audienceType);
      } else {
        document.getElementById('manual-selection').classList.add('hidden');
        document.getElementById('audience-selection').classList.remove('hidden');
        const audienceType = document.querySelector('input[name="audience"]:checked')?.value || 'driver';
        updateAudienceSelect(audienceType);
      }
    }

    function updateAudienceSelect(audienceType) {
      const audienceSelect = document.getElementById('audienceSelect');
      audienceSelect.innerHTML = '<option value="">Select an audience...</option>';

      const audiences = audienceType === 'driver' ? state.driverAudiences : state.userAudiences;

      audiences.forEach(audience => {
        const option = document.createElement('option');
        option.value = audience.audience_id;
        option.textContent = audience.title;
        if (String(audience.audience_id) === preselectedAudienceId) {
          option.selected = true;
        }
        audienceSelect.appendChild(option);
      });
    }

    async function fetchDrivers() {
      try {
        const response = await fetch('/admin/active/driver/options?d_active=1&is_delete=0&is_phone=1');
        if (!response.ok) throw new Error('Failed to fetch drivers');
         drivers = await response.json();
                state.drivers = drivers.data;

        renderDriverList();
      } catch (error) {
        console.error('Error fetching drivers:', error);
        showToast('Failed to load drivers. Please try again.', 'error');
      }
    }

    async function fetchUsers() {
      try {
        const response = await fetch('/admin/all/passengers/options?active=1&is_delete=0&is_phone=1');
        if (!response.ok) throw new Error('Failed to fetch users');
                users = await response.json();

        state.users = users.data;
        renderUserList();
      } catch (error) {
        console.error('Error fetching users:', error);
        showToast('Failed to load users. Please try again.', 'error');
      }
    }

    async function fetchDriverAudiences() {
      try {
        const response = await fetch('/admin/getaudiences');
        if (!response.ok) throw new Error('Failed to fetch driver audiences');
        const data = await response.json();
        state.driverAudiences = data.driversAudience.filter(audience => !audience.is_delete);
      } catch (error) {
        console.error('Error fetching driver audiences:', error);
      }
    }

    async function fetchUserAudiences() {
      try {
        const response = await fetch('/admin/getaudiences');
        if (!response.ok) throw new Error('Failed to fetch user audiences');
        const data = await response.json();
        state.userAudiences = data.userAudience.filter(audience => !audience.is_delete);
      } catch (error) {
        console.error('Error fetching user audiences:', error);
      }
    }

    function renderDriverList() {
      const driverList = document.getElementById('driver-list');
      driverList.innerHTML = '';

      if (state.drivers.length === 0) {
        driverList.innerHTML = '<li class="dropdown-item">No drivers found</li>';
        return;
      }

      state.drivers.forEach(driver => {
        const li = document.createElement('li');
        li.className = 'dropdown-checkbox-item';
        li.innerHTML = `
          <input type="checkbox" id="driver-${driver.driver_id}" class="form-check-input" value="${driver.driver_id}" 
            ${state.selectedDrivers.includes(driver.driver_id) ? 'checked' : ''}>
          <label for="driver-${driver.driver_id}">
          ${driver.driver_id} - ${driver.d_name} (${driver.d_phone})
          </label>
        `;

        li.querySelector('input').addEventListener('change', function() {
          if (this.checked) {
            state.selectedDrivers.push(this.value);
          } else {
            state.selectedDrivers = state.selectedDrivers.filter(id => id !== this.value);
          }
          updateSelectedCount('driver');
        });

        driverList.appendChild(li);
      });

      updateSelectedCount('driver');
    }

    function renderUserList() {
      const userList = document.getElementById('user-list');
      userList.innerHTML = '';

      if (state.users.length === 0) {
        userList.innerHTML = '<li class="dropdown-item">No users found</li>';
        return;
      }

      state.users.forEach(user => {
        const li = document.createElement('li');
        li.className = 'dropdown-checkbox-item';
        li.innerHTML = `
          <input type="checkbox" id="user-${user.user_id}" class="form-check-input" value="${user.user_id}" 
            ${state.selectedUsers.includes(user.user_id) ? 'checked' : ''}>
          <label for="user-${user.user_id}">
           ${user.user_id} - ${user.u_name} (${user.u_phone})
          </label>
        `;

        li.querySelector('input').addEventListener('change', function() {
          if (this.checked) {
            state.selectedUsers.push(this.value);
          } else {
            state.selectedUsers = state.selectedUsers.filter(id => id !== this.value);
          }
          updateSelectedCount('user');
        });

        userList.appendChild(li);
      });

      updateSelectedCount('user');
    }

    function setupEventListeners() {
      // Toggle dropdown menus
      document.getElementById('dropdownDriverButton').addEventListener('click', function() {
        document.getElementById('dropdownDriver').classList.toggle('show');
      });

      document.getElementById('dropdownUserButton').addEventListener('click', function() {
        document.getElementById('dropdownUser').classList.toggle('show');
      });

      // Close dropdowns when clicking outside
      document.addEventListener('click', function(event) {
        if (!event.target.closest('.dropdown-container')) {
          document.getElementById('dropdownDriver').classList.remove('show');
          document.getElementById('dropdownUser').classList.remove('show');
        }
      });

      // Audience type toggle
      document.querySelectorAll('input[name="audience"]').forEach(radio => {
        radio.addEventListener('change', function() {
          toggleAudienceType(this.value);
        });
      });

      // Selection type toggle
      document.querySelectorAll('input[name="selection"]').forEach(radio => {
        radio.addEventListener('change', function() {
          toggleSelectionType(this.value);
        });
      });

      // Search functionality
      document.getElementById('driver-search').addEventListener('input', function() {
        filterList(this.value, 'driver');
      });

      document.getElementById('user-search').addEventListener('input', function() {
        filterList(this.value, 'user');
      });

      // SMS character counter
      document.getElementById('sms-message').addEventListener('input', function() {
        const length = this.value.length;
        const counter = document.getElementById('sms-counter');
        counter.textContent = `${length}/160 characters`;

        if (length > 160) {
          counter.classList.add('error');
          counter.classList.remove('warning');
        } else if (length > 140) {
          counter.classList.add('warning');
          counter.classList.remove('error');
        } else {
          counter.classList.remove('warning', 'error');
        }
      });

      // Select all functionality
      document.getElementById('select-all-drivers').addEventListener('click', function() {
        selectAll('driver');
      });

      document.getElementById('select-all-users').addEventListener('click', function() {
        selectAll('user');
      });

      // Form submission
      document.getElementById('sendSmsBtn').addEventListener('click', sendSms);
    }

    function filterList(searchTerm, type) {
      const list = type === 'driver' ?
        document.getElementById('driver-list') :
        document.getElementById('user-list');
      const items = list.querySelectorAll('.dropdown-checkbox-item');

      searchTerm = searchTerm.toLowerCase();

      items.forEach(item => {
        const text = item.textContent.toLowerCase();
        item.style.display = text.includes(searchTerm) ? 'flex' : 'none';
      });
    }

    function selectAll(type) {
      const checkboxes = type === 'driver' ?
        document.querySelectorAll('#driver-list input[type="checkbox"]') :
        document.querySelectorAll('#user-list input[type="checkbox"]');

      const allChecked = Array.from(checkboxes).every(checkbox => checkbox.checked);

      checkboxes.forEach(checkbox => {
        checkbox.checked = !allChecked;
        const event = new Event('change');
        checkbox.dispatchEvent(event);
      });
    }

    function updateSelectedCount(type) {
      const count = type === 'driver' ? state.selectedDrivers.length : state.selectedUsers.length;
      const buttonText = type === 'driver' ?
        document.getElementById('driverButtonText') :
        document.getElementById('userButtonText');

      buttonText.textContent = count > 0 ? `${count} selected` : `Select ${type}`;
    }

async function sendSms() {
  // Validate form
  const message = document.getElementById('sms-message').value.trim();

  if (!message) {
    showToast('SMS message is required', 'error');
    return;
  }

  if (message.length > 160) {
    showToast('SMS message cannot exceed 160 characters', 'error');
    return;
  }

  // Prepare SMS data
  const audienceType = document.querySelector('input[name="audience"]:checked').value;
  const selectionType = document.querySelector('input[name="selection"]:checked').value;

  const smsData = {
    userType: audienceType === 'driver' ? 'Drivers' : 'Users',
    message: message,
    selectionType
  };

  // Add recipients based on selection type
  if (selectionType === 'manual') {
    if (audienceType === 'driver') {
      if (state.selectedDrivers.length === 0) {
        showToast('Please select at least one driver', 'error');
        return;
      }
      smsData.default_drivers = state.selectedDrivers;
    } else {
      if (state.selectedUsers.length === 0) {
        showToast('Please select at least one user', 'error');
        return;
      }
      smsData.default_users = state.selectedUsers;
    }
  } else {
    // Audience selection - get audience ID and user IDs
    const audienceId = document.getElementById('audienceSelect').value;
    if (!audienceId) {
      showToast('Please select an audience', 'error');
      return;
    }

    // Get the selected audience
    const audiences = audienceType === 'driver' ? state.driverAudiences : state.userAudiences;
    const selectedAudience = audiences.find(aud => String(aud.audience_id) === audienceId);

    if (!selectedAudience) {
      showToast('Selected audience not found', 'error');
      return;
    }

    // Add audience ID to the request
    smsData.audience_id = audienceId;
    
    // Get user IDs from the audience - handle comma-separated string
    let userIds = [];
    
    if (selectedAudience.user_audi_id) {
      // Split comma-separated string into array
      userIds = selectedAudience.user_audi_id.split(',').map(id => id.trim()).filter(id => id !== '');
    }

    if (userIds.length === 0) {
      showToast('Selected audience has no users/drivers', 'error');
      return;
    }

    smsData.userids = userIds;
    
    // Also include the audience title for reference
    smsData.audience_title = selectedAudience.title;
  }

  console.log('Sending SMS data:', smsData); // For debugging

  // Disable button and show loading state
  const sendBtn = document.getElementById('sendSmsBtn');
  const originalText = sendBtn.textContent;
  sendBtn.disabled = true;
  sendBtn.innerHTML = '<span class="loading-spinner"></span> Sending...';

  try {
    const response = await fetch('/admin/sendsms', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest'
      },
      body: JSON.stringify(smsData)
    });

    const data = await response.json();

    if (response.ok) {
      showToast(data.message || 'SMS sent successfully', 'success');

      // Reset form
      document.getElementById('sms-message').value = '';
      document.getElementById('sms-counter').textContent = '0/160 characters';
      document.getElementById('sms-counter').classList.remove('warning', 'error');

      // Reset selections
      state.selectedDrivers = [];
      state.selectedUsers = [];
      renderDriverList();
      renderUserList();
    } else {
      showToast(data.message || data.error || 'Failed to send SMS', 'error');
    }
  } catch (error) {
    console.error('Error sending SMS:', error);
    showToast('An error occurred while sending the SMS', 'error');
  } finally {
    sendBtn.disabled = false;
    sendBtn.textContent = originalText;
  }
}
    function showToast(message, type = 'success') {
      Swal.fire({
        toast: true,
        position: 'top-end',
        icon: type,
        title: message,
        showConfirmButton: false,
        timer: 3000,
        timerProgressBar: true
      });
    }
  });
</script>

<%- footer %>