<?php
error_reporting(E_ERROR | E_PARSE);

?>
<style>
.upload-area {
    /* width: 70%; */
    height: 200px;
    border: 2px solid lightgray;
    border-radius: 3px;
    margin: 0 auto;
    /* margin-top: 100px; */
    text-align: center;
    overflow: auto;
}

.upload-area:hover {
    cursor: pointer;
}

.upload-area h5 {
    text-align: center;
    font-weight: normal;
    font-family: sans-serif;
    /* line-height: 50px; */
    color: darkslategray;
}

#file {
    display: none;
}

/* Thumbnail */
.thumbnail {
    width: 80px;
    height: 80px;
    padding: 2px;
    border: 2px solid lightgray;
    border-radius: 3px;
    float: left;
}

.size {
    font-size: 12px;
}
</style>

<div class="container-md">
    <div class="row">
        <div class="col-6 col-md-6">

            <!-- <div class="col-12 row">
                <label class="control-label col-6 text-right">Select Type <em class="required">&nbsp;*</em></label>
                <div class="col-6">
                    <select name="invList_select" id="invList_select" class="form-control col-lg-12">
                        <option selected value="0">Please Select Template </option>
                        <option value="1">Domestic</option>
                        <option value="2">Export</option>
                    </select>
                </div>
                <br />
                <br />
            </div> -->

            <div class="row">
                <div class="col-12">
                    <input type="file" name="file" id="file">
                    <div class="upload-area col-12" id="uploadfile">
                        <h5>Drag and Drop JSON file here<br />Or<br />Click to select JSON file</h5>
                    </div>
                    <br />
                    <button class="btn btn-primary collg-4 m0 g_qr float-right">Upload JSON File</button>
                </div>
            </div>            

            <div class="qrcode col-10 float-left"></div>
            <canvas id="mycanvas"></canvas>
        </div>
        <div class="col-6">
            <div class="col-12 downloadBtn">
                <a id="downloadBtn" href="" target="_Blank" class="btn btn-primary">Donwload Invoice</a>
            </div>
        </div>
    </div>
</div>
<script>
$(document).ready(function () {
    $(document).ajaxStart(function () {
        $(".pr_myDivLoading").show();
    }).ajaxStop(function () {
        $(".pr_myDivLoading").hide();
    });
});
</script>
<script>
$(function() {
    $('.downloadBtn').hide();
    
    $("html").on("dragover", function(e) {
        e.preventDefault();
        e.stopPropagation();
        $("h5").text("Drag here");
    });

    $("html").on("drop", function(e) {
        e.preventDefault();
        e.stopPropagation();
    });

    
    $('.upload-area').on('dragenter', function(e) {
        e.stopPropagation();
        e.preventDefault();
        $("h5").text("Drop");
    });

    
    $('.upload-area').on('dragover', function(e) {
        e.stopPropagation();
        e.preventDefault();
        $("h5").text("Drop");
    });

    
    $('.upload-area').on('drop', function(e) {
        e.stopPropagation();
        e.preventDefault();
        var file = e.originalEvent.dataTransfer.files;
        var extension = file[0].name.split('.').pop().toLowerCase();
        var validFileExtensions = ['json', 'JSON'];
        if ($.inArray(extension, validFileExtensions) == -1) {
            $(this).replaceWith($(this).val('').clone(true));
            swal('Warning', "Please select valid file");
        } else {
            var dispData = "<div> File Name :" + file[0].name + " </div><div> Size :" + convertSize(
                file[0].size) + "</div>";
            $("h5").html(dispData);

            var fd = new FormData();
            fd.append('file', file[0]);
            fd.append('invList_select', $('#invList_select option:selected').val());
            uploadData(fd);
        }
    });

    $("#uploadfile").click(function() {
        $("#file").click();
    });

    
    $("#file").change(function() {
        var extension = $(this).val().split('.').pop().toLowerCase();
        var validFileExtensions = ['json', 'JSON'];
        if ($.inArray(extension, validFileExtensions) == -1) {
            $(this).replaceWith($(this).val('').clone(true));
            swal('warning', "Please select valid file");
        } else {
            var file_data = $('#file').prop('files')[0];
            var fd = new FormData();
            fd.append('file', file_data);
            fd.append('invList_select', $('#invList_select option:selected').val());
            uploadData(fd);
        }
    });

});
// Bytes conversion
function convertSize(size) {
    var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    if (size == 0) return '0 Byte';
    var i = parseInt(Math.floor(Math.log(size) / Math.log(1024)));
    return Math.round(size / Math.pow(1024, i), 2) + ' ' + sizes[i];
}

function uploadData(formdata) {

    
    // if ($('#invList_select option:selected').val() == 0) {
    //     swal('warning Please Select Template');
    // } 
    // else {
        // 'pages/save_json.php'
        $('.pr_myDivLoading').show();
        var url = 'pages/domestic/inv_generator.php';
        // if ($('#invList_select option:selected').val() == 1) {
        //     url = 'pages/domestic/inv_generator.php';
        // }
        // else if ($('#invList_select option:selected').val() == 1) {
        //     url = 'pages/export/Einv_generator.php';
        // }
        $.ajax({
            // url: 'pages/save_json.php',
            url: url,
            type: 'post',
            data: formdata,
            contentType: false,
            processData: false,
            dataType: 'JSON',
            success: function(response) {                
                $('.downloadBtn').show();
                $('#downloadBtn').attr('href',response.download);
                swal('Click the Button to download Invoice');
                
            }
        });       
    // }
}

function printQR(data) {
    var details = data.json;
    var loc = data.loc;
    $('#hdn_JsonUrl').val(post_data);
    var post_data = details.SignedQRCode;
    $.ajax({
        url: 'qr/index.php?data=' + post_data,
        type: 'GET',
        success: function(response) {
            $('.qrcode').html(response);
            $('#hdn_JsonData').val(post_data);
        }
    });

}

$('#submitBtn').click(function() {
    var extension = $('#excel_file').val().split('.').pop().toLowerCase();
    var validFileExtensions = ['xls', 'xlsb', 'xlsx', 'xlsm', 'xlw', 'xps', 'xml'];
    if ($.inArray(extension, validFileExtensions) == -1) {
        $(this).replaceWith($(this).val('').clone(true));
        swal("Warning", "Please select valid file");
    } else {
        var Qr_data = $('#hdn_JsonData').val();
        var Json_Furl = $('#hdn_JsonUrl').val();
        var Inv_no = $('#DocNo').val();
        var Inv_Date = $('#DocDt').val();
        var SellerGstin = $('#SellerGstin').val();
        var BuyerGstin = $('#BuyerGstin').val();
        var TotInvVal = $('#TotInvVal').val();
        var ItemCnt = $('#ItemCnt').val();
        var Irn = $('#Irn').val();
        var Qr_url = $('#ImageUrl').val();

        //var Qr_data = $('#SellerGstin').val();
        //var Qr_data = $('#SellerGstin').val();
        var file_data = $('#excel_file').prop('files')[0];
        var form_data = new FormData();
        form_data.append('Qr_data', Qr_data);
        form_data.append('Inv_no', Inv_no);
        form_data.append('Inv_Date', Inv_Date);
        form_data.append('SellerGstin', SellerGstin);
        form_data.append('BuyerGstin', BuyerGstin);
        form_data.append('TotInvVal', TotInvVal);
        form_data.append('ItemCnt', ItemCnt);
        form_data.append('Irn', Irn);
        form_data.append('Qr_url', Qr_url);
        form_data.append('excel_file', file_data);
        form_data.append('json_url', Json_Furl);

        //$(this).hide();

        $.ajax({
            url: 'pages/save_invoice.php',
            //url: 'tools/save_excel.php',
            dataType: 'JSON',
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,
            type: 'post',
            success: function(php_script_response) {
                //$('#download_link').show();
                swal(php_script_response.status_info)
                LoadList();
            }
        });

        $('.upload').show();
    }
});

function printDetails(data) {
    var details = data.json;
    var post_data = details.SignedQRCode;
    $.ajax({
        url: 'tools/decrypt_QR.php?data=' + post_data,
        type: 'GET',
        success: function(response) {
            $('.qrcode_details > textarea').val(response);
            $('.qrcode_details > textarea').show();
            var json = $.parseJSON(response);
            var datas = $.parseJSON(json.data);
            $('#SellerGstin').val(datas['SellerGstin']);
            $('#BuyerGstin').val(datas['BuyerGstin']);
            $('#DocNo').val(datas['DocNo']);
            $('#DocDt').val(datas['DocDt']);
            $('#TotInvVal').val(datas['TotInvVal']);
            $('#ItemCnt').val(datas['ItemCnt']);
            $('#Irn').val(datas['Irn']);
            $('.data_qr ').attr('readonly', 'readonly');
            $('.g_qr').hide();
            $('#hdn_JsonUrl').val(data.loc);
            $('#form_data').show();
        }
    });
    $('.upload').show();

}

function addThumbnail(data) {
    $("#uploadfile h5").remove();
    var len = $("#uploadfile div.thumbnail").length;
    var num = Number(len);
    num = num + 1;
    var name = data.name;
    var size = convertSize(data.size);
    var src = data.src;
    // Creating an thumbnail
    $("#uploadfile").append('<div id="thumbnail_' + num + '" class="thumbnail"></div>');
    $("#thumbnail_" + num).append('<img src="' + src + '" width="100%" height="78%">');
    $("#thumbnail_" + num).append('<span class="size">' + size + '<span>');

}

function LoadList() {
    $.ajax({
        url: 'pages/list_inv.php',
        //dataType: 'text',  
        //cache: false,
        //contentType: false,
        //processData: false,
        //            data: form_data,                         
        //type: 'post',
        success: function(php_script_response) {
            $('#ListInvoices').html(php_script_response);
            $('.tesla').DataTable();
        }
    });
}
</script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>