@extends('layouts.master_two')
@section('content')
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <style>
        #canvas {
            border: 1px solid black;
        }

        /* Custom styles for the range input */
        input[type="range"] {
            -webkit-appearance: none;
            width: 100%;
            height: 8px;
            border-radius: 5px;
            background: #ddd;
            outline: none;
            opacity: 0.7;
            -webkit-transition: .2s;
            transition: opacity .2s;
        }

        input[type="range"]::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 25px;
            height: 25px;
            border-radius: 50%;
            background: #007bff;
            /* Bootstrap primary color */
            cursor: pointer;
        }

        input[type="range"]::-moz-range-thumb {
            width: 25px;
            height: 25px;
            border-radius: 50%;
            background: #007bff;
            /* Bootstrap primary color */
            cursor: pointer;
        }

        input[type="range"]::-ms-thumb {
            width: 25px;
            height: 25px;
            border-radius: 50%;
            background: #007bff;
            /* Bootstrap primary color */
            cursor: pointer;
        }
    </style>

    <style>
        /* This will ensure that the video is displayed in its actual size */
        video {
            display: block;
            max-width: none;
            width: auto;
            /* Let the video width be auto so it adjusts to its actual resolution */
            height: auto;
            /* Let the video height be auto so it adjusts to its actual resolution */
        }
    </style>
    <style>
        .video-container {
            position: relative;
            display: inline-block;
        }

        video {
            display: block;
            width: 100%;
            /* Ensure the video fits within its container */
        }

        canvas {
            position: absolute;
            top: 0;
            left: 0;
            pointer-events: auto;
            /* Allow mouse events on canvas */
            border: 1px solid black;
            /* Optional: to visualize the canvas boundary */
        }
    </style>

    <div class="container-xxl flex-grow-1 container-p-y">
        {{-- @dd($result->video_type) --}}
        <div class="card" style="display: grid;height: 100%;">

            <div class="row" style=" padding: 0px; margin: 0px; ">
                {{-- <video id="videoElement" style="width: {{$streamInfo[0]->width}}px; height: {{$streamInfo[0]->height}}px;" controls>
                    <source src="{{ $result['stream_url'] }}" type="video/mp4">
                    Your browser does not support the video tag.
                </video> --}}

                @if ($result->video_type == 'normal')
                    @php
                        // Define the MIME types for video and image formats
                        $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',
                        ];

                        $allImageFormat = [
                            'jpg' => 'image/jpeg',
                            'jpeg' => 'image/jpeg',
                            'png' => 'image/png',
                            'gif' => 'image/gif',
                            'bmp' => 'image/bmp',
                            'webp' => 'image/webp',
                            'svg' => 'image/svg+xml',
                        ];

                        // Get the file extension from the stream URL
                        $fileExtension = pathinfo($result['stream_url'], PATHINFO_EXTENSION);
                        $mimeType = null;

                        // Check if the file is a video or image based on the extension
                        if (array_key_exists($fileExtension, $allVideoFormat)) {
                            $mimeType = $allVideoFormat[$fileExtension];
                        } elseif (array_key_exists($fileExtension, $allImageFormat)) {
                            $mimeType = $allImageFormat[$fileExtension];
                        }
                    @endphp

                    @if ($mimeType && strpos($mimeType, 'video') !== false)
                        <!-- Video tag rendering -->

                        {{-- <video id="videoElement"
                            style="width: {{ $streamInfo[0]->width }}px; height:{{ $streamInfo[0]->height }}px;" controls>
                            <source src="{{ $result['stream_url'] }}" type="{{ $mimeType }}">
                            Your browser does not support the video tag.
                        </video> --}}
                        <video id="videoElement" style="width: {{$streamInfo[0]->width}}px; height: {{$streamInfo[0]->height}}px;" controls>
                            <source src="{{ $result['stream_url'] }}" type="{{ $mimeType }}">
                            Your browser does not support the video tag.
                        </video>

                    @elseif ($mimeType && strpos($mimeType, 'image') !== false)
                        <!-- Image tag rendering -->
                        <img src="{{ $result['stream_url'] }}" id="videoElement"
                            style="width: {{ $streamInfo[0]->width }}px; height: {{ $streamInfo[0]->height }}px;"
                            alt="Image">
                    @else
                        <!-- Unsupported file type -->
                        <p>Unsupported file type.</p>
                    @endif
                @elseif ($result->video_type == 'youtube')
                    @php
                        $url = $result['stream_url']; // Full YouTube URL
                        $videoId = null;

                        // Parse the YouTube URL and extract video ID
                        $parsedUrl = parse_url($url);
                        parse_str($parsedUrl['query'] ?? '', $queryParams);

                        // Extract the video ID from query parameters
                        if (isset($queryParams['v'])) {
                            $videoId = $queryParams['v'];
                        }
                    @endphp

                    <!-- YouTube video iframe rendering -->
                    <iframe width="{{ $streamInfo[0]->width }}" height="{{ $streamInfo[0]->height }}"
                        src="https://www.youtube.com/embed/{{ $videoId }}" frameborder="0" allowfullscreen></iframe>
                @endif

                <canvas id="canvasElement">
                    </canvas>

            </div>

            <div class="row" style=" text-align: center; padding: 24px; display: block;">

                <form id="dataForm" action="{{ route('attendance.line') }}" method="post">
                    @csrf
                    <input type="hidden" id="start_x" name="start_x" />
                    <input type="hidden" id="start_y" name="start_y" />
                    <input type="hidden" id="end_x" name="end_x" />
                    <input type="hidden" id="end_y" name="end_y" />
                    <input type="hidden" id="color" name="color" />
                    <input type="hidden" id="width" name="width" />
                    <button type="submit" class="btn btn-info btn-sm">Create Line</button>
                </form>

            </div>
            <div id="loading" style=" text-align: center; padding: 51px;display: none;">
                <img src="{{ asset('infinite-spinner.svg') }}" style="width:300px;" />
            </div>

        </div>
    </div>

    <script>
        const video = document.getElementById('videoElement');
        const canvas = document.getElementById('canvasElement');
        const ctx = canvas.getContext('2d');
        let box = false;
        let isDrawing = false;
        let startX, startY;

        // Set the canvas dimensions to match the video dimensions
        video.addEventListener('loadedmetadata', function() {
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
        });

        // Start drawing on mouse down
        canvas.addEventListener('mousedown', function(e) {
            // Prevent drawing on double-click or right-click
            if (e.detail > 1 || e.button !== 0) return;

            isDrawing = true;
            startX = e.offsetX;
            startY = e.offsetY;
            console.log(`Mouse down at: ${startX}, ${startY}`);
        });

        // Draw the box on mouse move
        canvas.addEventListener('mousemove', function(e) {
            if (!isDrawing) return;

            const endX = e.offsetX;
            const endY = e.offsetY;

            // Clear the canvas before drawing the new rectangle
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            // Draw the rectangle
            ctx.strokeStyle = 'red';
            ctx.lineWidth = 2;
            ctx.strokeRect(startX, startY, endX - startX, endY - startY);
            console.log(`Drawing box from: (${startX}, ${startY}) to (${endX}, ${endY})`);
        });

        // Finish drawing on mouse up
        canvas.addEventListener('mouseup', function(e) {
            if (!isDrawing) return;

            isDrawing = false;
            const endX = e.offsetX;
            const endY = e.offsetY;

            const minBoxSize = 5; // Minimum width/height for the box

            const boxWidth = Math.abs(endX - startX);
            const boxHeight = Math.abs(endY - startY);

            // Ensure the box is large enough before drawing
            if (boxWidth > minBoxSize && boxHeight > minBoxSize) {
                // Draw the final rectangle
                ctx.strokeStyle = 'red';
                ctx.lineWidth = 2;
                ctx.strokeRect(startX, startY, endX - startX, endY - startY);
                console.log(`Final box from: (${startX}, ${startY}) to (${endX}, ${endY})`);
                console.log(`(${startX}, ${endX} , ${startY}, ${endY})`);
                box = true;
                // Save coordinates to hidden form fields
                document.getElementById('start_x').value = startX;
                document.getElementById('start_y').value = startY;
                document.getElementById('end_x').value = endX;
                document.getElementById('end_y').value = endY;
                document.getElementById('color').value = 'red';
                document.getElementById('width').value = 2;
            } else {
                console.log('Box too small to draw.');
            }
        });

        // Prevent double-click zoom
        canvas.addEventListener('dblclick', function(e) {
            e.preventDefault();
        });



        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('dataForm');
            const responseDiv = document.getElementById('response');

            form.addEventListener('submit', function(e) {
                e.preventDefault();

                if (box) {

                    const formData = new FormData(form);
                    const data = {};

                    formData.forEach((value, key) => {
                        data[key] = value;
                    });

                    fetch('{{ route('attendance.line') }}', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content')
                            },
                            body: JSON.stringify(data)
                        })
                        .then(response => response.json())
                        .then(data => {
                            document.getElementById('loading').style.display = "none";
                            if (data.status == 200) {
                                Swal.fire({
                                    title: "Good job!",
                                    text: "Box is created successfully",
                                    icon: "success"
                                });
                            } else {
                                Swal.fire({
                                    title: "Error!",
                                    text: "Sorry try again",
                                    icon: "error"
                                });
                            }
                        }).catch(error => {
                            document.getElementById('loading').style.display = "none";
                            console.error('Error:', error)
                        });

                } else {
                    alert('No box drawn or no changes found');
                }
            });
        });






    </script>
@endsection
