<!DOCTYPE html>
<html lang="en">
  <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="css/style.css" />
    <!-- Bootstrap -->
    <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"
    />
    <style>
      /* Include the modal CSS here as shown above */
      .custom-modal {
        display: none; /* Hidden by default */
        position: fixed;
        z-index: 1001; /* Higher than other elements */
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto; /* Enable scroll if needed */
        background-color: rgba(0, 0, 0, 0.5); /* Black with opacity */
      }

      .custom-modal-content {
        background-color: #fefefe;
        margin: 15% auto; /* 15% from the top and centered */
        padding: 20px;
        border: 1px solid #888;
        width: 40%; /* Adjust as needed */
        border-radius: 8px;
        position: relative;
      }

      .custom-modal-content .close {
        color: #aaa;
        position: absolute;
        top: 10px;
        right: 20px;
        font-size: 28px;
        font-weight: bold;
        cursor: pointer;
      }

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

      .custom-modal-content button {
        margin: 10px 5px 0 0;
      }

      /* Optional: Disable background scrolling when any modal is open */
      body.modal-open {
        overflow: hidden;
      }
    </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">
              <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..." />
              <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">
                  <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 general_information active" data-num="1">
            <div class="line">
              <div class="main_details">
                <div class="box_main_details">
                  <div class="image">
                    <img
                      src="./images/profile-img.jpeg"
                      alt=""
                      loading="lazy"
                    />
                  </div>
                  <!-- <h5 class="name">Rick James</h5>
                  <span class="position">Lead Designer / Developer</span> -->
                </div>
                <div class="box_btns_utils">
                  <div class="box">
                    <a id="delbtn" class="item btn_remove_user">
                      <i class="fa-solid fa-trash"></i>
                      <span> حذف</span>
                    </a>
                  </div>
                </div>
              </div>
              <div class="info_details">
                <div class="row">
                  <div class="col-12">
                    <div class="item">
                      <h6>القالب</h6>
                      <span id="ttname">{{$tname}}</span>
                    </div>
                    <div class="item">
                      <h6>الرساله</h6>
                      <span>{{$message}}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="section_profile update_infomation" data-num="2">
            <div class="general_information">
              <div class="head">
                <h4>اضافه عميل</h4> <!-- "Add Client" -->
              </div>
              <form action="">
                <div class="row">
                  <div class="col-12">
                    <div class="input_item">
                      <label for="">القالب</label>
                      <input id="tempname" type="text" placeholder="اكتب اي اسم" />
                    </div>

                    <div class="input_item">
                      <label for=""> الرسالة</label>
                      <textarea name="" id="msg"></textarea>
                    </div>
                  </div>
                </div>
              </form>
            </div>

            <div class="btns_add">
              <button id="add" class="btn_add">موافق</button> <!-- "Confirm" -->
              <button class="btn_close">الغاء</button> <!-- "Cancel" -->
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- Delete Confirmation Modal -->
    <div id="deleteConfirmationModal" class="custom-modal">
      <div class="custom-modal-content">
        <span class="close">&times;</span>
        <h5>تأكيد الحذف</h5> <!-- "Confirm Deletion" -->
        <p>هل أنت متأكد من حذف هذا القالب؟</p> <!-- "Are you sure you want to delete this template?" -->
        <button class="btn btn-primary" id="confirmDelete">موافق</button> <!-- "Confirm" -->
        <button class="btn btn-close" id="cancelDelete">الغاء</button> <!-- "Cancel" -->
      </div>
    </div>

    <!-- Edit Confirmation Modal -->
    <div id="editConfirmationModal" class="custom-modal">
      <div class="custom-modal-content">
        <span class="close">&times;</span>
        <h5>تأكيد التعديل</h5> <!-- "Confirm Edit" -->
        <p>هل أنت متأكد من حفظ التعديلات على هذا القالب؟</p> <!-- "Are you sure you want to save the changes to this template?" -->
        <button class="btn btn-primary" id="confirmEdit">موافق</button> <!-- "Confirm" -->
        <button class="btn btn-close" id="cancelEdit">الغاء</button> <!-- "Cancel" -->
      </div>
    </div>
    <!-- End of Modals -->

    <!-- Scripts -->
    <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>

    <!-- Updated JavaScript for Handling Delete and Edit Confirmations -->
    <script>
      document.addEventListener('DOMContentLoaded', function() {
        // Data object to hold template information
        let data = {};
        const mtname = document.getElementById('ttname').textContent;
        const btnsubmit = document.getElementById('add');
        const delbtn = document.getElementById('delbtn');
        const msgname = document.getElementById('tempname');
        const tmsg = document.getElementById('msg');

        // **Delete Confirmation Modal Elements**
        const deleteConfirmationModal = document.getElementById('deleteConfirmationModal');
        const closeDeleteModalElements = deleteConfirmationModal.querySelectorAll('.close, #cancelDelete');
        const confirmDeleteButton = document.getElementById('confirmDelete');

        // **Edit Confirmation Modal Elements**
        const editConfirmationModal = document.getElementById('editConfirmationModal');
        const closeEditModalElements = editConfirmationModal.querySelectorAll('.close, #cancelEdit');
        const confirmEditButton = document.getElementById('confirmEdit');

        /** 
         * Function to Show a Modal
         * @param {HTMLElement} modal - The modal element to display.
         */
        function showModal(modal) {
          modal.style.display = 'block';
          document.body.classList.add('modal-open');
        }

        /**
         * Function to Hide a Modal
         * @param {HTMLElement} modal - The modal element to hide.
         */
        function hideModal(modal) {
          modal.style.display = 'none';
          document.body.classList.remove('modal-open');
        }

        /** 
         * SETUP for Delete Confirmation Modal 
         */
        
        // Function to show the delete confirmation modal
        function showDeleteConfirmationModal() {
          showModal(deleteConfirmationModal);
        }

        // Function to hide the delete confirmation modal
        function hideDeleteConfirmationModal() {
          hideModal(deleteConfirmationModal);
        }

        // Attach event listeners to close buttons in the delete modal
        closeDeleteModalElements.forEach(element => {
          element.addEventListener('click', hideDeleteConfirmationModal);
        });

        // Event listener for "Confirm Delete" button in the delete modal
        confirmDeleteButton.addEventListener('click', () => {
          hideDeleteConfirmationModal();
          performDelete(); // Proceed with deletion
        });

        // Modify the delete button to show the modal instead of immediate deletion
        delbtn.addEventListener('click', function(event){
          event.preventDefault(); // Prevent default action if it's a link
          showDeleteConfirmationModal();
        });

        // Function to perform the deletion
        function performDelete() {
          const deld = { 'name': mtname };

          fetch('/del-temp-message', {
            method: 'POST',
            headers: { 
              'Content-Type': 'application/json',
              'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            },
            body: JSON.stringify(deld)
          })
          .then(response => response.json())
          .then(responseData => {
            if (responseData.success) { // Ensure your backend returns a success status
              alert('تم حذف القالب بنجاح.'); // "Template has been successfully deleted."
              window.location.href = '/temp-messages'; // Redirect after deletion
            } else {
              console.error('Deletion Error:', responseData.error);
              alert('حدث خطأ أثناء حذف القالب. يرجى المحاولة مرة أخرى.'); // "An error occurred while deleting the template. Please try again."
            }
          })
          .catch(error => {
            console.error('Fetch Error:', error);
            alert('حدث خطأ أثناء حذف القالب. يرجى المحاولة مرة أخرى.'); // "An error occurred while deleting the template. Please try again."
          });
        }

        /** 
         * SETUP for Edit Confirmation Modal 
         */

        // Function to show the edit confirmation modal
        function showEditConfirmationModal() {
          showModal(editConfirmationModal);
        }

        // Function to hide the edit confirmation modal
        function hideEditConfirmationModal() {
          hideModal(editConfirmationModal);
        }

        // Attach event listeners to close buttons in the edit modal
        closeEditModalElements.forEach(element => {
          element.addEventListener('click', hideEditConfirmationModal);
        });

        // Event listener for "Confirm Edit" button in the edit modal
        confirmEditButton.addEventListener('click', () => {
          hideEditConfirmationModal();
          performEdit(); // Proceed with editing
        });

        // Modify the submit (add) button to show the edit confirmation modal instead of immediate submission
        btnsubmit.addEventListener('click', function(event){
          event.preventDefault(); // Prevent default form submission
          showEditConfirmationModal();
        });

        // Function to perform the edit
        function performEdit() {
          // Prepare the data to be sent
          data.name = mtname;
          data.y = msgname.value.trim();
          data.s = tmsg.value.trim();

          fetch('/edit-template-messages', { // Ensure there's no space at the end of the URL
            method: 'POST',
            headers: { 
              'Content-Type': 'application/json',
              'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            },
            body: JSON.stringify(data)
          })
          .then(response => response.json())
          .then(responseData => {
            if(responseData.success){
              alert('تم تعديل القالب بنجاح.'); // "Template has been successfully updated."
              window.location.href = "/temp-messages"; // Redirect after successful edit
            } else {
              console.error('Edit Error:', responseData.error);
              alert('حدث خطأ أثناء تعديل القالب. يرجى المحاولة مرة أخرى.'); // "An error occurred while editing the template. Please try again."
            }
          })
          .catch(error => {
            console.error('Fetch Error:', error);
            alert('حدث خطأ أثناء تعديل القالب. يرجى المحاولة مرة أخرى.'); // "An error occurred while editing the template. Please try again."
          });
        }

        // Initialize DataTable if needed
        $("#table").DataTable({
          pagingType: "full_numbers",
          scrollX: true,
          autoWidth: false,
        });
      });
    </script>
  </body>
</html> make the popup functionality for edit and delete to this code from this code <!DOCTYPE html>
<html lang="en">
  <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="css/style.css" />
    <!-- Bootstrap -->
    <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"
    />
    <style>
      /* Include the modal CSS here as shown above */
      .custom-modal {
        display: none; /* Hidden by default */
        position: fixed;
        z-index: 1001; /* Higher than other elements */
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto; /* Enable scroll if needed */
        background-color: rgba(0, 0, 0, 0.5); /* Black with opacity */
      }

      .custom-modal-content {
        background-color: #fefefe;
        margin: 15% auto; /* 15% from the top and centered */
        padding: 20px;
        border: 1px solid #888;
        width: 40%; /* Adjust as needed */
        border-radius: 8px;
        position: relative;
      }

      .custom-modal-content .close {
        color: #aaa;
        position: absolute;
        top: 10px;
        right: 20px;
        font-size: 28px;
        font-weight: bold;
        cursor: pointer;
      }

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

      .custom-modal-content button {
        margin: 10px 5px 0 0;
      }

      /* Optional: Disable background scrolling when any modal is open */
      body.modal-open {
        overflow: hidden;
      }
    </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">
              <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..." />
              <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">
                  <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 general_information active" data-num="1">
            <div class="line">
              <div class="main_details">
                <div class="box_main_details">
                  <div class="image">
                    <img
                      src="./images/profile-img.jpeg"
                      alt=""
                      loading="lazy"
                    />
                  </div>
                  <!-- <h5 class="name">Rick James</h5>
                  <span class="position">Lead Designer / Developer</span> -->
                </div>
                <div class="box_btns_utils">
                  <div class="box">
                    <a id="delbtn" class="item btn_remove_user">
                      <i class="fa-solid fa-trash"></i>
                      <span> حذف</span>
                    </a>
                  </div>
                </div>
              </div>
              <div class="info_details">
                <div class="row">
                  <div class="col-12">
                    <div class="item">
                      <h6>القالب</h6>
                      <span id="ttname">{{$tname}}</span>
                    </div>
                    <div class="item">
                      <h6>الرساله</h6>
                      <span>{{$message}}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="section_profile update_infomation" data-num="2">
            <div class="general_information">
              <div class="head">
                <h4>اضافه عميل</h4> <!-- "Add Client" -->
              </div>
              <form action="">
                <div class="row">
                  <div class="col-12">
                    <div class="input_item">
                      <label for="">القالب</label>
                      <input id="tempname" type="text" placeholder="اكتب اي اسم" />
                    </div>

                    <div class="input_item">
                      <label for=""> الرسالة</label>
                      <textarea name="" id="msg"></textarea>
                    </div>
                  </div>
                </div>
              </form>
            </div>

            <div class="btns_add">
              <button id="add" class="btn_add">موافق</button> <!-- "Confirm" -->
              <button class="btn_close">الغاء</button> <!-- "Cancel" -->
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- Delete Confirmation Modal -->
    <div id="deleteConfirmationModal" class="custom-modal">
      <div class="custom-modal-content">
        <span class="close">&times;</span>
        <h5>تأكيد الحذف</h5> <!-- "Confirm Deletion" -->
        <p>هل أنت متأكد من حذف هذا القالب؟</p> <!-- "Are you sure you want to delete this template?" -->
        <button class="btn btn-primary" id="confirmDelete">موافق</button> <!-- "Confirm" -->
        <button class="btn btn-close" id="cancelDelete">الغاء</button> <!-- "Cancel" -->
      </div>
    </div>

    <!-- Edit Confirmation Modal -->
    <div id="editConfirmationModal" class="custom-modal">
      <div class="custom-modal-content">
        <span class="close">&times;</span>
        <h5>تأكيد التعديل</h5> <!-- "Confirm Edit" -->
        <p>هل أنت متأكد من حفظ التعديلات على هذا القالب؟</p> <!-- "Are you sure you want to save the changes to this template?" -->
        <button class="btn btn-primary" id="confirmEdit">موافق</button> <!-- "Confirm" -->
        <button class="btn btn-close" id="cancelEdit">الغاء</button> <!-- "Cancel" -->
      </div>
    </div>
    <!-- End of Modals -->

    <!-- Scripts -->
    <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>

    <!-- Updated JavaScript for Handling Delete and Edit Confirmations -->
    <script>
      document.addEventListener('DOMContentLoaded', function() {
        // Data object to hold template information
        let data = {};
        const mtname = document.getElementById('ttname').textContent;
        const btnsubmit = document.getElementById('add');
        const delbtn = document.getElementById('delbtn');
        const msgname = document.getElementById('tempname');
        const tmsg = document.getElementById('msg');

        // **Delete Confirmation Modal Elements**
        const deleteConfirmationModal = document.getElementById('deleteConfirmationModal');
        const closeDeleteModalElements = deleteConfirmationModal.querySelectorAll('.close, #cancelDelete');
        const confirmDeleteButton = document.getElementById('confirmDelete');

        // **Edit Confirmation Modal Elements**
        const editConfirmationModal = document.getElementById('editConfirmationModal');
        const closeEditModalElements = editConfirmationModal.querySelectorAll('.close, #cancelEdit');
        const confirmEditButton = document.getElementById('confirmEdit');

        /** 
         * Function to Show a Modal
         * @param {HTMLElement} modal - The modal element to display.
         */
        function showModal(modal) {
          modal.style.display = 'block';
          document.body.classList.add('modal-open');
        }

        /**
         * Function to Hide a Modal
         * @param {HTMLElement} modal - The modal element to hide.
         */
        function hideModal(modal) {
          modal.style.display = 'none';
          document.body.classList.remove('modal-open');
        }

        /** 
         * SETUP for Delete Confirmation Modal 
         */
        
        // Function to show the delete confirmation modal
        function showDeleteConfirmationModal() {
          showModal(deleteConfirmationModal);
        }

        // Function to hide the delete confirmation modal
        function hideDeleteConfirmationModal() {
          hideModal(deleteConfirmationModal);
        }

        // Attach event listeners to close buttons in the delete modal
        closeDeleteModalElements.forEach(element => {
          element.addEventListener('click', hideDeleteConfirmationModal);
        });

        // Event listener for "Confirm Delete" button in the delete modal
        confirmDeleteButton.addEventListener('click', () => {
          hideDeleteConfirmationModal();
          performDelete(); // Proceed with deletion
        });

        // Modify the delete button to show the modal instead of immediate deletion
        delbtn.addEventListener('click', function(event){
          event.preventDefault(); // Prevent default action if it's a link
          showDeleteConfirmationModal();
        });

        // Function to perform the deletion
        function performDelete() {
          const deld = { 'name': mtname };

          fetch('/del-temp-message', {
            method: 'POST',
            headers: { 
              'Content-Type': 'application/json',
              'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            },
            body: JSON.stringify(deld)
          })
          .then(response => response.json())
          .then(responseData => {
            if (responseData.success) { // Ensure your backend returns a success status
              alert('تم حذف القالب بنجاح.'); // "Template has been successfully deleted."
              window.location.href = '/temp-messages'; // Redirect after deletion
            } else {
              console.error('Deletion Error:', responseData.error);
              alert('حدث خطأ أثناء حذف القالب. يرجى المحاولة مرة أخرى.'); // "An error occurred while deleting the template. Please try again."
            }
          })
          .catch(error => {
            console.error('Fetch Error:', error);
            alert('حدث خطأ أثناء حذف القالب. يرجى المحاولة مرة أخرى.'); // "An error occurred while deleting the template. Please try again."
          });
        }

        /** 
         * SETUP for Edit Confirmation Modal 
         */

        // Function to show the edit confirmation modal
        function showEditConfirmationModal() {
          showModal(editConfirmationModal);
        }

        // Function to hide the edit confirmation modal
        function hideEditConfirmationModal() {
          hideModal(editConfirmationModal);
        }

        // Attach event listeners to close buttons in the edit modal
        closeEditModalElements.forEach(element => {
          element.addEventListener('click', hideEditConfirmationModal);
        });

        // Event listener for "Confirm Edit" button in the edit modal
        confirmEditButton.addEventListener('click', () => {
          hideEditConfirmationModal();
          performEdit(); // Proceed with editing
        });

        // Modify the submit (add) button to show the edit confirmation modal instead of immediate submission
        btnsubmit.addEventListener('click', function(event){
          event.preventDefault(); // Prevent default form submission
          showEditConfirmationModal();
        });

        // Function to perform the edit
        function performEdit() {
          // Prepare the data to be sent
          data.name = mtname;
          data.y = msgname.value.trim();
          data.s = tmsg.value.trim();

          fetch('/edit-template-messages', { // Ensure there's no space at the end of the URL
            method: 'POST',
            headers: { 
              'Content-Type': 'application/json',
              'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            },
            body: JSON.stringify(data)
          })
          .then(response => response.json())
          .then(responseData => {
            if(responseData.success){
              alert('تم تعديل القالب بنجاح.'); // "Template has been successfully updated."
              window.location.href = "/temp-messages"; // Redirect after successful edit
            } else {
              console.error('Edit Error:', responseData.error);
              alert('حدث خطأ أثناء تعديل القالب. يرجى المحاولة مرة أخرى.'); // "An error occurred while editing the template. Please try again."
            }
          })
          .catch(error => {
            console.error('Fetch Error:', error);
            alert('حدث خطأ أثناء تعديل القالب. يرجى المحاولة مرة أخرى.'); // "An error occurred while editing the template. Please try again."
          });
        }

        // Initialize DataTable if needed
        $("#table").DataTable({
          pagingType: "full_numbers",
          scrollX: true,
          autoWidth: false,
        });
      });
    </script>
  </body>
</html>