@extends('layouts.app')

@section('content')
    <div class="edit-container">
        <form id="scan-form" action="{{ route('qr_scan.scan') }}" method="post" class="edit-form">
            @csrf
            <div class="column">
                <label for="qr_code">Scan QR Code:</label>
                <div id="scanner-container"></div>
                <div id="result"></div>
            </div>
        </form>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/quagga/dist/quagga.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <script>
        Quagga.init({
            inputStream: {
                name: "Live",
                type: "LiveStream",
                target: document.querySelector('#scanner-container')
            },
            decoder: {
                readers: ["qrcode_reader"]
            }
        }, function(err) {
            if (err) {
                console.error(err);
                return;
            }
            Quagga.start();
            Quagga.onDetected(function(result) {
                var code = result.codeResult.code;
                document.querySelector('#qr_code').value = code;
                Quagga.stop();
            });
        });

        $('#scan-form').submit(function(e) {
            e.preventDefault();
            var qrCode = $('#qr_code').val();
            $.ajax({
                type: "POST",
                url: "{{ route('qr_scan.scan') }}",
                data: { _token: "{{ csrf_token() }}", qr_code: qrCode },
                success: function(response) {
                    $('#result').html(response.message);
                },
                error: function(xhr, status, error) {
                    console.error(xhr.responseText);
                }
            });
        });
    </script>
@endsection
