<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Video Streams</title>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-2.2.4.min.js"
        integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>

    <!-- Bootstrap files (jQuery first, then Popper.js, then Bootstrap JS) -->
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"
        type="text/css" />
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js" type="text/javascript">
    </script>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    {{-- bootstrap icon --}}
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">

    <style>
        body {
            background-image: url('https://rare-gallery.com/livewalls/imgpreview/141151-artificial-intelligence-neural-network-live-wallpaper.jpg');
            background-repeat: no-repeat;
            background-attachment: fixed;
            background-size: 100% 100%;
        }

        .camera-container {
            width: 420px;
            /* Adjusted to fit 2x2 grid of 200px wide cameras plus margins */
            height: 420px;
            /* Make it square */
            margin: 0 auto;
            padding: 10px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            box-sizing: border-box;
        }

        .camera-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            grid-template-rows: repeat(2, 1fr);
            gap: 10px;
            width: 100%;
            height: 100%;
        }

        .video-wrapper {
            width: 100%;
            height: 100%;
            overflow: hidden;
            position: relative;
            border: 1px solid #198754;
            box-sizing: border-box;
        }

        .video-wrapper video {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .nav-buttons {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-bottom: 10px;
        }

        .camera-name-label {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            background-color: rgba(25, 135, 84, 0.8);
            color: white;
            padding: 5px 0;
            text-align: center;
            font-weight: bold;
            z-index: 10;
            font-size: 0.8em;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .camera-name-label span {
            margin-left: 5px;
        }

        .camera-name-label select {
            background-color: transparent;
            color: black;
            border: none;
            padding: 3px 5px;
            font-size: 0.8em;
            margin-right: 5px;
            width: auto;
            max-width: 60%;
        }

        .tooltip-box {
            position: absolute;
            bottom: 3px;
            left: 3px;
            right: 3px;
            background-color: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 2px;
            font-size: 0.5em;
            display: none;
            border-radius: 2px;
        }

        .video-wrapper:hover .tooltip-box {
            display: block;
        }

        .nav-buttons button {
            padding: 5px 10px;
            background-color: #198754;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            transition: background-color 0.3s;
            font-size: 0.7em;
        }

        .nav-buttons button:hover {
            background-color: #146c43;
        }

        .nav-buttons button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }


        .camera-name-label .form-select {
            /* #ffc107 */
            background-color: #ffffff;
            color: #000000;
            border: 1px solid #000000;
            border-radius: 10px;
        }

        .form-select {
            background-color: #ffffff;
            color: #000000;
            border: 1px solid #000000;
            border-radius: 10px;
        }

        #show_regions {
            margin-left: 10px;
            padding: 0px 10px;

        }

        #add-preset {
            background-color: rgba(255, 255, 255, 0.7);
            /* White background with 80% opacity */
            border-radius: 30px;
        }

        .camera-img-content {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    </style>
</head>

<body>
    <div class="row" style=" padding: 10px; margin-left: 4px; ">
        <a href="{{ route('dash') }}" class="btn btn-success btn-sm" style="margin-right: 5px">Go Back</a>

        <button data-toggle="modal" data-target="#modal_aside_left" class="btn btn-danger btn-sm">View Logs</button>

        <select class="form-select form-select-lg ms-3 region-select" id="show_regions"
            aria-label="Large select example" onchange="getMessage('select-series')">
        </select>

    </div>
    <div class="container">

        <form action="{{ route('preset_save') }}" method="POST">
            @csrf()
            <div class=" rounded-5 px-3" id="add-preset">
                <h2 class="display-4 text-center my-3" style="font-size: 30px">Create Virtual Wall Presets
                </h2>
                <table id="preset-table" class="table">
                    <thead>
                        <tr class="text-nowrap">
                            <th class="">#</th>
                            <th class="">Preset Lebel</th>
                            <th class="">Select Region</th>
                            <th class="">Select Cameras</th>
                            <th class=""></th>

                        </tr>
                    </thead>
                    <tbody>
                        {{-- @dd($presets) --}}
                        @if (isset($presets) && count($presets) > 0)
                            @foreach ($presets as $index => $preset)
                                <tr class="">
                                    <td>{{ $index + 1 }}</td>
                                    <td>{{ $preset->label }}</td>
                                    <td>{{ $preset->region_details['region'] ?? 'No Region' }}</td>
                                    <td>
                                        @php
                                            $cameraDetails = $preset['camera_details'] ?? [];
                                        @endphp
                                        @if (!empty($cameraDetails))
                                            @php
                                                $cameraNames = [];
                                                //                                                 foreach ($cameraDetails as $camera) {
                                                //                                                     if ($camera instanceof MongoDB\Model\BSONDocument) {
                                                //                                                         // If it's a BSONDocument, extract the cameraname
//         $cameraNames[] = $camera['cameraname'] ?? 'Unknown';
//     } elseif (is_array($camera)) {
//         // If it's an array, extract the cameraname
                                                //                                                         $cameraNames[] = $camera['cameraname'] ?? 'Unknown';
                                                //                                                     } else {
                                                //                                                         // If it's something else, convert to string
//         $cameraNames[] = (string) $camera;
//     }
// }

foreach ($cameraDetails as $camera) {
    if ($camera instanceof MongoDB\Model\BSONDocument) {
        // If it's a BSONDocument, extract the cameraname
                                                        $cameraNames[] = $camera['cameraname'] ?? 'Unknown';
                                                    } elseif (is_array($camera)) {
                                                        // If it's an array, extract the cameraname
        $cameraNames[] = $camera['cameraname'] ?? 'Unknown';
    } else {
        // If it's something else, convert to string
                                                        $cameraNames[] = (string) $camera;
                                                    }
                                                }
                                                echo implode(', ', $cameraNames);
                                            @endphp
                                        @else
                                            No cameras available
                                        @endif
                                    </td>
                                    <td>
                                        <a href="javascript:void(0)" role="button" class="btn btn-success"
                                            onclick="loadPreset('{{ $preset->_id }}')">Load</a>
                                        <a href="javascript:void()" class="btn btn-danger" role="button"
                                            onclick="deletePreset('{{ $preset->_id }}')">Delete</a>

                                    </td>
                                </tr>
                            @endforeach

                        @endif

                        {{-- @if (count($presets) < 3) --}}
                        <tr id="addNewPreset">
                            <td></td>
                            <td><input type="text" class="form-control" required name="preset_label[]"
                                    placeholder="Label name" value="">
                            </td>
                            <td>
                                <select class="form-select form-select-sm ms-3 p-2 region-select preset-region-select"
                                    aria-label="Large select example" name="region_id[]"
                                    onchange="sendRegionReq(this.value, 'preset-camera-0')" id="region-preset">
                                </select>
                            </td>
                            <td>
                                <div class="mt-2">
                                    <select
                                        class="form-select form-select-sm ms-3 camera-select-preset preset preset-camera-0"
                                        name="preset[0][]" aria-label="Large select example">

                                    </select>
                                    <select
                                        class="form-select form-select-sm ms-3 camera-select-preset preset preset-camera-0"
                                        name="preset[0][]" aria-label="Large select example">
                                    </select>
                                    <select
                                        class="form-select form-select-sm ms-3 camera-select-preset preset preset-camera-0"
                                        name="preset[0][]" aria-label="Large select example">
                                    </select>
                                    <select
                                        class="form-select form-select-sm ms-3 camera-select-preset preset preset-camera-0"
                                        name="preset[0][]" aria-label="Large select example">
                                    </select>
                                </div>
                            </td>
                        </tr>

                        {{-- @endif --}}

                    </tbody>
                </table>
                @if ($errors->any())
                    <div class="alert alert-light text-danger py-0 rounded-pill">
                        <ul class="mt-1">
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif

                <div class="d-flex justify-content-end">
                    <button id="addRowBtn" type="button" class="btn btn-primary m-2"> <i
                            class="bi bi-plus-circle-fill"></i> Add More Preset</button>
                    <button class="btn btn-success m-2"><i class="bi bi-floppy2-fill"></i> Save Preset</button>
                </div>
            </div>
        </form>
        <div class="video-container mt-5" id="videoContainer">
            <div id="loading" style=" text-align: center; padding: 51px; ">
                <img src="{{ asset('infinite-spinner.svg') }}" style="width:300px;" />
            </div>
            {{-- @foreach ($cameras as $list)
                <div class="video-wrapper border border-2 rounded p-1 border-success">
                    <div class="camera-name-label bg-success">Camera Stream 1</div>
                    <video src="{{ $list['stream_url'] }}" controls autoplay muted></video>
                    @if (sizeOf($list['joined_data']) > 0)
                        <?php
                        $joined_data = $list['joined_data'][0];
                        ?>
                        @if ($joined_data['info'])
                            <?php $info = $joined_data['info']; ?>
                            <div class="tooltip-box">
                                <strong>Video Format</strong> {{ $info['format']['format_long_name'] }}<br>
                                <strong>Status:</strong>{{ $list['status'] == 1 ? 'Active' : 'Disabled' }}<br>
                                <strong>Black Screen:</strong> Yes<br>
                                <strong>Blur Screen:</strong> Yes<br>
                                <strong>Threshold:</strong>
                                {{ isset($info['format']['bit_rate']) ? $info['format']['bit_rate'] : '' }}<br>
                                <strong>Latency:</strong>
                                {{ isset($info['latency_seconds']) ? $info['latency_seconds'] : '' }}
                            </div>
                        @endif
                    @endif

                </div>
            @endforeach --}}
        </div>
    </div>


    <div id="modal_aside_left" class="modal fixed-left fade" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-dialog-aside" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Activity Logs</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <ul id="myList" style="font-size: 10px;">
                    </ul>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div> <!-- modal-bialog .// -->
    </div> <!-- modal.// -->


    @if (session()->has('error'))
        <script>
            Swal.fire({
                title: 'Error!',
                text: '{{ session()->get('error') }}',
                icon: 'error',
                customClass: {
                    popup: 'swal2-popup'
                }
            });
        </script>
    @endif

    @if (session()->has('success'))
        <script>
            Swal.fire(
                'Success!',
                '{{ session()->get('success') }}',
                'success'
            )
        </script>
    @endif


    <script src="https://js.pusher.com/8.2.0/pusher.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

    <link href="https://vjs.zencdn.net/7.14.3/video-js.css" rel="stylesheet" />
    <script src="https://vjs.zencdn.net/7.14.3/video.min.js"></script>



    <script>
        // ====== CREATE NEW ROW IN TABLE ON BTN CLICK   ======

        var rowCount = 0; // This will be used to keep track of the next row number

        document.getElementById('addRowBtn').addEventListener('click', function() {
            // Get the table where you want to add the row
            var table = document.getElementById('add-preset').getElementsByTagName('tbody')[0];

            // Get the row with ID 'addNewPreset' as a template
            var templateRow = document.getElementById('addNewPreset');

            // Clone the row with the ID 'addNewPreset'
            var newRow = templateRow.cloneNode(true);

            // Increment rowCount for unique identifiers
            rowCount++;

            // Update the 'name' and 'onchange' attributes in the new row
            newRow.querySelectorAll('select').forEach(function(select) {
                // Update 'preset-camera-x' class
                select.className = select.className.replace(/preset-camera-\d+/, 'preset-camera-' +
                    rowCount);

                // Update 'name' attributes like 'preset[1][]' to 'preset[' + rowCount + '][]'
                select.name = select.name.replace(/\[\d+\]/, '[' + rowCount + ']');

                // Clear any selected options
                select.selectedIndex = -1; // Ensures no option is selected for other select menus
            });

            // Find the region select and update its 'onchange' attribute if it exists
            var regionSelect = newRow.querySelector('.preset-region-select');
            if (regionSelect) {
                // Set the first option as the selected option
                regionSelect.selectedIndex = 0;

                // Update the 'onchange' attribute
                regionSelect.setAttribute('onchange', "sendRegionReq(this.value, 'preset-camera-" + rowCount +
                    "')");
            }

            // Clear input values for the cloned row
            newRow.querySelectorAll('input').forEach(input => input.value = '');

            // Remove the ID from the cloned row to avoid duplicate IDs
            newRow.removeAttribute('id');

            // Create a new <td> element for the delete button
            var deleteTd = document.createElement('td');
            var deleteBtn = document.createElement('button');
            deleteBtn.textContent = 'Delete';
            deleteBtn.className = 'btn btn-danger'; // Optional: styling for the delete button

            // Add click event to delete the row
            deleteBtn.addEventListener('click', function() {
                newRow.remove();
                updateRowNumbers(); // Update row numbers after a row is deleted
            });

            // Append the delete button to the new <td>
            deleteTd.appendChild(deleteBtn);
            newRow.appendChild(deleteTd); // Append the <td> to the new row

            // Append the new row to the end of the table
            table.appendChild(newRow);

            // Update the rowCount to reflect the highest current row number
            rowCount = document.querySelectorAll('#add-preset tbody tr').length;
        });

        // Function to update row numbering after a row is deleted
        function updateRowNumbers() {
            var rows = document.querySelectorAll('#add-preset tbody tr'); // Get all rows in the tbody

            rows.forEach(function(row, index) {
                var newRowNumber = index; // Start rowNumber from 0 for each row

                row.querySelectorAll('select').forEach(function(select) {
                    select.className = select.className.replace(/preset-camera-\d+/, 'preset-camera-' +
                        newRowNumber);
                    select.name = select.name.replace(/\[\d+\]/, '[' + newRowNumber + ']');
                });

                var regionSelect = row.querySelector('.preset-region-select');
                if (regionSelect) {
                    regionSelect.setAttribute('onchange', "sendRegionReq(this.value, 'preset-camera-" +
                        newRowNumber + "')");
                }
            });

            // Update rowCount to match the new row number sequence
            rowCount = rows.length;
        }





        // ====== DELETE PRESET ON BTN CLICK   ======

        function deletePreset(id) {
            Swal.fire({
                title: "Are you sure?",
                text: "You won't be able to revert this!",
                icon: "warning",
                showCancelButton: true,
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#d33",
                confirmButtonText: "Yes, delete it!"
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = "{{ url('/virtial-wall/preset/delete/') }}/" + id;
                }
            });
        }


        // Enable pusher logging - don't include this in production
        Pusher.logToConsole = true;
        var pusher = new Pusher(
            '{{ env('PUSHER_APP_KEY') }}', {
                cluster: '{{ env('PUSHER_APP_CLUSTER') }}'
            });

        var channel = pusher.subscribe('my-channel');

        channel.bind('my-event', function(data) {
            // var msgg = data['message'];
            console.log(data.message);
            var _data = data.message
            if (_data.type == "black_detected" || _data.type == "blur_detected" || _data.type ==
                "motion_detection") {
                cameraNameLabel = document.getElementById("camera_" + _data.camera_id);
                cameraNameLabel.className = "camera-name-label bg-warning";
                var ulElement = document.getElementById('myList');
                var newLiElement = document.createElement('li');
                newLiElement.textContent = _data.type + " in " + _data.camera_name;
                ulElement.appendChild(newLiElement);
            }
            //alert(JSON.stringify(data));
        });



        getMessage('select-series');



        let currentCameraSet = 0;
        const camerasPerSet = 4;


        // Define video formats and their MIME types globally
        const allVideoFormat = {
            'mpd': "application/dash+xml",
            'mp4': "video/mp4",
            'webm': "video/webm",
            'ogg': "video/ogg",
            'm3u8': "application/x-mpegURL",
            'mjpeg': "video/x-motion-jpeg",
            'avi': "video/x-msvideo",
            'mov': "video/quicktime",
            'mkv': "video/x-matroska",
            '3gp': "video/3gpp",
            '3g2': "video/3gpp2",
            'asf': "video/x-ms-asf",
            'flv': "video/x-flv",
            'f4v': "video/x-f4v",
            'ts': "video/mp2t",
            'mpeg': "video/mpeg",
            'mpg': "video/mpeg",
            'wmv': "video/x-ms-wmv",
            'divx': "video/divx",
            'xvid': "video/xvid",
            'vob': "video/dvd",
            'mts': "video/avchd",
            'm2ts': "video/avchd",
            'hevc': "video/hevc",
            'h264': "video/h264",
            'h265': "video/h265",
            'dv': "video/x-dv",
            'rm': "application/vnd.rn-realmedia",
            'rv': "video/vnd.rn-realvideo",
            'drc': "video/x-dirac"
        };

        function getFileExtension(url) {
            return url.split('.').pop().split(/[\?#]/)[0];
        }

        function createMediaElement(url, video_type, videoContainerId) {
            if (video_type === 'normal') {
                const fileExtension = getFileExtension(url).toLowerCase();
                const mimeType = allVideoFormat[fileExtension] || '';
                if (videoContainerId) {
                    const element = document.getElementById('videoContainer_' + videoContainerId);
                    if (element) {
                        element.parentNode.removeChild(element);
                    }
                }

                if (mimeType) {
                    var videoContainer = document.createElement("div");
                    videoContainer.style.width = "100%";
                    videoContainer.style.height = "auto";
                    videoContainer.id = 'videoContainer_' + videoContainerId;

                    var videoElement = document.createElement("video");
                    videoElement.className = "video-js";
                    videoElement.controls = true; // Show controllers
                    videoElement.autoplay = true; // Autoplay the video
                    videoElement.muted = true; // Mute the audio by default
                    videoElement.preload = "auto";
                    videoElement.style.width = "100%";
                    videoElement.style.height = "auto";

                    var sourceElement = document.createElement("source");
                    sourceElement.src = url;
                    sourceElement.type = mimeType;

                    videoElement.appendChild(sourceElement);

                    videoContainer.appendChild(videoElement);

                    // Initialize Video.js
                    videojs(videoElement, {
                        // Options
                        muted: true, // Mute the audio by default
                        autoplay: true, // Autoplay the video
                        controls: true, // Show controllers
                        playbackRates: [0.5, 1, 1.5, 2], // Add playback rate options
                        fluid: true,
                    });

                    return videoContainer; // Return the container that holds the video player
                } else {
                    var imgElement = document.createElement("img");
                    imgElement.src = url;
                    imgElement.alt = "Image";
                    imgElement.className = "camera-img-content";
                    return imgElement;
                }
            } else {
                // Handle YouTube video
                var videoId = url.split('v=')[1];
                var ampersandPosition = videoId.indexOf('&');
                if (ampersandPosition != -1) {
                    videoId = videoId.substring(0, ampersandPosition);
                }

                // Add mute and autoplay parameters to the YouTube embed URL
                var youtubeEmbedUrl = `https://www.youtube.com/embed/${videoId}?autoplay=1&mute=1`;

                var iframeElement = document.createElement("iframe");
                iframeElement.width = "100%";
                iframeElement.height = "100%";
                iframeElement.src = youtubeEmbedUrl;
                iframeElement.frameBorder = "0";
                iframeElement.allow =
                    "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture";
                iframeElement.allowFullscreen = true;

                return iframeElement;
            }
        }








        function getMessage(cameraClass = 'camera-select') {
            const videoContainer = document.getElementById('videoContainer');
            const showRegionsSelect = document.getElementById('show_regions');
            let regionId = showRegionsSelect.value;

            $.ajax({
                type: 'GET',
                url: '{{ url('virtial/wall/view') }}' + (regionId ? '/' + regionId : ''),
                data: '_token = <?php echo csrf_token(); ?>',
                success: function(response) {
                    var cameras = JSON.parse(response[0]);
                    var regions = response[1];
                    var first_region_id = regions[0]._id.$oid;

                    // Clear existing cameras
                    videoContainer.innerHTML = '';

                    // Create navigation buttons
                    var navButtons = document.createElement('div');
                    navButtons.className = 'nav-buttons';
                    navButtons.innerHTML = `
                <button id="prevBtn" class="btn btn-primary">&lt; Previous</button>
                <button id="nextBtn" class="btn btn-primary">Next &gt;</button>
            `;
                    videoContainer.appendChild(navButtons);

                    // Create camera grid
                    var cameraGrid = document.createElement('div');
                    cameraGrid.className = 'camera-grid';
                    videoContainer.appendChild(cameraGrid);

                    let currentCameraSet = 0; // Initialize currentCameraSet
                    const camerasPerSet = 4; // Number of cameras per page


                    function displayCameras() {
                        cameraGrid.innerHTML = ''; // Clear previous cameras
                        let start = currentCameraSet * camerasPerSet;
                        let end = Math.min(start + camerasPerSet, cameras.length);

                        for (let i = start; i < end; i++) {

                            let cameraAlarm = cameras[i]['alarm_counts']

                            var ribbonColorClass = 'bg-success' // no alarm detec


                            if (cameraAlarm && cameraAlarm[0]) {


                                if (cameraAlarm[0]['total_black_count'] > 0 || cameraAlarm[0][
                                        'total_blur_count'
                                    ] > 0 || cameraAlarm[0]['total_motion_detect_count'] >
                                    0) {
                                    ribbonColorClass = 'bg-warning'


                                    if (cameraAlarm[0]['total_black_count'] > 0) {

                                        var ulElement = document.getElementById('myList');
                                        var newLiElement = document.createElement('li');
                                        newLiElement.textContent = cameraAlarm[0]['total_black_count'] +
                                            ' Black detected' + " in " + cameras[i]['cameraname'];
                                        ulElement.appendChild(newLiElement);

                                    }

                                    if (cameraAlarm[0]['total_blur_count'] > 0) {

                                        var ulElement = document.getElementById('myList');
                                        var newLiElement = document.createElement('li');
                                        newLiElement.textContent = cameraAlarm[0]['total_blur_count'] +
                                            ' Blur detected' + " in " + cameras[i]['cameraname'];
                                        ulElement.appendChild(newLiElement);

                                    }

                                    if (cameraAlarm[0]['total_motion_detect_count'] > 0) {

                                        var ulElement = document.getElementById('myList');
                                        var newLiElement = document.createElement('li');
                                        newLiElement.textContent = cameraAlarm[0]['total_motion_detect_count'] +
                                            ' Motion detected' + " in " + cameras[i]['cameraname'];
                                        ulElement.appendChild(newLiElement);

                                    }
                                }

                            }




                            let videoWrapper = document.createElement("div");
                            videoWrapper.className =
                                "video-wrapper border border-2 rounded p-1 border-success position-relative"; // Green ribbon box

                            let cameraNameLabel = document.createElement("div");
                            cameraNameLabel.className =
                                "camera-name-label " + ribbonColorClass +
                                " d-flex justify-content-between align-items-center";
                            cameraNameLabel.id = "camera_" + cameras[i]['_id']['$oid'];

                            let leftSection = document.createElement("div");
                            leftSection.className = "d-flex align-items-center";

                            let cameraId = cameras[i]['_id']['$oid'];
                            let redirectRoute = '{{ route('camera.monitor', ':id') }}'.replace(':id',
                                cameraId);


                            // Create Customised Alarm button
                            let customAlarmBtn = document.createElement("a");
                            customAlarmBtn.innerText = "Customised Alarm";
                            customAlarmBtn.className = "btn btn-sm btn-light ml-2";
                            customAlarmBtn.href = redirectRoute;
                            customAlarmBtn.role = "button";
                            customAlarmBtn.addEventListener('click', function(event) {
                                event.preventDefault();
                                window.location.href = this.href;
                            });

                            leftSection.appendChild(customAlarmBtn);
                            cameraNameLabel.appendChild(leftSection);

                            let selectMenu = document.createElement("select");
                            selectMenu.className = "form-select form-select-sm select-series camera-select";
                            selectMenu.style.width = "auto";

                            // Populate the select menu with camera names and video types
                            cameras.forEach((camera) => {
                                let option = document.createElement("option");
                                option.value = camera._id.$oid;
                                option.text = camera.cameraname; // Use the real camera name
                                option.dataset.streamUrl = camera.stream_url;
                                option.dataset.videoType = camera
                                    .video_type; // Store the video type in a data attribute
                                selectMenu.appendChild(option);
                            });

                            selectMenu.value = cameras[i]['_id']['$oid']; // Set the selected camera
                            cameraNameLabel.appendChild(selectMenu);
                            videoWrapper.appendChild(cameraNameLabel);

                            // Create media element based on URL format and video type
                            let mediaElement = createMediaElement(
                                cameras[i]['stream_url'],
                                cameras[i]['video_type'],
                                cameras[i]['_id']['$oid'] // Pass a unique videoContainerId for each camera
                            );
                            videoWrapper.appendChild(mediaElement);

                            // Tooltip creation (conditionally if joined_data exists)
                            if (cameras[i]['joined_data'] && cameras[i]['joined_data'].length > 0) {
                                let joinedData = cameras[i]['joined_data'][0];
                                if (joinedData['info']) {
                                    let info = joinedData['info'];

                                    let tooltipBox = document.createElement("div");
                                    tooltipBox.className =
                                        "tooltip-box position-absolute p-2 bg-light border border-secondary rounded";
                                    tooltipBox.style.display = "none"; // Initially hidden
                                    tooltipBox.style.top = "100%";
                                    tooltipBox.style.left = "0";

                                    tooltipBox.innerHTML = `
                    <strong>Video Format:</strong> ${info['format']['format_long_name']}<br>
                    <strong>Status:</strong> ${cameras[i]['status'] == 1 ? 'Active' : 'Disabled'}<br>
                    <strong>Black Screen:</strong> Yes<br>
                    <strong>Blur Screen:</strong> Yes<br>
                    <strong>Threshold:</strong> ${info['format']['bit_rate'] ? info['format']['bit_rate'] : ''}<br>
                    <strong>Latency:</strong> ${info['latency_seconds'] ? info['latency_seconds'] : ''}
                `;

                                    videoWrapper.appendChild(tooltipBox);

                                    // Show tooltip on hover
                                    videoWrapper.addEventListener('mouseenter', () => {
                                        tooltipBox.style.display = "block";
                                    });

                                    // Hide tooltip on mouse leave
                                    videoWrapper.addEventListener('mouseleave', () => {
                                        tooltipBox.style.display = "none";
                                    });
                                }
                            }

                            // Handle select menu changes
                            selectMenu.addEventListener('change', function(event) {
                                event.stopPropagation();
                                let selectedOption = event.target.options[event.target.selectedIndex];
                                let selectedStreamUrl = selectedOption.dataset.streamUrl;
                                let selectedVideoType = selectedOption.dataset
                                    .videoType; // Retrieve video type from option

                                let mediaElement = event.target.closest('.video-wrapper').querySelector(
                                    'video, img, iframe');
                                if (mediaElement) {
                                    mediaElement.remove(); // Remove existing media element
                                }
                                let newMediaElement = createMediaElement(selectedStreamUrl,
                                    selectedVideoType, cameras[i]['_id']['$oid']
                                ); // Use the retrieved video type
                                event.target.closest('.video-wrapper').appendChild(newMediaElement);
                            });

                            cameraGrid.appendChild(videoWrapper);
                        }

                        // Update button states
                        document.getElementById('prevBtn').disabled = currentCameraSet === 0;
                        document.getElementById('nextBtn').disabled = end >= cameras.length;
                    }





                    document.getElementById('prevBtn').addEventListener('click', function() {
                        if (currentCameraSet > 0) {
                            currentCameraSet--;
                            displayCameras();
                        }
                    });

                    document.getElementById('nextBtn').addEventListener('click', function() {
                        if ((currentCameraSet + 1) * camerasPerSet < cameras.length) {
                            currentCameraSet++;
                            displayCameras();
                        }
                    });

                    displayCameras();

                    // Process regions data and populate the select menu
                    showRegionsSelect.innerHTML = '';
                    populateRegionsSelect(regions, 'region-select');

                    if (regionId) {
                        showRegionsSelect.value = regionId;
                    } else {
                        showRegionsSelect.value = '';
                    }

                    if (!regionId) {
                        populateCamerasSelect(cameras, 'camera-select-preset',
                            first_region_id); // for preset camera dropdown
                    }

                    console.log("Regions data:", regions);

                    // document.getElementById('loading').style.display = "none";
                },
                error: function(xhr, status, error) {
                    // document.getElementById('loading').style.display = "none";
                    console.error(xhr.responseText);
                    console.error(status);
                    console.error(error);
                }
            });
        }








        // ====== SHOW REGIONS IN SELECT MENU   ======
        function populateRegionsSelect(regionsJSON, selectClass) {
            // Parse JSON if it's a string, otherwise use it as is
            var regions = typeof regionsJSON === 'string' ? JSON.parse(regionsJSON) : regionsJSON;

            var selectElements = document.getElementsByClassName(selectClass);

            Array.from(selectElements).forEach(function(select) {
                select.innerHTML = '';

                regions.forEach(function(region) {
                    var option = document.createElement('option');
                    option.value = region._id.$oid || region._id;
                    option.textContent = region.region;
                    select.appendChild(option);
                });

                // Always select the first option
                select.selectedIndex = 0;
            });
        }

        // ====== SHOW CAMERA IN SELECT MENU   ======

        function populateCamerasSelect(camerasJSON, selectClass, regionId = undefined) {
            let lastSelectedIndex = -1;

            var cameras = typeof camerasJSON === 'string' ? JSON.parse(camerasJSON) : camerasJSON;
            var selectElements = document.getElementsByClassName(selectClass);

            Array.from(selectElements).forEach(function(select) {
                select.innerHTML = '';

                // Check if the select element has the 'select-series' class
                const isSeriesSelect = select.classList.contains('select-series');

                // If it's a series select, increment the index
                if (isSeriesSelect) {
                    lastSelectedIndex = (lastSelectedIndex + 1) % cameras.length;
                }

                // Filter cameras by regionId if provided
                var filteredCameras = regionId ? cameras.filter(camera => camera.region_id.$oid === regionId) :
                    cameras;

                filteredCameras.forEach(function(cam, index) {
                    var option = document.createElement('option');
                    option.value = cam._id.$oid || cam._id;
                    option.textContent = cam.cameraname;
                    option.dataset.streamUrl = cam.stream_url;
                    select.appendChild(option);

                    // Set the camera as selected only if it's a series select
                    if (isSeriesSelect && index === lastSelectedIndex) {
                        option.selected = true;
                    }
                });

                // If it's not a series select, don't select any option by default
                if (!isSeriesSelect) {
                    select.selectedIndex = -1;
                }

                // Trigger change event
                var event = new Event('change');
                select.dispatchEvent(event);
            });
        }


        // ====== CHANGE CAMERAS BASED ON REGION   ======
        function sendRegionReq(showRegionsSelect, cameraClass) {

            let regionId = showRegionsSelect;

            $.ajax({
                type: 'GET',
                url: '{{ url('virtial/wall/view') }}' + (regionId ? '/' + regionId : ''),
                data: '_token = <?php echo csrf_token(); ?>',
                success: function(response) {
                    console.log(response);
                    var cameras = JSON.parse(response[0]);
                    // var regions = response[1];

                    populateCamerasSelect(cameras, cameraClass)

                },
                error: function(xhr, status, error) {
                    document.getElementById('loading').style.display = "none";
                    console.error(xhr.responseText);
                    console.error(status);
                    console.error(error);
                }
            });
        }


        // ====== LOAD PRESET ON BTN CLICK   ======
        function loadPreset(preset_id) {
            $.ajax({
                type: 'GET',
                url: '{{ url('virtial/wall/load/preset') }}' + (preset_id ? '/' + preset_id : ''),
                data: '_token = <?php echo csrf_token(); ?>',
                success: function(response) {
                    var cameras = response.cameras || [];
                    var currentCameraSet = 0;
                    var camerasPerSet = 4;

                    var cameraContainer = document.getElementById('videoContainer');
                    if (!cameraContainer) {
                        console.error('Camera container not found.');
                        return;
                    }

                    // Clear existing cameras within the container only
                    cameraContainer.innerHTML = '';

                    // Create navigation buttons
                    var navButtons = document.createElement('div');
                    navButtons.className = 'nav-buttons';
                    navButtons.innerHTML = `
                <button id="prevBtn" class="btn btn-primary">&lt; Previous</button>
                <button id="nextBtn" class="btn btn-primary">Next &gt;</button>
            `;
                    cameraContainer.appendChild(navButtons);

                    // Create camera grid
                    var cameraGrid = document.createElement('div');
                    cameraGrid.className = 'camera-grid';
                    cameraContainer.appendChild(cameraGrid);

                    // Create a dictionary to keep track of select menus
                    var selectMenus = [];

                    function displayCameras() {
                        cameraGrid.innerHTML = ''; // Clear previous cameras
                        let start = currentCameraSet * camerasPerSet;
                        let end = Math.min(start + camerasPerSet, cameras.length);

                        for (let i = start; i < end; i++) {
                            let videoWrapper = document.createElement("div");
                            videoWrapper.className =
                                "video-wrapper border border-2 rounded p-1 border-success position-relative"; // Green ribbon box

                            let cameraNameLabel = document.createElement("div");
                            cameraNameLabel.className =
                                "camera-name-label bg-success d-flex justify-content-between align-items-center";
                            cameraNameLabel.id = "camera_" + cameras[i]['_id']['$oid'];

                            let leftSection = document.createElement("div");
                            leftSection.className = "d-flex align-items-center";

                            let cameraId = cameras[i]['_id']['$oid'];
                            let redirectRoute = '{{ route('camera.monitor', ':id') }}'.replace(':id',
                                cameraId);

                            // Create Customised Alarm button
                            let customAlarmBtn = document.createElement("a");
                            customAlarmBtn.innerText = "Customised Alarm";
                            customAlarmBtn.className = "btn btn-sm btn-light ml-2";
                            customAlarmBtn.href = redirectRoute;
                            customAlarmBtn.role = "button";
                            customAlarmBtn.addEventListener('click', function(event) {
                                event.preventDefault();
                                window.location.href = this.href;
                            });

                            leftSection.appendChild(customAlarmBtn);
                            cameraNameLabel.appendChild(leftSection);

                            let selectMenu = document.createElement("select");
                            selectMenu.className = "form-select form-select-sm select-series camera-select";
                            selectMenu.style.width = "auto";

                            // Populate the select menu with camera names and video types
                            cameras.forEach((camera) => {
                                let option = document.createElement("option");
                                option.value = camera._id.$oid;
                                option.text = camera.cameraname; // Use the real camera name
                                option.dataset.streamUrl = camera.stream_url;
                                option.dataset.videoType = camera
                                    .video_type; // Store the video type in a data attribute
                                selectMenu.appendChild(option);
                            });

                            selectMenu.value = cameras[i]['_id']['$oid']; // Set the selected camera
                            cameraNameLabel.appendChild(selectMenu);
                            videoWrapper.appendChild(cameraNameLabel);

                            // Create media element based on URL format and video type
                            // let mediaElement = createMediaElement(cameras[i]['stream_url'], cameras[i][
                            //     'video_type'
                            // ]);
                            let mediaElement = createMediaElement(
                                cameras[i]['stream_url'],
                                cameras[i]['video_type'],
                                cameras[i]['_id']['$oid'] // Pass a unique videoContainerId for each camera
                            )
                            videoWrapper.appendChild(mediaElement);

                            // Tooltip creation (conditionally if joined_data exists)
                            if (cameras[i]['joined_data'] && cameras[i]['joined_data'].length > 0) {
                                let joinedData = cameras[i]['joined_data'][0];
                                if (joinedData['info']) {
                                    let info = joinedData['info'];

                                    let tooltipBox = document.createElement("div");
                                    tooltipBox.className =
                                        "tooltip-box position-absolute p-2 bg-light border border-secondary rounded";
                                    tooltipBox.style.display = "none"; // Initially hidden
                                    tooltipBox.style.top = "100%";
                                    tooltipBox.style.left = "0";

                                    tooltipBox.innerHTML = `
                    <strong>Video Format:</strong> ${info['format']['format_long_name']}<br>
                    <strong>Status:</strong> ${cameras[i]['status'] == 1 ? 'Active' : 'Disabled'}<br>
                    <strong>Black Screen:</strong> Yes<br>
                    <strong>Blur Screen:</strong> Yes<br>
                    <strong>Threshold:</strong> ${info['format']['bit_rate'] ? info['format']['bit_rate'] : ''}<br>
                    <strong>Latency:</strong> ${info['latency_seconds'] ? info['latency_seconds'] : ''}
                `;

                                    videoWrapper.appendChild(tooltipBox);

                                    // Show tooltip on hover
                                    videoWrapper.addEventListener('mouseenter', () => {
                                        tooltipBox.style.display = "block";
                                    });

                                    // Hide tooltip on mouse leave
                                    videoWrapper.addEventListener('mouseleave', () => {
                                        tooltipBox.style.display = "none";
                                    });
                                }
                            }

                            // Handle select menu changes
                            selectMenu.addEventListener('change', function(event) {
                                event.stopPropagation();
                                let selectedOption = event.target.options[event.target.selectedIndex];
                                let selectedStreamUrl = selectedOption.dataset.streamUrl;
                                let selectedVideoType = selectedOption.dataset
                                    .videoType; // Retrieve video type from option

                                let mediaElement = event.target.closest('.video-wrapper').querySelector(
                                    'video, img, iframe');
                                if (mediaElement) {
                                    mediaElement.remove(); // Remove existing media element
                                }
                                // let newMediaElement = createMediaElement(selectedStreamUrl,
                                //     selectedVideoType); // Use the retrieved video type

                                let newMediaElement = createMediaElement(
                                    selectedStreamUrl,
                                    selectedVideoType,
                                    cameras[i]['_id'][
                                        '$oid'
                                    ] // Pass a unique videoContainerId for each camera
                                )
                                event.target.closest('.video-wrapper').appendChild(newMediaElement);
                            });

                            cameraGrid.appendChild(videoWrapper);
                        }

                        // Update button states
                        document.getElementById('prevBtn').disabled = currentCameraSet === 0;
                        document.getElementById('nextBtn').disabled = end >= cameras.length;
                    }

                    displayCameras();

                    document.getElementById('prevBtn').addEventListener('click', function() {
                        if (currentCameraSet > 0) {
                            currentCameraSet--;
                            displayCameras();
                        }
                    });

                    document.getElementById('nextBtn').addEventListener('click', function() {
                        if ((currentCameraSet + 1) * camerasPerSet < cameras.length) {
                            currentCameraSet++;
                            displayCameras();
                        }
                    });

                    document.getElementById('loading').style.display = "none";
                },
                error: function(xhr, status, error) {
                    document.getElementById('loading').style.display = "none";
                    console.error("An error occurred: " + error);
                }
            });
        }
    </script>
</body>

</html>
