@extends('dashboard')
@section('title', 'Distribute Food')
@section('page_content')
    <div class="container py-4">
        <div class="row mb-4">
            <div class="col-12">
                <div class="card bg-dark text-white shadow-sm border-0">
                    <div class="card-body text-center py-4">
                        <h3 class="mb-1 text-warning">Word Number: {{ $dealer->word_number }}</h3>
                        <h5 class="mb-1">Dealer: {{ $dealer->dealer_name }}</h5>
                        <p class="mb-0 text-light">Sale Point: {{ $dealer->sale_point }} | Institute:
                            {{ $dealer->institute_name }}</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="row justify-content-center">
            <div class="col-md-8 text-center">
                <button id="startScanBtn" class="btn btn-success btn-lg px-5 py-3 mb-4 rounded-pill shadow">
                    <i class="fas fa-camera"></i> Distribute (Scan Client QR)
                </button>

                <div id="reader-container" class="card shadow-sm d-none mx-auto" style="max-width: 500px;">
                    <div class="card-body p-2">
                        <div id="reader" style="width: 100%;"></div>
                        <button id="stopScanBtn" class="btn btn-danger btn-sm mt-3 w-100">Stop Camera</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://unpkg.com/html5-qrcode"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
        let html5QrcodeScanner;
        let isProcessing = false;

        // Web Audio API for Error Alert Sound
        function playAlertSound() {
            const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
            const oscillator = audioCtx.createOscillator();
            const gainNode = audioCtx.createGain();

            oscillator.type = 'triangle';
            oscillator.frequency.setValueAtTime(600, audioCtx.currentTime); // Frequency (Pitch)
            oscillator.connect(gainNode);
            gainNode.connect(audioCtx.destination);

            oscillator.start();
            // Sound duration
            setTimeout(() => { oscillator.stop(); }, 500);
        }

        document.getElementById('startScanBtn').addEventListener('click', function () {
            this.classList.add('d-none');
            document.getElementById('reader-container').classList.remove('d-none');
            startScanner();
        });

        document.getElementById('stopScanBtn').addEventListener('click', function () {
            stopScanner();
        });

        function startScanner() {
            html5QrcodeScanner = new Html5Qrcode("reader");

            // ডিভাইসের সব ক্যামেরা লিস্ট করবে
            Html5Qrcode.getCameras().then(devices => {
                if (devices && devices.length > 0) {
                    // যদি একাধিক ক্যামেরা থাকে (যেমন মোবাইলে), তবে ২য় বা পেছনের ক্যামেরা নিবে, নাহলে ১ম ক্যামেরা (ল্যাপটপ)
                    let cameraId = devices[0].id;
                    if (devices.length > 1) {
                        cameraId = devices[1].id; // ব্যাক ক্যামেরা সিলেক্ট করার চেষ্টা
                    }

                    const config = { fps: 10, qrbox: { width: 250, height: 250 } };

                    html5QrcodeScanner.start(cameraId, config, onScanSuccess)
                        .catch(err => {
                            console.error(err);
                            Swal.fire('Error', 'ক্যামেরা স্টার্ট করতে সমস্যা হচ্ছে!', 'error');
                        });
                } else {
                    Swal.fire('Error', 'আপনার ডিভাইসে কোনো ক্যামেরা পাওয়া যায়নি!', 'error');
                }
            }).catch(err => {
                console.error(err);
                Swal.fire('Error', 'ক্যামেরা পারমিশন দেওয়া হয়নি অথবা সাইটটি HTTPS নয়!', 'error');
            });
        }

        function stopScanner() {
            if (html5QrcodeScanner) {
                html5QrcodeScanner.stop().then(() => {
                    document.getElementById('reader-container').classList.add('d-none');
                    document.getElementById('startScanBtn').classList.remove('d-none');
                });
            }
        }

        function onScanSuccess(decodedText, decodedResult) {
            if (isProcessing) return; // Prevent multiple requests at once
            isProcessing = true;

            // Pause camera temporarily while verifying
            html5QrcodeScanner.pause();

            fetch("{{ route('distributions.scan_verify') }}", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-CSRF-TOKEN": "{{ csrf_token() }}"
                },
                body: JSON.stringify({
                    nid_number: decodedText,
                    dealer_id: "{{ $dealer->id }}"
                })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'error') {
                        playAlertSound(); // Trigger sound for failure
                        Swal.fire({
                            icon: 'error',
                            title: 'Warning!',
                            text: data.message,
                            confirmButtonColor: '#d33'
                        }).then(() => {
                            resumeScanner();
                        });
                    } else {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success!',
                            text: data.client_name + ' - ' + data.message,
                            timer: 2000,
                            showConfirmButton: false
                        }).then(() => {
                            resumeScanner();
                        });
                    }
                })
                .catch(err => {
                    console.error(err);
                    isProcessing = false;
                    html5QrcodeScanner.resume();
                });
        }

        function resumeScanner() {
            isProcessing = false;
            if (html5QrcodeScanner) {
                html5QrcodeScanner.resume();
            }
        }
    </script>
@endsection