<?php $__env->startSection('content'); ?>
    <div class="container-xxl flex-grow-1 container-p-y">

        <div class="card container ">
            <h5 class="card-header">Attendance Report</h5>
            <div class="table-responsive text-nowrap mt-4">
                <table class="table" id='myDataTable'>
                    <thead>
                        <tr class="text-nowrap">
                            <th>#</th>
                            <th>Person Face</th>
                            <th>Name</th>
                            <th>Camera</th>
                            <th>Region</th>
                            <th>Time</th>
                            <th>Attendance</th>
                            <th>Matched Faces</th>
                        </tr>
                    </thead>
                    <tbody>
                        
                        <?php $__currentLoopData = $records; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <tr>
                                <th scope="row"><?php echo e($loop->iteration); ?></th> <!-- Use $loop->iteration for row number -->
                                <td>
                                    <img src="data:image/png;base64, <?php echo e($item['face_image']); ?>"
                                        style="width: 70px; height: 70px;">
                                </td>
                                <td><?php echo e($item['attendee_name']); ?></td>
                                <td><?php echo e($item['camera_name']); ?></td>
                                <td><?php echo e($item['region_name']); ?></td>
                                <td>
                                    <?php if(isset($item['created_at'])): ?>
                                        <?php echo e($item['created_at']->toDateTime()->format('F j, Y, g:i a')); ?>

                                    <?php else: ?>
                                        <?php echo e(''); ?>

                                    <?php endif; ?>
                                </td>


                                <td>

                                    <?php if($item['is_present'] > 0): ?>
                                        <span>

                                            Present
                                        </span>
                                        <i class="bi bi-check-circle-fill text-success" style="font-size: 1.5rem;"></i>
                                    <?php else: ?>
                                        Absent
                                        <i class="bi bi-x-circle-fill text-danger" style="font-size: 1.5rem;"></i>
                                    <?php endif; ?>
                                </td>

                                <td>
                                    <!-- Button to Open Modal -->
                                    <button type="button" class="btn btn-secondary btn-sm" data-bs-toggle="modal"
                                        <?php if($item['is_present'] == 0): echo 'disabled'; endif; ?> data-bs-target="#exampleModal"
                                        onclick="matchFaces('<?php echo e((string) $item['_id']); ?>')">
                                        View Detail Report
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

                    </tbody>
                </table>
            </div>

            <div class="pagination d-flex justify-content-center container">
                <?php if($page > 1): ?>
                    <a href="<?php echo e(route('stream.frame.detected', ['camera_id' => $camera_id, 'page' => $page - 1])); ?>"
                        class="btn btn-secondary btn-sm mx-1">Previous</a>
                <?php endif; ?>

                
                <?php if($page < $totalPages): ?>
                    <a href="<?php echo e(route('stream.frame.detected', ['camera_id' => $camera_id, 'page' => $page + 1])); ?>"
                        class="btn btn-secondary btn-sm mx-1">Next</a>
                <?php endif; ?>
            </div>

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


        <!-- Modal -->
        <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-xl">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">Detailed Report</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <table class="table">
                            <thead>
                                <tr class="text-nowrap">
                                    <th>#</th>
                                    <th>Person Face</th>
                                    <th>Email</th>
                                    <th>Phone</th>
                                    <th>Address</th>
                                    <th>Camera</th>
                                    <th>Time</th>
                                </tr>
                            </thead>
                            <tbody id="showFaces">
                            </tbody>

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



    </div>



    <script>
        function matchFaces(cameraId) {
            console.log(cameraId);

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


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

                    // console.log(response);


                    // Iterate over the response array to create img elements


                    let count = 1; // Initialize a counter

                    response.forEach(function(item) {
                        // Create a new row for each item
                        var row = $('<tr>');

                        // Add counting cell
                        var countCell = $('<td>').text(count++); // Increment count and set as text
                        row.append(countCell); // Append counting cell to row

                        // Define the keys you want to display, including faceInfo fields
                        var keys = [
                            'face_photo', // Person Face
                            'faceInfo.attendee_email', // Email
                            'faceInfo.attendee_phone_number', // Phone
                            'faceInfo.attendee_address', // Address
                            'camera_name', // Camera
                            'created_at' // Time
                        ];

                        // Loop through each key and create cells
                        keys.forEach(function(key) {
                            var cell = $('<td>');

                            if (key === 'face_photo') {
                                // If the key is face_photo, create an img element
                                var imgElement = $('<img>', {
                                    src: 'data:image/png;base64,' + item[
                                        key], // Set the src attribute
                                    style: 'width: 50px; height: 50px;', // Set styles as needed
                                    alt: 'Matched Face'
                                });
                                cell.append(imgElement); // Append img to cell
                            } else if (key === 'created_at') {
                                // Convert timestamp to a readable date format
                                var timestampInMilliseconds = item[key]['$date'][
                                    '$numberLong'
                                ]; // Accessing the timestamp correctly
                                var date = new Date(parseInt(
                                    timestampInMilliseconds
                                )); // Convert to a number and create Date object

                                if (!isNaN(date.getTime())) { // Check if date is valid
                                    cell.text(date.toLocaleString()); // Format date as needed
                                } else {
                                    cell.text("Invalid Date"); // Handle invalid date case
                                }
                            } else if (key.startsWith('faceInfo.')) {
                                // For faceInfo fields, access them correctly
                                var faceKey = key.split('.')[
                                    1]; // Get the specific field name from faceInfo
                                cell.text(item.faceInfo[
                                    faceKey]); // Set text content from faceInfo object
                            } else {
                                // For other keys, just set the text content
                                cell.text(item[key]);
                            }

                            row.append(cell); // Append cell to row
                        });

                        // Append the row to the tbody of the table with id showFaces
                        $('#showFaces').append(row); // Correctly appending to tbody with ID showFaces
                    });

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


                },
                error: function(xhr, status, error) {
                    // Handle any errors here
                    console.error('Error:', status, error);
                }
            });
        }




        $(document).ready(function() {
            $('#myDataTable').DataTable({
                searching: true,
                ordering: true,
                info: false,
                lengthChange: false, // This line hides the entries dropdown
                pageLength: 10, // Optional: Set default number of entries per page
                "order": [], // Disable initial sorting
                "columnDefs": [{
                        "orderable": true,
                        "targets": "_all"
                    }, // Make all columns orderable
                    {
                        "type": "string",
                        "targets": "_all"
                    } // Treat all column data as strings for sorting
                ],
                language: {
                    paginate: {
                        previous: "<i class='fas fa-angle-left'></i>", // Icon for previous button
                        next: "<i class='fas fa-angle-right'></i>" // Icon for next button
                    }
                }
            });

            // $("#searchCamera").on('change', function() {
            //     $('#myDataTable').DataTable().column(1).search(
            //         $(this).val(),
            //         false, // regex
            //         true // smart search
            //     ).draw();
            // });

            // $("#searchRegion").on('change', function() {
            //     $('#myDataTable').DataTable().column(2).search(
            //         $(this).val(),
            //         false, // regex
            //         true // smart search
            //     ).draw();
            // });

            // $("#searchUrl").on('keyup', function() {
            //     $('#myDataTable').DataTable().column(3).search(
            //         $(this).val(),
            //         false, // regex
            //         true // smart search
            //     ).draw();
            // });
        });
    </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/report.blade.php ENDPATH**/ ?>