<!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"id='addModelButton' data-model="1">
                                        <i class="fa-solid fa-plus"></i>
                                        <span>{{ __('Add') }}</span>
                                    </div>
                                    <div  id='connectButton' 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">
                    <i class="fa-solid fa-xmark" id="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() {
        console.log("DOM fully loaded and parsed.");

        // Variables to hold interval IDs
        let intervalFun = null;
        let intervalFun2 = null;

        // Function to handle stopping the interval and clearing QR code (Connect Modal)
        function stopInterval2() {
            console.log('stopInterval2: Function invoked.');

            if (intervalFun2) {
                clearInterval(intervalFun2);
                intervalFun2 = null;
                console.log('stopInterval2: intervalFun2 cleared.');
            } else {
                console.warn('stopInterval2: intervalFun2 was not running.');
            }

            const qrcode2 = document.getElementById("qrcode2");
            const spinner2 = document.getElementById("spinner2");
            const connectModal = document.querySelector('.model_poup[data-model="2"]');
            const whatsappForm = document.getElementById("whatsapp_phone_form");

            if (qrcode2) {
                qrcode2.classList.remove("d-block");
                qrcode2.classList.add("d-none");
                qrcode2.src = ''; // Clear the QR code image
                console.log('stopInterval2: QR code cleared.');
            } else {
                console.error('stopInterval2: Element with ID "qrcode2" not found.');
            }

            if (spinner2) {
                spinner2.classList.add("d-none");
                console.log('stopInterval2: Spinner hidden.');
            } else {
                console.error('stopInterval2: Element with ID "spinner2" not found.');
            }

            if (connectModal) {
                connectModal.classList.remove("active"); // Adjust based on your CSS to hide the modal
                console.log('stopInterval2: Connect modal hidden.');
            } else {
                console.error('stopInterval2: Connect modal element not found.');
            }

            if (whatsappForm) {
                whatsappForm.reset(); // Resets the form fields
                whatsappForm.classList.remove("d-none");
                console.log('stopInterval2: WhatsApp phone form reset and shown.');
            } else {
                console.error('stopInterval2: WhatsApp phone form element not found.');
            }
        }

        // Function to handle stopping the interval and clearing QR code (Add Modal)
        function stopInterval() {
            console.log('stopInterval: Function invoked.');

            if (intervalFun) {
                clearInterval(intervalFun);
                intervalFun = null;
                console.log('stopInterval: intervalFun cleared.');
            } else {
                console.warn('stopInterval: intervalFun was not running.');
            }

            const qrcode = document.getElementById("qrcode");
            const spinner = document.getElementById("spinner");
            const addModal = document.querySelector('.model_poup[data-model="1"]');
            const whatsappForm = document.getElementById("whatsapp_phone_form");

            if (qrcode) {
                qrcode.classList.remove("d-block");
                qrcode.classList.add("d-none");
                qrcode.src = ''; // Clear the QR code image
                console.log('stopInterval: QR code cleared.');
            } else {
                console.error('stopInterval: Element with ID "qrcode" not found.');
            }

            if (spinner) {
                spinner.classList.add("d-none");
                console.log('stopInterval: Spinner hidden.');
            } else {
                console.error('stopInterval: Element with ID "spinner" not found.');
            }

            if (addModal) {
                addModal.classList.remove("active"); // Adjust based on your CSS to hide the modal
                console.log('stopInterval: Add modal hidden.');
            } else {
                console.error('stopInterval: Add modal element not found.');
            }

            if (whatsappForm) {
                whatsappForm.reset(); // Resets the form fields
                whatsappForm.classList.remove("d-none");
                console.log('stopInterval: WhatsApp phone form reset and shown.');
            } else {
                console.error('stopInterval: WhatsApp phone form element not found.');
            }
        }

        // Function to handle starting intervalFun2
        function runInterval2() {
            if (intervalFun2) {
                console.warn('runInterval2: intervalFun2 is already running.');
                return;
            }
            console.log('runInterval2: Starting intervalFun2.');
            qrcodeRequest2(); // Initial call before setting interval
            intervalFun2 = setInterval(qrcodeRequest2, 5000);
        }

        // Function to handle adding a phone
        function addPhoneRequest() {
            var whatsapp_phone = $('#whatsapp_phone').val().trim();
            var tokenAuth = $("#myToken").val();

            if (!whatsapp_phone) {
                $("#whatsapp_phone_error").removeClass("d-none").text("Please enter a phone number.");
                console.warn('addPhoneRequest: Phone number is empty.');
                return;
            }

            console.log("addPhoneRequest: Attempting to add phone:", whatsapp_phone);

            $.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) {
                    console.log("addPhoneRequest AJAX Success:", 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");
                            console.log('addPhoneRequest: Spinner shown.');
                        } else {
                            console.error('addPhoneRequest: Spinner element not found.');
                        }

                        if (whatsappForm) {
                            whatsappForm.classList.add("d-none");
                            console.log('addPhoneRequest: WhatsApp phone form hidden.');
                        } else {
                            console.error('addPhoneRequest: WhatsApp phone form element not found.');
                        }

                        if (qrcodePhone) {
                            qrcodePhone.value = data.phone;
                            console.log('addPhoneRequest: QR code phone set to', data.phone);
                        } else {
                            console.error('addPhoneRequest: QR code phone element not found.');
                        }

                        runInterval();
                    } else {
                        $("#whatsapp_phone_error").removeClass("d-none").text(data.message || "Failed to add phone.");
                        console.warn('addPhoneRequest: Server returned success=false.');
                    }
                },
                error: function(xhr, status, error) {
                    console.error("addPhoneRequest AJAX Error:", error);
                    $("#whatsapp_phone_error").removeClass("d-none").text("An error occurred. Please try again.");
                }
            });
        }

        // Function to handle QR code requests (Primary)
        function qrcodeRequest() {
            var phone = $("#qrcode_phone").val();
            var myToken = $("#myToken").val();

            console.log("qrcodeRequest: Request sent for phone:", phone);

            $.ajax({
                method: "GET",
                url: "{{ route('whatsapp.qrcode') }}",
                data: {
                    phone: phone,
                    token: myToken
                },
                success: function(data) {
                    console.log("qrcodeRequest AJAX Success:", data);
                    if (data.status === 'success') {
                        if (data.qrcode && 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;
                                console.log('qrcodeRequest: QR code displayed.');
                            } else {
                                console.error('qrcodeRequest: Element with ID "qrcode" not found.');
                            }

                            if (spinner) {
                                spinner.classList.add("d-none");
                                console.log('qrcodeRequest: Spinner hidden.');
                            } else {
                                console.error('qrcodeRequest: Element with ID "spinner" not found.');
                            }
                        } else {
                            console.error('qrcodeRequest: Invalid QR code data received:', data.qrcode);
                        }
                    }
                    if (data.status === 'connected') {
                        console.log("qrcodeRequest: Connected status received for phone:", phone);
                        // Update session status
                        $.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) {
                                console.log("Session status updated successfully.");
                                location.reload();
                            },
                            error: function(xhr, status, error) {
                                console.error("Session Status AJAX Error:", error);
                                alert('An error occurred while updating session status. Please try again.');
                            }
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error("qrcodeRequest AJAX Error:", error);
                    alert('Failed to retrieve QR Code. Please check your connection and try again.');
                }
            });
        }

        // Function to handle QR code requests for Connect Modal
        function qrcodeRequest2() {
            var defCheckbox = document.getElementById('defCheckbox')?.checked;
            var selectedCheckbox = document.querySelector('.row-checkbox:checked');

            console.log("qrcodeRequest2: Checking for selected checkbox.");

            if (!selectedCheckbox) {
                const errorPhone = document.getElementById("error_phone");
                if (errorPhone) {
                    errorPhone.classList.remove("d-none");
                    errorPhone.textContent = "Please select a phone number to reconnect.";
                    console.warn('qrcodeRequest2: No checkbox selected.');
                } else {
                    console.error('qrcodeRequest2: Element with ID "error_phone" not found.');
                }
                stopInterval2(); // Ensure intervals are cleared if no selection
                return;
            }

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

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

            if (!phone) {
                console.error('qrcodeRequest2: Phone number not found in selected row.');
                return;
            }

            console.log("qrcodeRequest2: Request sent for phone:", phone);

            $.ajax({
                method: "GET",
                url: "{{ route('whatsapp.qrcode') }}",
                data: {
                    phone: phone,
                    default_phone: defCheckbox,
                    token: myToken
                },
                success: function(data) {
                    console.log("qrcodeRequest2 AJAX Success:", data);
                    if (data.status === 'success') {
                        if (data.qrcode && 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;
                                console.log('qrcodeRequest2: QR code displayed.');

                                // **NEW:** Stop interval since QR code is now displayed
                                stopInterval2();
                            } else {
                                console.error('qrcodeRequest2: Element with ID "qrcode2" not found.');
                            }

                            if (spinner2) {
                                spinner2.classList.add("d-none");
                                console.log('qrcodeRequest2: Spinner hidden.');
                            } else {
                                console.error('qrcodeRequest2: Element with ID "spinner2" not found.');
                            }
                        } else {
                            console.error('qrcodeRequest2: Invalid QR code data received:', data.qrcode);
                        }
                    }
                    if (data.status === 'connected') {
                        console.log("qrcodeRequest2: Connected status received for phone:", phone);
                        // Update session status
                        $.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) {
                                console.log("Session status updated successfully.");
                                location.reload();
                            },
                            error: function(xhr, status, error) {
                                console.error("Session Status AJAX Error:", error);
                                alert('An error occurred while updating session status. Please try again.');
                            }
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error("qrcodeRequest2 AJAX Error:", error);
                    alert('Failed to retrieve QR Code. Please check your connection and try again.');
                }
            });
        }

        // Function to handle starting intervalFun
        function runInterval() {
            if (intervalFun) {
                console.warn('runInterval: intervalFun is already running.');
                return;
            }
            console.log('runInterval: Starting intervalFun.');
            qrcodeRequest(); // Initial call before setting interval
            intervalFun = setInterval(qrcodeRequest, 5000);
        }

        // Function to handle stopping intervalFun
        function stopInterval() {
            console.log('stopInterval: Function invoked.');

            if (intervalFun) {
                clearInterval(intervalFun);
                intervalFun = null;
                console.log('stopInterval: intervalFun cleared.');
            } else {
                console.warn('stopInterval: intervalFun was not running.');
            }

            const qrcode = document.getElementById("qrcode");
            const spinner = document.getElementById("spinner");
            const addModal = document.querySelector('.model_poup[data-model="1"]');
            const whatsappForm = document.getElementById("whatsapp_phone_form");

            if (qrcode) {
                qrcode.classList.remove("d-block");
                qrcode.classList.add("d-none");
                qrcode.src = ''; // Clear the QR code image
                console.log('stopInterval: QR code cleared.');
            } else {
                console.error('stopInterval: Element with ID "qrcode" not found.');
            }

            if (spinner) {
                spinner.classList.add("d-none");
                console.log('stopInterval: Spinner hidden.');
            } else {
                console.error('stopInterval: Element with ID "spinner" not found.');
            }

            if (addModal) {
                addModal.classList.remove("active"); // Adjust based on your CSS to hide the modal
                console.log('stopInterval: Add modal hidden.');
            } else {
                console.error('stopInterval: Add modal element not found.');
            }

            if (whatsappForm) {
                whatsappForm.reset(); // Resets the form fields
                whatsappForm.classList.remove("d-none");
                console.log('stopInterval: WhatsApp phone form reset and shown.');
            } else {
                console.error('stopInterval: WhatsApp phone form element not found.');
            }
        }

        // Function to handle QR code requests (Primary)
        function qrcodeRequest() {
            var phone = $("#qrcode_phone").val();
            var myToken = $("#myToken").val();

            console.log("qrcodeRequest: Request sent for phone:", phone);

            $.ajax({
                method: "GET",
                url: "{{ route('whatsapp.qrcode') }}",
                data: {
                    phone: phone,
                    token: myToken
                },
                success: function(data) {
                    console.log("qrcodeRequest AJAX Success:", data);
                    if (data.status === 'success') {
                        if (data.qrcode && 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;
                                console.log('qrcodeRequest: QR code displayed.');
                            } else {
                                console.error('qrcodeRequest: Element with ID "qrcode" not found.');
                            }

                            if (spinner) {
                                spinner.classList.add("d-none");
                                console.log('qrcodeRequest: Spinner hidden.');
                            } else {
                                console.error('qrcodeRequest: Element with ID "spinner" not found.');
                            }
                        } else {
                            console.error('qrcodeRequest: Invalid QR code data received:', data.qrcode);
                        }
                    }
                    if (data.status === 'connected') {
                        console.log("qrcodeRequest: Connected status received for phone:", phone);
                        // Update session status
                        $.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) {
                                console.log("Session status updated successfully.");
                                location.reload();
                            },
                            error: function(xhr, status, error) {
                                console.error("Session Status AJAX Error:", error);
                                alert('An error occurred while updating session status. Please try again.');
                            }
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error("qrcodeRequest AJAX Error:", error);
                    alert('Failed to retrieve QR Code. Please check your connection and try again.');
                }
            });
        }

        // Function to handle QR code requests for Connect Modal
        function qrcodeRequest2() {
            var defCheckbox = document.getElementById('defCheckbox')?.checked;
            var selectedCheckbox = document.querySelector('.row-checkbox:checked');

            console.log("qrcodeRequest2: Checking for selected checkbox.");

            if (!selectedCheckbox) {
                const errorPhone = document.getElementById("error_phone");
                if (errorPhone) {
                    errorPhone.classList.remove("d-none");
                    errorPhone.textContent = "Please select a phone number to reconnect.";
                    console.warn('qrcodeRequest2: No checkbox selected.');
                } else {
                    console.error('qrcodeRequest2: Element with ID "error_phone" not found.');
                }
                stopInterval2(); // Ensure intervals are cleared if no selection
                return;
            }

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

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

            if (!phone) {
                console.error('qrcodeRequest2: Phone number not found in selected row.');
                return;
            }

            console.log("qrcodeRequest2: Request sent for phone:", phone);

            $.ajax({
                method: "GET",
                url: "{{ route('whatsapp.qrcode') }}",
                data: {
                    phone: phone,
                    default_phone: defCheckbox,
                    token: myToken
                },
                success: function(data) {
                    console.log("qrcodeRequest2 AJAX Success:", data);
                    if (data.status === 'success') {
                        if (data.qrcode && 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;
                                console.log('qrcodeRequest2: QR code displayed.');

                                // **NEW:** Stop interval since QR code is now displayed
                                stopInterval2();
                            } else {
                                console.error('qrcodeRequest2: Element with ID "qrcode2" not found.');
                            }

                            if (spinner2) {
                                spinner2.classList.add("d-none");
                                console.log('qrcodeRequest2: Spinner hidden.');
                            } else {
                                console.error('qrcodeRequest2: Element with ID "spinner2" not found.');
                            }
                        } else {
                            console.error('qrcodeRequest2: Invalid QR code data received:', data.qrcode);
                        }
                    }
                    if (data.status === 'connected') {
                        console.log("qrcodeRequest2: Connected status received for phone:", phone);
                        // Update session status
                        $.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) {
                                console.log("Session status updated successfully.");
                                location.reload();
                            },
                            error: function(xhr, status, error) {
                                console.error("Session Status AJAX Error:", error);
                                alert('An error occurred while updating session status. Please try again.');
                            }
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error("qrcodeRequest2 AJAX Error:", error);
                    alert('Failed to retrieve QR Code. Please check your connection and try again.');
                }
            });
        }

        // Function to handle starting intervalFun
        function runInterval() {
            if (intervalFun) {
                console.warn('runInterval: intervalFun is already running.');
                return;
            }
            console.log('runInterval: Starting intervalFun.');
            qrcodeRequest(); // Initial call before setting interval
            intervalFun = setInterval(qrcodeRequest, 5000);
        }

        // Function to handle stopping intervalFun
        function stopInterval() {
            console.log('stopInterval: Function invoked.');

            if (intervalFun) {
                clearInterval(intervalFun);
                intervalFun = null;
                console.log('stopInterval: intervalFun cleared.');
            } else {
                console.warn('stopInterval: intervalFun was not running.');
            }

            const qrcode = document.getElementById("qrcode");
            const spinner = document.getElementById("spinner");
            const addModal = document.querySelector('.model_poup[data-model="1"]');
            const whatsappForm = document.getElementById("whatsapp_phone_form");

            if (qrcode) {
                qrcode.classList.remove("d-block");
                qrcode.classList.add("d-none");
                qrcode.src = ''; // Clear the QR code image
                console.log('stopInterval: QR code cleared.');
            } else {
                console.error('stopInterval: Element with ID "qrcode" not found.');
            }

            if (spinner) {
                spinner.classList.add("d-none");
                console.log('stopInterval: Spinner hidden.');
            } else {
                console.error('stopInterval: Element with ID "spinner" not found.');
            }

            if (addModal) {
                addModal.classList.remove("active"); // Adjust based on your CSS to hide the modal
                console.log('stopInterval: Add modal hidden.');
            } else {
                console.error('stopInterval: Add modal element not found.');
            }

            if (whatsappForm) {
                whatsappForm.reset(); // Resets the form fields
                whatsappForm.classList.remove("d-none");
                console.log('stopInterval: WhatsApp phone form reset and shown.');
            } else {
                console.error('stopInterval: WhatsApp phone form element not found.');
            }
        }

        // Function to handle QR code requests (Primary Initiation)
        function qrcodeRequest() {
            var phone = $("#qrcode_phone").val();
            var myToken = $("#myToken").val();

            console.log("qrcodeRequest: Request sent for phone:", phone);

            $.ajax({
                method: "GET",
                url: "{{ route('whatsapp.qrcode') }}",
                data: {
                    phone: phone,
                    token: myToken
                },
                success: function(data) {
                    console.log("qrcodeRequest AJAX Success:", data);
                    if (data.status === 'success') {
                        if (data.qrcode && 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;
                                console.log('qrcodeRequest: QR code displayed.');
                            } else {
                                console.error('qrcodeRequest: Element with ID "qrcode" not found.');
                            }

                            if (spinner) {
                                spinner.classList.add("d-none");
                                console.log('qrcodeRequest: Spinner hidden.');
                            } else {
                                console.error('qrcodeRequest: Element with ID "spinner" not found.');
                            }
                        } else {
                            console.error('qrcodeRequest: Invalid QR code data received:', data.qrcode);
                        }
                    }
                    if (data.status === 'connected') {
                        console.log("qrcodeRequest: Connected status received for phone:", phone);
                        // Update session status
                        $.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) {
                                console.log("Session status updated successfully.");
                                location.reload();
                            },
                            error: function(xhr, status, error) {
                                console.error("Session Status AJAX Error:", error);
                                alert('An error occurred while updating session status. Please try again.');
                            }
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error("qrcodeRequest AJAX Error:", error);
                    alert('Failed to retrieve QR Code. Please check your connection and try again.');
                }
            });
        }

        // Function to handle QR code requests for Connect Modal
        function qrcodeRequest2() {
            var defCheckbox = document.getElementById('defCheckbox')?.checked;
            var selectedCheckbox = document.querySelector('.row-checkbox:checked');

            console.log("qrcodeRequest2: Checking for selected checkbox.");

            if (!selectedCheckbox) {
                const errorPhone = document.getElementById("error_phone");
                if (errorPhone) {
                    errorPhone.classList.remove("d-none");
                    errorPhone.textContent = "Please select a phone number to reconnect.";
                    console.warn('qrcodeRequest2: No checkbox selected.');
                } else {
                    console.error('qrcodeRequest2: Element with ID "error_phone" not found.');
                }
                stopInterval2(); // Ensure intervals are cleared if no selection
                return;
            }

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

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

            if (!phone) {
                console.error('qrcodeRequest2: Phone number not found in selected row.');
                return;
            }

            console.log("qrcodeRequest2: Request sent for phone:", phone);

            $.ajax({
                method: "GET",
                url: "{{ route('whatsapp.qrcode') }}",
                data: {
                    phone: phone,
                    default_phone: defCheckbox,
                    token: myToken
                },
                success: function(data) {
                    console.log("qrcodeRequest2 AJAX Success:", data);
                    if (data.status === 'success') {
                        if (data.qrcode && 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;
                                console.log('qrcodeRequest2: QR code displayed.');

                                // **NEW:** Stop interval since QR code is now displayed
                                stopInterval2();
                            } else {
                                console.error('qrcodeRequest2: Element with ID "qrcode2" not found.');
                            }

                            if (spinner2) {
                                spinner2.classList.add("d-none");
                                console.log('qrcodeRequest2: Spinner hidden.');
                            } else {
                                console.error('qrcodeRequest2: Element with ID "spinner2" not found.');
                            }
                        } else {
                            console.error('qrcodeRequest2: Invalid QR code data received:', data.qrcode);
                        }
                    }
                    if (data.status === 'connected') {
                        console.log("qrcodeRequest2: Connected status received for phone:", phone);
                        // Update session status
                        $.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) {
                                console.log("Session status updated successfully.");
                                location.reload();
                            },
                            error: function(xhr, status, error) {
                                console.error("Session Status AJAX Error:", error);
                                alert('An error occurred while updating session status. Please try again.');
                            }
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error("qrcodeRequest2 AJAX Error:", error);
                    alert('Failed to retrieve QR Code. Please check your connection and try again.');
                }
            });
        }

        // Event Listeners

        // Attach event listener to the Close Connect Modal Button
        const stopInterval2Button = document.getElementById('stopInterval2');
        if (stopInterval2Button) {
            stopInterval2Button.addEventListener('click', stopInterval2);
            console.log('Event listener attached to "stopInterval2".');
        } else {
            console.error('Button with ID "stopInterval2" not found.');
        }

        // Attach event listener to the Close Add Modal Button (if exists)
        const stopIntervalButton = document.getElementById('stopInterval');
        if (stopIntervalButton) {
            stopIntervalButton.addEventListener('click', stopInterval);
            console.log('Event listener attached to "stopInterval".');
        } else {
            console.warn('Button with ID "stopInterval" not found.');
        }

        // Attach event listener to the Add Model Button
        const addModelButton = document.getElementById('addModelButton');
        if (addModelButton) {
            addModelButton.addEventListener('click', function(event) {
                addPhoneRequest();
                event.preventDefault(); // Prevent default button behavior if necessary
            });
            console.log('Event listener attached to "addModelButton".');
        } else {
            console.error('Button with ID "addModelButton" not found.');
        }

        // Attach event listener to the Connect Button
        const connectButton = document.getElementById('connectButton');
        if (connectButton) {
            connectButton.addEventListener('click', runInterval2);
            console.log('Event listener attached to "connectButton".');
        } else {
            console.error('Button with ID "connectButton" not found.');
        }

        // Initialize DataTables
        $("#table").DataTable({
            pagingType: "full_numbers",
            scrollX: true,
            autoWidth: false,
        });
        console.log('DataTables initialized.');
    });
</script>
</body>
</html>  when qrcodeis retrieved it doesnt load or shhow ithe model but it just all turns to gray overflow the web page