@extends('layouts.master')
@section('content')

@section('css')
    <style>
        video {
            border: 2px solid #333;
            border-radius: 10px;
            /* width: 80%;
                                                                                                                                                                                                                                max-width: 640px; */
        }

        input[type="radio"] {
            width: 25px;
            height: 25px;
        }

        #show_extract_faces {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
        }

        #show_extract_faces img {
            margin: 10px;
            width: 100px;
            height: 100px;
        }

        #show_extract_faces img:nth-child(10n+1) {
            clear: both;
        }
    </style>
@endsection

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

    <div class="card">
        <h5 class="card-header" style="color:rgb(255, 255, 255);">Add Attendee</h5>
        <div class="table-responsive text-nowrap">
            <form action="{{ route('faces.add.post') }}" method="POST" enctype="multipart/form-data">
                @csrf
                <input type="hidden" value="{{ $camera_id }}" name="camera_id">

                <div class="row" style="margin: 10px;">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Attendee Name*</label>
                            <input type="text" class="form-control" name="attendee_name" required />
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Attendee Email</label>
                            <input type="text" class="form-control" name="attendee_email" required />
                        </div>
                    </div>
                </div>
                <div class="row" style="margin: 10px;">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Attendee Phone Number</label>

                            <input type="text" class="form-control" name="attendee_phone_number" required />
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Attendee Address</label>
                            <input type="text" class="form-control" name="attendee_address" required />
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Region Name</label>
                            <input type="text" value="{{ $region['region'] ?? '' }}" class="form-control" disabled />



                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Camera Name</label>
                            <input type="text" value="{{ $camera['cameraname'] ?? '' }}" class="form-control"
                                disabled />
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Streaming URL</label>

                            <input type="text" disabled placeholder="Enter Stream URL" class="form-control"
                                name="stream_url" id="stream_url" value="{{ $camera['stream_url'] }}"
                                style="background-color: rgba(211, 211, 211, 0.5); color: white;" />
                        </div>
                    </div>
                    <div class="col-md-12">
                        <div class="form-group">
                            <div class="row" style="display: block;text-align: center;">
                                <button style=" width: 200px; margin: 38px; " type="button" id="capture_steam"
                                    class="btn btn-info">Capture Video</button>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row" style=" margin-left: 26px; margin-top: 29px; margin-bottom: 21px; ">
                    {{-- <div class="form-check" style="width: auto">
                        <input class="form-check-input" type="radio" value="direct" name="image_source"
                            id="flexRadioDefault1">
                        <label class="form-check-label" for="flexRadioDefault1">
                            Upload Upload
                        </label>
                    </div>
                    <div class="form-check" style="width: auto">
                        <input class="form-check-input" type="radio" value="camera" name="image_source"
                            id="flexRadioDefault2">
                        <label class="form-check-label" for="flexRadioDefault2">
                            Take Picture
                        </label>
                    </div> --}}
                    {{-- <div class="form-check" style="width: auto">
                        <input class="form-check-input" type="radio" value="capture_stream" name="image_source"
                            id="flexRadioDefault3">
                        <label class="form-check-label" for="flexRadioDefault3">
                            Capture Faces
                        </label>
                    </div> --}}
                </div>
                {{-- Capture face from Camera --}}

                <div class="row" id="camera_layout" style="display: none;">
                    <div class="col-md-6" style=" padding: 38px; ">
                        <video id="camera" autoplay playsinline></video>
                        <canvas id="snapshot" style="display:none;"></canvas>
                    </div>
                    <div class="col-md-2" style="align-items: center;align-content: center;">
                        <button id="take-photo" class="btn btn-warning" type="button" style="width: 163px;">Take
                            Photo</button>
                    </div>
                    <div class="col-md-4" style=" align-items: center; align-content: center; ">
                        <img id="face_image"
                            style=" border: 2px solid #989797; border-radius: 13px; width: 200px; height: 200px; " />
                        <input type="hidden" name="face_image_base64" id="face_image_base64" />

                    </div>
                </div>


                <div class="row justify-content-center" id="camera_layout" style="display: none;">
                    <div class="col-md-6 d-flex flex-column align-items-center justify-content-center"
                        style="padding: 38px;">
                        <div class="text-center">
                            <video id="camera" autoplay playsinline
                                style="border: 2px solid #989797; border-radius: 13px; width: 200px; height: 200px;"></video>
                            <canvas id="snapshot" style="display:none;"></canvas>
                        </div>
                        <div class="text-center text-warning">
                            please keep your face in front of camera
                        </div>
                        <div class="mt-3">
                            <button id="take-photo" class="btn btn-secondary btn-sm" type="button">Take Photo</button>
                        </div>
                    </div>
                    <div class="col-md-6 d-flex flex-column align-items-center justify-content-center"
                        style="margin-bottom: 45px;">
                        <img id="face_image"
                            style="border: 2px solid #989797; border-radius: 13px; width: 200px; height: 200px;" />
                        <input type="hidden" name="face_image_base64" id="face_image_base64" />
                    </div>
                </div>

                {{-- Face  Upload layout --}}
                <div class="row" style="margin: 10px;display: none;" id="upload_layout">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label>Upload Face</label>
                            <input type="file" value="" placeholder="Upload face" class="form-control"
                                name="face_image" />

                        </div>
                    </div>
                </div>

                {{-- Canpture From Video Stream --}}

                <div class="row" style="margin: 10px;display: block;" id="capture_stream_layout">
                    {{-- <div class="col-md-12">
                        <div class="form-group">
                            <label>Streaming URL</label>

                            <input type="text" disabled placeholder="Enter Stream URL" class="form-control"
                                name="stream_url" id="stream_url" value="{{ $camera['stream_url'] }}"
                                style="background-color: rgba(211, 211, 211, 0.5); color: white;" />
                            <div class="row" style="display: block;text-align: center;">
                                <button style=" width: 200px; margin: 38px; " type="button" id="capture_steam"
                                    class="btn btn-info">Capture</button>
                            </div>
                        </div>
                    </div> --}}

                    {{-- <div class="row" id="capture_video_url_layout" style="display: none;">
                        <div class="col-md-6">
                            <video id="videoStream" width="540" height="260" controls muted>
                                <source type="video/mp4">
                                Your browser does not support the video tag.
                            </video>
                            <div class="row" style="display: block;text-align: center;">
                                <button type="button" style="width: 200px; " class="btn btn-warning"
                                    id="captureBtn">Extract
                                    Frame</button>

                            </div>
                        </div>
                        <div class="col-md-6">
                            <canvas id="canvas_video" style="width: 100%"></canvas>
                        </div>
                    </div> --}}


                    <div class="row" id="capture_video_url_layout"
                        style="display: flex; align-items: center; justify-content: center; display:none;">
                        <div
                            style="flex: 1; padding: 10px; display: flex; flex-direction: column; align-items: center;">
                            <video id="videoStream" style="width: 100%; height: auto;" controls muted>
                                <source type="video/mp4">
                                Your browser does not support the video tag.
                            </video>
                            <div style="text-align: center; margin-top: 10px;">
                                <button type="button" style="width: 200px;" class="btn btn-secondary"
                                    id="captureBtn">Extract Faces</button>
                            </div>
                        </div>
                        <div
                            style="flex: 1; padding: 10px; display: flex; flex-direction: column; align-items: center;">
                            <canvas id="canvas_video" style="width: 100%; height: auto; margin-bottom:50px;"></canvas>
                            <input type="hidden" name="face_image_base64_capture" id="face_image_base64_capture" />

                        </div>
                        <div class="text-center">
                            <h3 id="show_extract_faces_heading"></h3>
                            <div class="d-flex justify-content-center">
                                <h4 id="show_extract_faces_status"
                                    style="color: rgb(255, 255, 255); text-shadow: 0 0 10px white, 0 0 20px white, 0 0 30px white; animation: blink 1.5s infinite;">
                                </h4>
                            </div>
                            <div id="show_extract_faces" class="d-flex justify-content-center">
                            </div>
                        </div>
                    </div>



                </div>

                <div class="row" style="margin: 50px;display: block;text-align: center;;">
                    <a href="{{ route('faces.all') }}" style="width:150px;" type="submit"
                        class="btn btn-secondary">
                        View
                        all faces
                    </a>
                    <input style="width:150px;" type="submit" value="Submit" class="btn btn-primary" />
                </div>

            </form>

        </div>

    </div>


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


</div>
</div>
</div>

{{-- @section('js') --}}
<script>
    function getExtractFaces(photoFrameBase64) {

        var showExtractFaces_heading = document.getElementById('show_extract_faces_heading');
        showExtractFaces_heading.textContent = "Extracted Faces"

        var showExtractFaces_status = document.getElementById('show_extract_faces_status');
        showExtractFaces_status.textContent = "Extracting faces. Please wait ..."

        const csrfToken = "{{ csrf_token() }}"; // Directly set the CSRF token
        fetch('{{ route('extact_frame_faces') }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                },
                body: JSON.stringify({
                    photo_frame_base64: photoFrameBase64
                })
            })
            .then(response => response.json())
            .then(response => {
                // console.log(response);

                showExtractFaces_status.textContent = "";

                const showExtractFaces = document.getElementById('show_extract_faces');

                function highlightImage(event) {
                    const images = document.querySelectorAll('#show_extract_faces img');
                    images.forEach(img => img.style.border = 'none');
                    event.target.style.border = '2px solid red';
                    document.getElementById('face_image_base64_capture').value = event.target.src.split(',')[1];
                }
// console.log(response.data);
                if (response.data && Array.isArray(response.data)) {
                    response.data.forEach(base64Str => {
                        const img = new Image();
                        img.src = 'data:image/jpeg;base64,' + base64Str;
                        img.onclick = highlightImage;
                        showExtractFaces.appendChild(img);
                    });
                    console.log('Success:', response);
                } else if (response.error) {
                    // Handle the error response
                    // showExtractFaces_status.textContent = response.message;
                    alert(response.message); // Show the error message in an alert

                }
            })
            .catch((error) => {
                console.error('Error:', error);
                showExtractFaces_status.textContent = "Face not found. Please try again !!!";
            });
    }



    const video = document.getElementById('camera');
    const takePhotoButton = document.getElementById('take-photo');
    const canvas = document.getElementById('snapshot');
    const context = canvas.getContext('2d');
    videoStream = document.getElementById("videoStream");
    canvas_video = document.getElementById("canvas_video");

    const context1 = canvas_video.getContext('2d');
    context1.crossOrigin = 'anonymous'; // Add this line
    // Start the camera
    async function startCamera() {
        try {
            const stream = await navigator.mediaDevices.getUserMedia({
                video: true
            });
            // navigator.mediaDevices.enumerateDevices()
            //   .then(devices => {
            //     devices.forEach(device => {
            //       console.log(`${device.kind}: ${device.label} (ID: ${device})`);
            //     });
            //   })
            //   .catch(error => {
            //     console.error("Error enumerating devices:", error);
            //   });
            video.srcObject = stream;
        } catch (error) {
            console.error('Error accessing the camera:', error);
            alert('Unable to access the camera. Please allow camera access and try again.');
        }
    }

    // Take a photo
    takePhotoButton.addEventListener('click', () => {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        // Convert canvas to image and display in a new tab
        const imageUrl = canvas.toDataURL('image/png');
        console.log(imageUrl);
        document.getElementById("face_image").src = imageUrl;
        document.getElementById("face_image_base64").value = imageUrl;

        // const newWindow = window.open();
        // newWindow.document.write(`<img src="${imageUrl}" alt="Snapshot">`);
    });

    // Start the camera when the page loads
    // window.addEventListener('load', );

    const radios = document.querySelectorAll('input[name="image_source"]');

    // Add event listeners to all radio buttons in the group
    radios.forEach((radio) => {
        radio.addEventListener("change", (event) => {
            value = event.target.value;
            if (value == "direct") {
                document.getElementById("capture_stream_layout").style.display = "none";
                document.getElementById("camera_layout").style.display = "none";
                document.getElementById("upload_layout").style.display = "block";

            } else if (value == "camera") {
                document.getElementById("camera_layout").style.display = "flex";
                document.getElementById("upload_layout").style.display = "none";
                document.getElementById("capture_stream_layout").style.display = "none";
                startCamera();
            } else if (value == "capture_stream") {
                document.getElementById("camera_layout").style.display = "none";
                document.getElementById("upload_layout").style.display = "none";
                document.getElementById("capture_stream_layout").style.display = "block";

            }
        });
    });


    document.getElementById("capture_steam").addEventListener('click', function() {
        var url = document.getElementById("stream_url").value;
        if (url) {
            document.getElementById("capture_video_url_layout").style.display = "flex";

            var videoStream = document.getElementById("videoStream");
            if (videoStream) {
                videoStream.src = "{{ route('proxy_video') }}?url=" + url;
            } else {
                console.log("videoStream element is null");
            }
        } else {
            alert("Please enter stream url");
        }
    });




    // document.getElementById("capture_steam").addEventListener('click', function() {
    //     url = document.getElementById("stream_url").value;
    //     if (url) {
    //         document.getElementById("capture_video_url_layout").style.display = "flex";
    //         videoStream.src = url;
    //     } else {
    //         alert("Please enter stream url");
    //     }
    // });

    // document.getElementById("captureBtn").addEventListener('click', function() {
    //     videoStream.pause();
    //     // const canvas = document.getElementById('yourCanvasId')
    //     // Draw the current video frame onto the canvas
    //     context1.drawImage(videoStream, 0, 0, canvas.width, canvas.height);
    //     // Optionally, you can save the captured frame as an image
    //     const dataUrl = canvas.toDataURL(); // This is a base64-encoded image
    //     console.log(dataUrl); // Log the captured image data URL
    //     document.getElementById('face_image_base64_capture').value = dataUrl;
    // });


    document.getElementById("captureBtn").addEventListener('click', function() {
        videoStream.pause();
        // Draw the current video frame onto the canvas
        context1.drawImage(videoStream, 0, 0, canvas_video.width, canvas_video.height);
        // Optionally, you can save the captured frame as an image
        const dataUrl = canvas_video.toDataURL('image/jpeg'); // This is a base64-encoded image
        console.log(dataUrl); // Log the captured image data URL
        getExtractFaces(dataUrl);

    });
</script>
{{-- @endsection --}}

@endSection
