<!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" />
    <input type="hidden" id="qrcode_phone" />
    <input type="hidden" id="myToken" value="{{ csrf_token() }}" />
    <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>
        <div class="sidebar">
            @include('include.sidebar')
        </div>

        <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  id='runInterval2Button' class="item btn_open_model" data-model="2">
                                        <button type="button">
                                            <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" id='addPhoneButton'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" id="stopInterval2">
                    <i class="fa-solid fa-xmark"  ></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() {
    let intervalFun;
    let intervalFun2;
  

    // Function Definitions

    function runInterval() {
        intervalFun = setInterval(qrcodeRequest, 5000);
    }

    function stopInterval() {
        clearInterval(intervalFun);
    }

    function runInterval2() {
        qrcodeRequest2();
        intervalFun2 = setInterval(qrcodeRequest2, 5000);
    }
  function stopInterval2() {
    console.log("he")
        clearInterval(intervalFun2);
        
        const qrcode2 = document.getElementById("qrcode2");
        const spinner2 = document.getElementById("spinner2");

        if (qrcode2) {
            qrcode2.classList.remove("d-block");
            qrcode2.classList.add("d-none");
            qrcode2.src = ''; 
        } else {
            console.error('Element with ID "qrcode2" not found.');
        }

        if (spinner2) {
            spinner2.classList.add("d-none");
        } else {
            console.error('Element with ID "spinner2" not found.');
        }
    }
   
    function addPhoneRequest() {
        var whatsapp_phone = $('#whatsapp_phone').val();  // Get the phone value from input
        var tokenAuth = $("#myToken").val();  // Get the token value

        console.log("addPhoneRequest: Request sent");

        $.ajax({
            url: "{{ route('whatsapp.phone') }}",
            method: "post",
            data: {
                phone: whatsapp_phone,
                token: tokenAuth
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(data) {
                if (data.success === true) {
                    $("#whatsapp_phone_error").addClass("d-none");
                    const spinner = document.getElementById("spinner");
                    const whatsappForm = document.getElementById("whatsapp_phone_form");
                    const qrcodePhone = document.getElementById("qrcode_phone");

                    if (spinner) spinner.classList.remove("d-none");
                    if (whatsappForm) whatsappForm.classList.add("d-none");
                    if (qrcodePhone) qrcodePhone.value = data.phone;

                    runInterval();
                } else {
                    $("#whatsapp_phone_error").removeClass("d-none");
                    $("#whatsapp_phone_error").html(data.message);
                }
            },
            error: function(xhr, status, error) {
                console.error("addPhoneRequest AJAX Error:", error);
            }
        });
    }

    function qrcodeRequest() {
        var phone = $("#qrcode_phone").val();
        var myToken = $("#myToken").val();

        console.log("qrcodeRequest: Request sent");

        $.ajax({
            method: "get",
            url: "{{ route('whatsapp.qrcode') }}",
            data: {
                phone: phone,
                token: myToken
            },
            success: function(data) {
                if (data.status === 'success') {
                    if (data.qrcode.startsWith('data')) {
                        const qrcode = document.getElementById("qrcode");
                        const spinner = document.getElementById("spinner");

                        if (qrcode) {
                            qrcode.classList.remove("d-none");
                            qrcode.classList.add("d-block");
                            qrcode.src = data.qrcode;
                        } else {
                            console.error('Element with ID "qrcode" not found.');
                        }

                        if (spinner) {
                            spinner.classList.add("d-none");
                        } else {
                            console.error('Element with ID "spinner" not found.');
                        }
                    }
                }
                if (data.status === 'connected') {
                    console.log("qrcodeRequest: Connected status received");
                    $.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();
                        },
                        error: function(xhr, status, error) {
                            console.error("Session Status AJAX Error:", error);
                        }
                    });
                }
            },
            error: function(xhr, status, error) {
                console.error("qrcodeRequest AJAX Error:", error);
            }
        });
    }

    function qrcodeRequest2() {
        var defCheckbox = document.getElementById('defCheckbox')?.checked;
        var selectedCheckbox = document.querySelector('.row-checkbox:checked');

        if (!selectedCheckbox) {
            const errorPhone = document.getElementById("error_phone");
            if (errorPhone) {
                errorPhone.classList.remove("d-none");
            } else {
                console.error('Element with ID "error_phone" not found.');
            }
            clearInterval(intervalFun2);
            return;
        }

        const errorPhone = document.getElementById("error_phone");
        if (errorPhone) {
            errorPhone.classList.add("d-none");
        } else {
            console.error('Element with ID "error_phone" not found.');
        }

        var row = selectedCheckbox.closest('tr');
        var phone = row.cells[2]?.textContent.trim();
        var myToken = $("#myToken").val();

        console.log("qrcodeRequest2: Request sent");

        $.ajax({
            method: "get",
            url: "{{ route('whatsapp.qrcode') }}",
            data: {
                phone: phone,
                default_phone: defCheckbox,
                token: myToken
            },
            success: function(data) {
                if (data.status === 'success') {
                    if (data.qrcode.startsWith('data')) {
                        const qrcode2 = document.getElementById("qrcode2");
                        const spinner2 = document.getElementById("spinner2");

                        if (qrcode2) {
                            qrcode2.classList.remove("d-none");
                            qrcode2.classList.add("d-block");
                            qrcode2.src = data.qrcode;
                        } else {
                            console.error('Element with ID "qrcode2" not found.');
                        }

                        if (spinner2) {
                            spinner2.classList.add("d-none");
                        } else {
                            console.error('Element with ID "spinner2" not found.');
                        }
                    }
                }
                if (data.status === 'connected') {
                    console.log("qrcodeRequest2: Connected status received");
                    $.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();
                        },
                        error: function(xhr, status, error) {
                            console.error("Session Status AJAX Error:", error);
                        }
                    });
                }
            },
            error: function(xhr, status, error) {
                console.error("qrcodeRequest2 AJAX Error:", error);
            }
        });
    }

    // Event Listeners

    const addPhoneButton = document.getElementById('addPhoneButton');
    if (addPhoneButton) {
        addPhoneButton.addEventListener('click', addPhoneRequest);
    } else {
        console.error('Element with ID "addPhoneButton" not found.');
    }
    const stopInterval2Element = document.getElementById('stopInterval2');
    if (stopInterval2Element) {
        stopInterval2Element.addEventListener('click', stopInterval2);
    } else {
        console.error('Element with ID "stopInterval2" not found.');
    }

    const runInterval2Button = document.getElementById('runInterval2Button');
    if (runInterval2Button) {
        runInterval2Button.addEventListener('click', runInterval2);
    } else {
        console.error('Element with ID "runInterval2Button" not found.');
    }

    // Setup for Delete Functionality
    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');

    /**
     * Function to show a modal
     * @param {HTMLElement} modal - The modal element to show
     */
    function showModal(modal) {
        if (modal) {
            modal.style.display = 'block';
            document.body.classList.add('modal-open');
        } else {
            console.error('Modal element not provided.');
        }
    }

    /**
     * Function to hide a modal
     * @param {HTMLElement} modal 
     */
    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 (deleteBtn) {
            deleteBtn.addEventListener('click', function(event) {
                event.preventDefault();
                if (selectedPhones.size === 0) {
                    alert('يرجى تحديد جلسات للحذف.');
                    return;
                }
                showModal(deleteConfirmationModal);
            });
        } else {
            console.error('Element with ID "delbtn" not found.');
        }
    }
    

    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();
                if (deleteBtn) deleteBtn.disabled = true;
                checkboxes.forEach(checkbox => {
                    checkbox.checked = false;
                });
                alert('تم حذف الجلسات المحددة بنجاح.');
            } else {
                window.location.reload();
            }
        })
        .catch(error => {
            console.error('Delete Selected Rows Error:', error);
            window.location.reload();
        });
    }

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

        if (!checkboxes.length) {
            console.error('No checkboxes with class "row-checkbox" found.');
            return;
        }

        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 && phone) {
                    selectedPhones.add(phone);
                } else if (phone) {
                    selectedPhones.delete(phone);
                }
            });
            if (deleteBtn) 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 && phone) {
                    selectedPhones.add(phone);
                } else if (phone) {
                    selectedPhones.delete(phone);
                }

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

                if (deleteBtn) deleteBtn.disabled = selectedPhones.size === 0;
            });
        });
    }

    setupCheckboxes();
    setupDeleteModal();
});

// Initialize DataTables
$(document).ready(function() {
    $("#table").DataTable({
        pagingType: "full_numbers",
        scrollX: true,
        autoWidth: false,
    });
});
    </script>
</body>
</html> stopinterval 2 doesnt clear  the   qrcode the qrcode image is still there when i click the xmar and ggo do a new qrcode request with new numbe the old qrcode of the alst number reques i did is still there i want it to make eveything be initial  like the first time i did the qrcode code scanning and it show me the qrcode