<?php $__env->startSection('content'); ?>
    <style>
        select option {
            background-color: #007bff !important;
            color: white !important;
        }


        table {
            transform: scale(1);
            transform-origin: top left;
        }


        table.dataTable thead .sorting,
        table.dataTable thead .sorting_asc,
        table.dataTable thead .sorting_desc,
        table.dataTable thead .sorting_asc_disabled,
        table.dataTable thead .sorting_desc_disabled {
            background-image: url('https://cdn.datatables.net/1.10.24/images/sort_both.png');
            background-repeat: no-repeat;
            background-position: center right;
            cursor: pointer;
        }

        table.dataTable thead .sorting_asc {
            background-image: url('https://cdn.datatables.net/1.10.24/images/sort_asc.png');
        }

        table.dataTable thead .sorting_desc {
            background-image: url('https://cdn.datatables.net/1.10.24/images/sort_desc.png');
        }

        /* Remove hover-only display */
        table.dataTable thead>tr>th.sorting:before,
        table.dataTable thead>tr>th.sorting:after,
        table.dataTable thead>tr>th.sorting_asc:before,
        table.dataTable thead>tr>th.sorting_asc:after,
        table.dataTable thead>tr>th.sorting_desc:before,
        table.dataTable thead>tr>th.sorting_desc:after,
        table.dataTable thead>tr>th.sorting_asc_disabled:before,
        table.dataTable thead>tr>th.sorting_asc_disabled:after,
        table.dataTable thead>tr>th.sorting_desc_disabled:before,
        table.dataTable thead>tr>th.sorting_desc_disabled:after {
            opacity: 1 !important;
        }
    </style>

    <div class="container-xxl flex-grow-1 container-p-y">

        <div class="card" style="display: grid;height: 100%;">
            <div class="card-header">
                <h4 class="card-title">Object Counter Detail
                </h4>
            </div>

            


            <div class="table-responsive text-nowrap container">
                <h3 class="my-3">People Count Detail</h3>
                <table class="display table " id="peopleCountTable">
                    <thead>
                        <tr class="text-nowrap">
                            <th>#</th>
                            <th>Frame</th>
                            <th>Camera Name</th>
                            <th>Region Name</th>
                            <th>No Of Detected People</th>
                            <th>Timestamp</th>
                            <th>View People</th>

                        </tr>
                    </thead>
                    <tbody>

                    </tbody>
                </table>



                <div id="paginationContainer_people" class="pagination-buttons d-flex justify-content-center">
                    <!-- Pagination buttons will be appended here -->
                </div>
            </div>

            <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="exampleModalLabel">Detected Peoples</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <div class="row d-flex">
                                <div class="col-md-6">
                                    <h3 class="text-center">Source Image</h3>
                                    <div id="showFrame" class=" d-flex justify-content-center">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <h3 class="text-center">Detected Faces</h3>

                                    <div id="showFaces" class=" d-flex justify-content-center flex-wrap">
                                        Fetching records....
                                    </div>
                                </div>
                            </div>

                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            </div>




            


            <div class="table-responsive text-nowrap container">
                <h3 class="my-3">Detected Objects</h3>
                <table class="display table " id="objectCountTable">
                    <thead>
                        <tr class="text-nowrap">
                            <th>#</th>
                            <th>Frame</th>
                            <th>Camera Name</th>
                            <th>Region Name</th>
                            <th>Class Name</th>
                            <th>Confidence</th>
                            <th>Timestamp</th>
                            <th>View Frame</th>

                        </tr>
                    </thead>
                    <tbody>

                    </tbody>
                </table>


                <div id="paginationContainer_object" class="pagination-buttons d-flex justify-content-center">
                    <!-- Pagination buttons will be appended here -->
                </div>

            </div>

        </div>


        <div class="modal fade" id="modalCenter2" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered  modal-md" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="modalCenterTitle">Object Details</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            
                            <div id="showFrame_object" class="d-flex justify-content-center">
                            </div>
                            
                        </div>
                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                            Close
                        </button>
                    </div>
                </div>
            </div>
        </div>



        <div class="row" style=" text-align: center; display: block; margin-top: 100px; margin-bottom: 65px; ">
        </div>



        <!-- Modal -->


    </div>


    <script>
        function viewAttendee(frame_id, frame_img = "") {
            console.log(frame_id);


            $.ajax({
                url: '<?php echo e(route('attendance.object_counter_view_attendee', ':id')); ?>'.replace(':id',
                    frame_id), // Replace ':id' with the actual faceId
                type: 'GET', // or 'POST' if your route expects a POST request

                success: function(response) {
                    // Clear the #showFaces div before appending new images
                    $('#showFaces').empty();
                    $('#showFrame').empty();



                    // var frmaeImgElement = $('<img>', {
                    //     src: 'data:image/png;base64,' + frame_img, // Set the src attribute
                    //     style: 'width: 180px; height: 180px;', // Set styles as needed
                    // });

                    new_tab_img_url = `data:image/png;base64,${frame_img}`
                    var frmaeImgElement = $('<a>', {
                        href: new_tab_img_url, // Set the href to the image source
                        target: '_blank' // Open in a new tab
                    }).append($('<img>', {
                        src: 'data:image/png;base64,' + frame_img, // Set the src attribute
                        style: 'width: 180px; height: 180px;', // Set styles as needed
                    }));


                    // Append the img element to the #showFaces div
                    $('#showFrame').append(frmaeImgElement);

                    // Assuming 'response' is your array containing base64 image strings
                    
                    response.forEach(function(item) {
                        // Create a new img element for each detected_face_frame
                        var imgElement = $('<img>', {
                            src: 'data:image/png;base64,' + item
                                .detected_face_frame, // Set the src attribute
                            style: 'width: 100px; height: 100px; margin: 5px;', // Set styles as needed
                            alt: 'Matched Face'
                        });

                        // Append the img element to the #showFaces div
                        $('#showFaces').append(imgElement);
                    });

                },
                error: function(xhr, status, error) {
                    // Handle any errors here
                    console.error('Error:', status, error);
                    $('#showFaces').html(
                        'Face not found !!!');
                    $('#showFrame').empty();


                }
            });
        }


        $(document).ready(function() {
            $('#exampleModal').on('hidden.bs.modal', function() {
                $('#showFaces').html(
                    'Fetching records. please wait ....'); // Clear the inner HTML of the div
                $('#showFrame').empty();

            });
        });


        document.getElementById('modalCenter2').addEventListener('show.bs.modal', (e) => {
            var jsonData = e.relatedTarget.dataset.data;
            var frameImgData = e.relatedTarget.dataset.frameImg;

            $('#showFrame_object').empty();

            // Check if frameImgData is not empty
            if (frameImgData) {
                // Create an img tag and set the source to base64 data with PNG format
                var imgElement = document.createElement('img');
                imgElement.src = `data:image/png;base64,${frameImgData}`;

                // Set the image size
                imgElement.style.width = '400px';
                imgElement.style.height = '200px';

                // Append the img tag to the showFrame_object div
                document.getElementById('showFrame_object').appendChild(imgElement);
            } else {
                console.error('Invalid base64 image data');
            }

            // Parse jsonData since it's JSON formatted
            // populateTable(JSON.parse(jsonData));
        });











        function populateTable(data) {
            const tableBody = document.getElementById('table-body');
            tableBody.innerHTML = '';

            data.forEach(item => {
                const row = document.createElement('tr');
                row.innerHTML = `
                <td>${item.class}</td>
                <td>${item.confidence * 100} %</td>

            `;
                tableBody.appendChild(row);
            });
        }



        // ~~~ people counter ~~~ //


        document.addEventListener('DOMContentLoaded', function() {
            // let cameraId = 1; // Set your camera_id here
            let page = 1; // Set your page number here if required

            function fetchData(page) {
                let route = `<?php echo e(route('attendance.object_counter_detail', $camera['_id'])); ?>/${page}`;

                // Show fetching message
                let tableBody1 = document.getElementById('peopleCountTable').getElementsByTagName('tbody')[0];
                tableBody1.innerHTML = '<tr><td colspan="7">Fetching records...</td></tr>';

                fetch(route, {
                        method: 'GET',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.records) {
                            console.log(route);

                            tableBody1.innerHTML = ''; // Clear fetching message

                            data.records.forEach((item, index) => {
                                // For the first table 'peopleCountTable'
                                let row1 = tableBody1.insertRow();

                                // Row number
                                let cell1_1 = row1.insertCell(0);
                                cell1_1.textContent = index + 1 + ((page - 1) * data.records
                                    .length); // Proper row number

                                // Image
                                // let cell1_2 = row1.insertCell(1);
                                // let img1 = document.createElement('img');
                                // img1.src = `data:image/png;base64,${item.frame_img_count_base64}`;
                                // img1.style.width = '50px';
                                // img1.style.height = '50px';
                                // cell1_2.appendChild(img1);


                                let cell1_2 = row1.insertCell(1);
                                let anchor = document.createElement('a'); // Create the anchor tag
                                let imgSrc = `data:image/png;base64,${item.frame_img_count_base64}`;
                                anchor.href = imgSrc; // Set the href to the image source
                                anchor.target = '_blank'; // Open in a new tab

                                let img1 = document.createElement('img');
                                img1.src = imgSrc;
                                img1.style.width = '50px';
                                img1.style.height = '50px';

                                // Append the image to the anchor, then append the anchor to the cell
                                anchor.appendChild(img1);
                                cell1_2.appendChild(anchor);



                                // Camera name
                                let cell1_3 = row1.insertCell(2);
                                cell1_3.textContent = "<?php echo e($camera['cameraname']); ?>" ?? '';

                                // Region
                                let cell1_4 = row1.insertCell(3);
                                cell1_4.textContent = "<?php echo e($region['region']); ?>" ?? '';

                                // Detected people count
                                let cell1_5 = row1.insertCell(4);
                                cell1_5.classList.add('text-center');
                                cell1_5.textContent = item.detected_people_count ?? 0;

                                // Frame time
                                let cell1_6 = row1.insertCell(5);
                                let frameTime1 = item.frame_time?.$date?.$numberLong;
                                cell1_6.textContent = frameTime1 ? new Date(parseInt(frameTime1))
                                    .toLocaleString() : '';

                                // View button
                                let cell1_7 = row1.insertCell(6);
                                let viewButton1 = document.createElement('a');
                                viewButton1.className = 'btn btn-secondary btn-sm';
                                viewButton1.setAttribute('data-bs-toggle', 'modal');
                                viewButton1.setAttribute('data-bs-target', '#exampleModal');
                                viewButton1.textContent = 'View';
                                viewButton1.onclick = function() {
                                    viewAttendee(item._id.$oid, item.frame_img_count_base64);
                                };
                                cell1_7.appendChild(viewButton1);
                            });

                            // Add pagination buttons
                            let paginationContainer_people = document.getElementById(
                                'paginationContainer_people');
                            paginationContainer_people.innerHTML = ''; // Clear existing pagination buttons

                            // Previous button
                            let prevButton = document.createElement('button');
                            prevButton.textContent = 'Previous';
                            prevButton.className = 'btn btn-secondary pagination-button btn-sm mx-1';
                            prevButton.disabled = page === 1; // Disable if on the first page
                            prevButton.onclick = function() {
                                if (page > 1) {
                                    fetchData(page - 1);
                                }
                            };
                            paginationContainer_people.appendChild(prevButton);

                            // Next button
                            let nextButton = document.createElement('button');
                            nextButton.textContent = 'Next';
                            nextButton.className = 'btn btn-secondary pagination-button btn-sm mx-1';
                            nextButton.disabled = page === data.totalPages; // Disable if on the last page
                            nextButton.onclick = function() {
                                if (page < data.totalPages) {
                                    fetchData(page + 1);
                                }
                            };
                            paginationContainer_people.appendChild(nextButton);
                        }
                    })
                    .catch((error) => {
                        console.error('Error:', error);
                    });
            }

            // Initial fetch
            fetchData(page);
        });


        // ~~~ object counter ~~~ //

        document.addEventListener('DOMContentLoaded', function() {
            // let cameraId = 1; // Set your camera_id here
            let page = 1; // Set your page number here if required

            function fetchData(page) {
                // let route = `<?php echo e(route('attendance.object_counter_detail', $camera['_id'])); ?>?page=${page}`;
                let route = `<?php echo e(route('attendance.object_counter_detail', $camera['_id'])); ?>/${page}`;


                // Show fetching message
                let tableBody2 = document.getElementById('objectCountTable').getElementsByTagName('tbody')[0];
                tableBody2.innerHTML = '<tr><td colspan="6">Fetching records...</td></tr>';

                fetch(route, {
                        method: 'GET',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.records) {
                            tableBody2.innerHTML = ''; // Clear fetching message

                            // data.records.forEach((item, index) => {
                            //     // For the second table 'objectCountTable'
                            //     let row2 = tableBody2.insertRow();

                            //     // Row number
                            //     let cell2_1 = row2.insertCell(0);
                            //     cell2_1.textContent = index + 1 + ((page - 1) * data.records
                            //         .length); // Proper row number

                            //     // Image
                            //     let cell2_2 = row2.insertCell(1);
                            //     let img2 = document.createElement('img');
                            //     img2.src = `data:image/png;base64,${item.frame_img_base64}`;
                            //     img2.style.width = '50px';
                            //     img2.style.height = '50px';
                            //     cell2_2.appendChild(img2);

                            //     // Camera name
                            //     let cell2_3 = row2.insertCell(2);
                            //     cell2_3.textContent = "<?php echo e($camera['cameraname']); ?>" ?? '';

                            //     // Region
                            //     let cell2_4 = row2.insertCell(3);
                            //     cell2_4.textContent = "<?php echo e($region['region']); ?>" ?? '';

                            //     // Frame time
                            //     let cell2_5 = row2.insertCell(4);
                            //     let frameTime2 = item.frame_time?.$date?.$numberLong;
                            //     cell2_5.textContent = frameTime2 ? new Date(parseInt(frameTime2))
                            //         .toLocaleString() : '';

                            //     // View button
                            //     let cell2_6 = row2.insertCell(5);
                            //     let viewButton2 = document.createElement('a');
                            //     viewButton2.className = 'btn btn-secondary btn-sm';
                            //     viewButton2.setAttribute('data-bs-toggle', 'modal');
                            //     viewButton2.setAttribute('data-bs-target', '#modalCenter2');
                            //     viewButton2.textContent = 'View';
                            //     viewButton2.setAttribute('data-data', JSON.stringify(item.objectInfo));
                            //     viewButton2.setAttribute('data-frame-img', item.frame_img_base64);
                            //     cell2_6.appendChild(viewButton2);
                            // });


                            let count = 1; // Initialize counter outside the loop

                            data.records.forEach((item, index) => {
                                item.objectInfo.forEach((objectInfo, objIndex) => {
                                    let objRow = tableBody2.insertRow();

                                    // Proper row number
                                    let objCell2_1 = objRow.insertCell(0);
                                    objCell2_1.textContent = count++; // Increment the counter

                                    // Image
                                    let objCell2_2 = objRow.insertCell(1);
                                    let objImg2 = document.createElement('img');
                                    objImg2.src =
                                        `data:image/png;base64,${item.frame_img_base64}`;
                                    objImg2.style.width = '50px';
                                    objImg2.style.height = '50px';
                                    objCell2_2.appendChild(objImg2);

                                    // Camera name
                                    let objCell2_3 = objRow.insertCell(2);
                                    objCell2_3.textContent = "<?php echo e($camera['cameraname']); ?>" ??
                                        '';

                                    // Region
                                    let objCell2_4 = objRow.insertCell(3);
                                    objCell2_4.textContent = "<?php echo e($region['region']); ?>" ?? '';

                                    // ObjectInfo class name
                                    let objCell2_5 = objRow.insertCell(4);
                                    objCell2_5.textContent = objectInfo.class;

                                    // ObjectInfo confidence
                                    let objCell2_6 = objRow.insertCell(5);
                                    let confidence = objectInfo.confidence.toFixed(4);
                                    objCell2_6.textContent = (confidence * 100).toFixed(4) +
                                        " %";

                                    // Frame time
                                    let objCell2_7 = objRow.insertCell(6);
                                    let frameTime2 = item.frame_time?.$date?.$numberLong;
                                    objCell2_7.textContent = frameTime2 ? new Date(parseInt(
                                        frameTime2)).toLocaleString() : '';

                                    // View button
                                    let objCell2_8 = objRow.insertCell(7);
                                    let viewButton2 = document.createElement('a');
                                    viewButton2.className = 'btn btn-secondary btn-sm';
                                    viewButton2.setAttribute('data-bs-toggle', 'modal');
                                    viewButton2.setAttribute('data-bs-target', '#modalCenter2');
                                    viewButton2.textContent = 'View';
                                    viewButton2.setAttribute('data-data', JSON.stringify(item
                                        .objectInfo));
                                    viewButton2.setAttribute('data-frame-img', item
                                        .frame_img_base64);
                                    objCell2_8.appendChild(viewButton2);
                                });
                            });




                            // Add pagination buttons
                            let paginationContainer_object = document.getElementById(
                                'paginationContainer_object');
                            paginationContainer_object.innerHTML = ''; // Clear existing pagination buttons

                            // Previous button
                            let prevButton = document.createElement('button');
                            prevButton.textContent = 'Previous';
                            prevButton.className = 'btn btn-secondary pagination-button btn-sm mx-1';
                            prevButton.disabled = page === 1; // Disable if on the first page
                            prevButton.onclick = function() {
                                if (page > 1) {
                                    fetchData(page - 1);
                                }
                            };
                            paginationContainer_object.appendChild(prevButton);

                            // Next button
                            let nextButton = document.createElement('button');
                            nextButton.textContent = 'Next';
                            nextButton.className = 'btn btn-secondary pagination-button btn-sm mx-1';
                            nextButton.disabled = page === data.totalPages; // Disable if on the last page
                            nextButton.onclick = function() {
                                if (page < data.totalPages) {
                                    fetchData(page + 1);
                                }
                            };
                            paginationContainer_object.appendChild(nextButton);
                        }
                    })
                    .catch((error) => {
                        console.error('Error:', error);
                    });
            }

            // Initial fetch
            fetchData(page);
        });
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.master', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH C:\xampp\htdocs\surveillance\resources\views/attendance/object_counter_detail.blade.php ENDPATH**/ ?>