@extends('layouts.masterDashboard')
@section('content')
    <style>
        #qr-canvas {
            margin: auto;
            width: calc(100% - 5px);
            max-width: 400px;
            height: 300px;
            border-radius: 15px;
        }

        #btn-scan-qr {
            cursor: pointer;
        }

        #btn-scan-qr img {
            height: 10em;
            padding: 15px;
            margin: 15px;
            background: white;
        }

        #qr-result {
            font-size: 1.2em;
            margin: 20px auto;
            padding: 20px;
            max-width: 700px;
            background-color: white;
            border-radius: 10px;
            color: lightseagreen;
        }
    </style>
    <div class="row">
        <div class="col-md">
            <div class="card card-user">
                <div class="card-header d-flex justify-content-center border-0">
                    <h3>Scan QR Code</h3>
                </div>
                <div class="card-body py-1">
                    <div id="container">
                        <a id="btn-scan-qr">
                            <!-- <img src="https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2017/07/1499401426qr_icon.svg"> -->
                        </a>
                        <!-- <h4 class="text-center text-danger">Click this image to open scanner</h4> -->
                        <div class="d-flex justify-content-center">
                            <canvas hidden="" id="qr-canvas"></canvas>
                        </div>
                        <div id="qr-result" hidden="">
                          <div id="outputData">
                            <!--<h1>Pradeep</h1>-->
                          </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    @section('customscript')
        <script type="text/javascript" src="{{ asset('public/js/qr_packed.js') }}"></script>
        <script>
            // const qrcode = window.qrcode;

            window.onload = function(){
                console.log("Script Running..");
                $("a#btn-scan-qr").click();
                // For test purpose only
                // var res = "qr_id='2', client_code='steve94', client_id='3'";
                // ajx_call_to_decode_qr(res);
                // qrResult.hidden = false;
            }

            const video = document.createElement("video");
            const canvasElement = document.getElementById("qr-canvas");
            const canvas = canvasElement.getContext("2d");

            const qrResult = document.getElementById("qr-result");
            const outputData = document.getElementById("outputData");
            const btnScanQR = document.getElementById("btn-scan-qr");

            let scanning = false;

            function ajx_call_to_decode_qr(res){
                console.log("ajax call to decode qr", res);
                var token = $("meta[name='csrf-token']").attr("content");
                var splitting = res.split(", ");
                var obj = {};
                for (var i = 0; i < splitting.length; i++) {
                    var split = splitting[i].split('=');
                    obj[split[0].trim()] = split[1].trim();
                }
                var formData = {
                    "_token"  : token,
                    "qr_id" : obj.qr_id.replace(/'/g, ""),
                    "client_code" : obj.client_code.replace(/'/g, ""),
                    "client_id" : obj.client_id.replace(/'/g, ""),
                    "vendor_id" : "{{ Auth::user()->id }}",
                    "vendor_username" : "{{ Auth::user()->username }}"
                };
                console.log(formData);
                $.ajax({
                    type        : 'POST',
                    url         : "{{ url('qr/decode') }}",
                    data        : formData,
                    dataType    : 'json',
                    encode      : true,
                    success     : function(res){
                        console.log(res);
                        if(res.type == "success"){
                            success_detail(res);
                        }else{
                            alert_failure(res);
                        }
                    },
                    error       : function(xhr, textStatus, errorThrown){
                        console.log(errorThrown, textStatus);
                    }
                });
            }
            
            function success_detail(res){
                var qrcodetype = res.message.qrcode_type;
                console.log(qrcodetype);
                if(qrcodetype == "type4"){
                  
                  var div = "\
                        <div class='container-fluid'>\
                            <div class='row d-flex justify-content-center'>\
                                <div class='alert alert-success w-auto text-center px-2 py-1' role='alert'>\
                                    QR Code Scanning Successful\
                                </div>\
                            </div>\
                            <div class='row'>\
                                <p class='mx-2 my-0 text-left w-100'><span style='color: #304a96;'>Please Click Below Link To Place Order:</span></p>\
                                "+ res.message.orderlink +"\
                            </div>\
                        </div>\
                    ";
                $("div#outputData").html(div);
                  
                } else {
                  
                  var div = "\
                        <div class='container-fluid'>\
                            <div class='row d-flex justify-content-center'>\
                                <div class='alert alert-success w-auto text-center px-2 py-1' role='alert'>\
                                    QR Code Scanning Successful\
                                </div>\
                            </div>\
                            <div class='row'>\
                                <p class='mx-2 my-0 text-center w-100'><span style='color: #304a96;'>Client Name:</span> " + res.message.client_name + "</p>\
                                <p class='mx-2 my-0 text-center w-100'><span style='color: #304a96;'>Employee Name:</span> " + res.message.emp_name + "</p>\
                                <p class='mx-2 my-0 text-center w-100'><span style='color: #304a96;'>Designation:</span> " + res.message.designation + "</p>\
                                <p class='mx-2 my-0 text-center w-100'><span style='color: #304a96;'>Employee ID:</span> " + res.message.emp_id + "</p>\
                                <p class='mx-2 my-0 text-center w-100'><span style='color: #304a96;'>Date of QR Code assigned:</span> " + res.message.created_at + "</p>\
                                  <p class='mx-2 my-0 text-center w-100'><span style='color: #304a96;'>QR Code Type:</span> " + qrcodetype + "</p>\
                            </div>\
                        </div>\
                    ";
                $("div#outputData").html(div);
                  
                }
                
            }
            
            function alert_failure(res){
                var div = "\
                        <div class='container-fluid'>\
                            <div class='row d-flex justify-content-center'>\
                                <div class='alert alert-" + res.type + " w-auto text-center px-2 py-1' role='alert'>\
                                    " + res.message + "\
                                </div>\
                            </div>\
                        </div>\
                    ";
                $("div#outputData").html(div);
            }

            qrcode.callback = res => {
              if (res) {
                // outputData.innerText = res;
                ajx_call_to_decode_qr(res);
                scanning = false;
                console.log("ss");
                video.srcObject.getTracks().forEach(track => {
                  track.stop();
                });

                qrResult.hidden = false;
                canvasElement.hidden = true;
                btnScanQR.hidden = false;
              }
            };

            btnScanQR.onclick = () => {
            //   console.log(navigator);
              navigator.mediaDevices
                .getUserMedia({ video: { facingMode: "environment" } })
                .then(function(stream) {
                  scanning = true;
                  qrResult.hidden = true;
                  btnScanQR.hidden = true;
                  canvasElement.hidden = false;
                  video.setAttribute("playsinline", true); // required to tell iOS safari we don't want fullscreen
                  video.srcObject = stream;
                  video.play();
                  tick();
                  scan();
                });
            };

            function tick() {
              canvasElement.height = video.videoHeight;
              canvasElement.width = video.videoWidth;
              canvas.drawImage(video, 0, 0, canvasElement.width, canvasElement.height);

              scanning && requestAnimationFrame(tick);
            }

            function scan() {
              try {
                qrcode.decode();
              } catch (e) {
                setTimeout(scan, 300);
              }
            }
        </script>
    @endsection
@endsection
