@extends('layouts.customer')

@section('title', 'Device Edit')

@section('extra-css')
    <link rel="stylesheet" href="{{asset('plugins/select2/css/select2.min.css')}}">
@endsection

@section('content')
    <section class="content">
        <div class="row">
            <div class="col-12 mx-auto col-sm-10 mt-3">
                <div class="card">
                    <div class="card-header">
                        <h2 class="card-title">@lang('customer.device_edit')</h2>
                        <a class="btn btn-info float-right" href="{{route('customer.wadevice.index')}}">@lang('customer.back')</a>
                    </div>
                    <form method="post" role="form"  action="{{route('customer.wadevice.update',[$device])}}">
                        @csrf
                        @method('put')
                        <div class="card-body">
                            @include('customer.wadevice.form')
                        </div>
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">@lang('customer.update')</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </section>
@endsection

@section('extra-scripts')
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrious/4.0.2/qrious.min.js"></script>
<script src="https://cdn.socket.io/4.7.2/socket.io.min.js"
    integrity="sha384-mZLF4UVrpi/QTWPA7BjNPEnkIfRFn4ZEO3Qt/HFklTJBj/gBOV8G3HcKn4NfQblz" crossorigin="anonymous">
</script>
<script>
    const socket = io("{{ config('pico.wa_server_host') }}");
    socket.on("connect", () => {
        console.log("Connected");
    });
    socket.on("qrcode", (res) => {
        if (!res.code) {
            notify('danger', 'Invalid qr code')
            retrn;
        }
        const code = res.code;
        new QRious({
            element: document.getElementById("qrcode"),
            value: code,
            size: 200
        });
    });
    socket.on('scanned',(resp)=>{
            $.ajax({
                method:'post',
                url:"{{route('customer.wadevice.status')}}",
                data:{id:resp.id,status:'active',_token:"{{csrf_token()}}"},
                success:(res)=>{
                    console.log(res);
                    notify('success','Device connected successfully');
                    $('#qrcode').remove();
                }
            });
        })
    socket.on('status',(res)=>{
        console.log(res);
        let isCurrentOnline=false;
        @if (isset($device) && $device->status == 'active')
            isCurrentOnline=true;
        @endif
        if(res.online==false || isCurrentOnline==false){
            socket.emit('scan',{
            id: '{{ $device->device_unique_id }}'
            })
        }
    })


    socket.emit('check', {
        id: '{{ $device->device_unique_id }}'
    });


</script>
@endsection

