<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Session</title>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" />
    <link rel="stylesheet" href="{{ asset('css/spinner.css') }}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="css/style.css" />
    <link rel="stylesheet" href="css/bootstrap.css" />
    <style>
        /* نماذج المودال */
        .custom-modal {
            display: none; /* مخفي بشكل افتراضي */
            position: fixed;
            z-index: 1001; /* أعلى من العناصر الأخرى */
            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: 15% auto; /* 15% من الأعلى وموضوعة في المنتصف */
            padding: 20px;
            border: 1px solid #888;
            width: 40%; /* تعديل الحجم حسب الحاجة */
            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;
        }

        /* تعطيل التمرير الخلفي عند فتح المودال */
        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="main_content_tables">
                @if (session('error'))
                    <div class="alert alert-danger" role="alert">
                        {{ __(session('error')) }}
                    </div>
                @endif
                @if (session('success'))
                    <div class="alert alert-success" role="alert">
                        {{ __(session('success')) }}
                    </div>
                @endif

                <div class="conetnt_table">
                    <div class="path">
                        <span>الرئيسيه</span> / <span>الجلسات</span>
                    </div>

                    <div class="head_table">
                        <div class="info">
                            <p class="text_details">
                                <i class="fa-solid fa-people-group"></i>
                                قائمة الجلسات | عثر على {{ count($sessions) }} قيد
                            </p>
                        </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"></path>
                            </svg>
                        </div>

                        <div class="utils">
                            <div class="actions_box">
                                <button class="btn_actions">
                                    <i class="fa-solid fa-wrench"></i>
                                    العمليات
                                </button>

                                <div class="box box_utils">
                                    <div class="item btn_open_model" data-model="1">
                                        <i class="fa-solid fa-plus"></i>
                                        <span>{{ __('Add') }}</span>
                                    </div>
                                    <div class="item btn_open_model" data-model="2">
                                        <button type="button" onclick="runInterval2();">
                                            <i class="fa-solid fa-plug"></i>
                                            <span>{{ __('connect') }}</span>
                                        </button>
                                    </div>
                                    <div class="item">
                                        <button class="actions" id="discsession">
                                            <i class="fa-solid fa-eye"></i>
                                            <span>{{ __('disconnect') }}</span>
                                        </button>
                                    </div>
                                    <div class="item">
                                        <a href="#" id="delbtn" class="actions">
                                            <i class="fa-solid fa-trash"></i>
                                            <span>{{ __('delete') }}</span>
                                        </a>
                                    </div>
                                    <div class="item">
                                        <i class="fa-solid fa-envelope"></i>
                                        <span>تغير الاسم</span>
                                    </div>
                                </div>
                            </div>
                            <div class="reload">
                                <button class="btn_utils">
                                    <i class="fa-solid fa-repeat"></i>
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="container_table">
                        <table id="table" class="display" style="width: 100%">
                            <thead>
                                <tr>
                                    <th>
                                        <input id="selectAllCheckbox" type="checkbox" />
                                    </th>
                                    <th>اسم الجروب</th>
                                    <th>الهاتف</th>
                                    <th>الحاله</th>
                                    <th>تاريخ الانشاء</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach ($sessions as $session)
                                <tr>
                                    <td>
                                        <input type="checkbox" class="row-checkbox" />
                                    </td>
                                    <td>{{ $session->name }}</td>
                                    <td>{{ $session->phone }}</td>
                                    <td>{{ $session->status ?? "Offline" }}</td>
                                    <td>{{ $session->created_at }}</td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <div id="deleteConfirmationModal" class="custom-modal">
      <div class="custom-modal-content">
        <span class="close">&times;</span>
        <h5>تأكيد الحذف</h5>
        <p>هل أنت متأكد من حذف الجلسات المحددة؟</p>
        <button class="btn btn-primary" id="confirmDelete">موافق</button>
        <button class="btn btn-close" id="cancelDelete">إلغاء</button>
      </div>
    </div>

    <div class="overflow"></div>
    <div class="model_poup" data-model="1">
        <div class="content">
            <div class="head">
                <h5 class="title_model">اضافه جلسه</h5>
                <div class="close_model">
                    <i class="fa-solid fa-xmark" onclick="stopInterval();"></i>
                </div>
            </div>
            <form action="" id="whatsapp_phone_form">
                <div class="input_item">
                    <label for="">رقم هاتف مع كود الدوله</label>
                    <input type="text" id="whatsapp_phone" />
                    <p style="color: red" id="whatsapp_phone_error" class="d-none"></p>
                </div>
                <button type="button" class="btn_submit" onclick="addPhoneRequest();">{{ __('Add') }}</button>
            </form>
        </div>
    </div>
    <div class="overflow"></div>
    <div class="model_poup" data-model="2">
        <div class="content">
            <div class="head">
                <h5 class="title_model">{{ __('connect') }}</h5>
                <label for="myCheckbox">Set as a default Phone Number!</label>
                <input type="checkbox" id="defCheckbox" name="myCheckbox" checked>

                <div class="close_model">
                    <i class="fa-solid fa-xmark" onclick="stopInterval2();"></i>
                </div>
            </div>

            <div class="alert alert-danger m-3 d-none" role="alert" id="error_phone">
                {{ __('Choose a phone number to reconnect') }}
            </div>

            <span class="loader" id="spinner2"></span>
            <img class="d-none m-auto" src="" id="qrcode2" alt="qrcode">
        </div>
    </div>

    <!-- Scripts -->
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script src="{{ asset('js/tableUtils.js') }}"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="js/model.js"></script>
    <script src="js/boxs-header.js"></script>
    <script src="js/sidebar.js"></script>
    <script>
        
        document.addEventListener('DOMContentLoaded', function() {
            function addPhoneRequest() {
    var whatsapp_phone = $('#whatsapp_phone').val();  // Get the phone value from input
    var tokenAuth = $("#myToken").val();  // Get the token value

    console.log("hello from token: " + tokenAuth);

    $.ajax({
        url: "{{ route('whatsapp.phone') }}",
        method: "post",
        data: {
            phone: whatsapp_phone,  // Pass the phone number correctly
            token: tokenAuth  // Add the token to the request data
        },
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function(data) {
            if (data.success == true) {
                $("#whatsapp_phone_error").addClass("d-none");
                document.getElementById("spinner").classList.remove("d-none");
                document.getElementById("whatsapp_phone_form").classList.add("d-none");
                $("#qrcode_phone").val(data.phone);
                runInterval();
            } else {
                $("#whatsapp_phone_error").removeClass("d-none");
                $("#whatsapp_phone_error").html(data.message);
            }
        }
    });
}

function qrcodeRequest() {
    var phone = $("#qrcode_phone").val();
    var myToken = $("#myToken").val();
    $.ajax({
        method: "get",
        url: "{{ route('whatsapp.qrcode') }}",
        data: {
            phone: phone,
            token: myToken
        },

      
        success: function(data) {
            if (data.status == 'success') {
                if (data.qrcode.startsWith('data')) {
                    document.getElementById("qrcode").classList.remove("d-none");
                    document.getElementById("qrcode").classList.add("d-block");
                    document.getElementById("spinner").classList.add("d-none");
                    document.getElementById("qrcode").src = data.qrcode;
                }
            }
            if (data.status == 'connected') {
                $.ajax({
                    method: "put",
                    url: "{{ route('whatsapp.session.status') }}",
                    data: {
                        status: "connected",
                        phone: phone,
                        token: myToken  
                    },
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    success: function(data) {
                        location.reload();
                    }
                });
            }
        }
    });
}

            const selectedPhones = new Set();
            const deleteBtn = document.getElementById('delbtn');
            const selectAllCheckbox = document.getElementById('selectAllCheckbox');
            const checkboxes = document.querySelectorAll('.row-checkbox');
            const deleteConfirmationModal = document.getElementById('deleteConfirmationModal');
            const closeDeleteModalElements = deleteConfirmationModal.querySelectorAll('.close, #cancelDelete');
            const confirmDeleteButton = document.getElementById('confirmDelete');

            /**
             * دالة لإظهار المودال
             * @param {HTMLElement} modal - عنصر المودال المراد إظهاره
             */
            function showModal(modal) {
                modal.style.display = 'block';
                document.body.classList.add('modal-open');
            }

            /**
             * دالة لإخفاء المودال
             * @param {HTMLElement} modal - عنصر المودال المراد إخفاءه
             */
            function hideModal(modal) {
                modal.style.display = 'none';
                document.body.classList.remove('modal-open');
            }

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

                confirmDeleteButton.addEventListener('click', () => {
                    hideModal(deleteConfirmationModal);
                    deleteSelectedRows();
                });

                deleteBtn.addEventListener('click', function(event) {
                    event.preventDefault(); // منع السلوك الافتراضي للنقر
                    if (selectedPhones.size === 0) {
                        alert('يرجى تحديد جلسات للحذف.');
                        return;
                    }
                    showModal(deleteConfirmationModal);
                });
            }

        
            function deleteSelectedRows() {
                const phonesArray = Array.from(selectedPhones);

                fetch('/delete-sessions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: JSON.stringify({phones: phonesArray})
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        phonesArray.forEach(phone => {
                            const rows = document.querySelectorAll('tr');
                            for (let row of rows) {
                                if (row.cells[2] && row.cells[2].textContent.trim() === phone) {
                                    row.remove();
                                    break;
                                }
                            }
                        });
                        selectedPhones.clear();
                        deleteBtn.disabled = true;
                        checkboxes.forEach(checkbox => {
                            checkbox.checked = false;
                        });
                        alert('تم حذف الجلسات المحددة بنجاح.');
                    } else {
                        window.location.reload();
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    window.location.reload();
                });
            }

         
            function setupCheckboxes() {
                selectAllCheckbox.addEventListener('change', function() {
                    checkboxes.forEach(checkbox => {
                        checkbox.checked = this.checked;
                        const row = checkbox.closest('tr');
                        const phone = row.cells[2].textContent.trim();
                        if (checkbox.checked) {
                            selectedPhones.add(phone);
                        } else {
                            selectedPhones.delete(phone);
                        }
                    });
                    deleteBtn.disabled = selectedPhones.size === 0;
                });

                checkboxes.forEach(checkbox => {
                    checkbox.addEventListener('change', function() {
                        const row = this.closest('tr');
                        const phone = row.cells[2].textContent.trim();
                        if (this.checked) {
                            selectedPhones.add(phone);
                        } else {
                            selectedPhones.delete(phone);
                        }
                        const allChecked = Array.from(checkboxes).every(cb => cb.checked);
                        selectAllCheckbox.checked = allChecked;
                        deleteBtn.disabled = selectedPhones.size === 0;
                    });
                });
            }

            setupCheckboxes();
            setupDeleteModal();
        });

        $(document).ready(function() {
          $("#table").DataTable({
            pagingType: "full_numbers",
            scrollX: true,
            autoWidth: false,
          });
        });
    </script>
</body>
</html> fix the addpone request is undefined