<style>
    .text-grey{
        color: #9599AD;
    }

    .box {
        width: 100%;
        height: 60px;
        border-radius: 14px;
        display: flex;
        align-items: center;
        justify-content: center;
        text-align: center;
    }

    .file-box {
        width: 100%;
        height: 60px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        text-align: left;
        border: 1px solid #E9EBEC;
        padding-left: 10px;
        margin-right: 8px;
    }

    .file-delete {
        margin-left: auto;
        cursor: pointer;
        padding: 8px;
        margin-right: 8px;
        font-size: 16px;
    }

    .file-box-text {
        color: #495057;
        font-size: 14px;
    }

    .form-check-input {
        margin-top: 0;
        margin-bottom: 0;
    }

    .dotted {
        border:  3px #c3c3c3 dotted;
    }

    .pos-text {
        margin-top: 1em;
        font-size: 16px;
    }

    .detail-left{
        display: flex;
        flex-direction: column;
        height: 100%;
    }

    .iframe-pdf{
        width: 100%;
        height: 100%;
    }

    .card-content{
        height:700px;
    }

    .file-content {
        max-height: 370px;
        overflow: auto;
        overflow-x: hidden;
    }
    .border-upload{
        border: 1px solid #E9EBEC;
    }
</style>

@php
    $case       = @$case;
    $admin      = getCONFIG('admin');
    $hn         = @$case->hn ?? '';
    $folderdate = explode(' ', @$case->appointment."")[0] ?? '';
    $store_url  = @$admin->store_url;
@endphp

<div id="confirm_delete_modal" class="modal fade" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="myModalLabel">Confirm Delete</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"> </button>
            </div>
            <div class="modal-body">
                <p class="text-muted">Do you want to delete these cases?</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
                <button id="confirm_modal_btn" type="button" class="btn btn-primary ">Confirm</button>
            </div>

        </div>
    </div>
</div>

<div class="card card-content">
    <div class="card-body" >
        <div class="row m-3" style="height: 100%;">
            <div class="col-4 detail-left">
                <h4>Upload Report</h4>
                <h5 class="text-grey">Please select report file to upload to EndoINDEX</h5>
                <input type="file" name="" id="file_input"  hidden>
                <div class="box dotted" id="upload_div" id="drop_zone" style="cursor: pointer;"
                    onclick="open_file_input()" ondrop="dropHandler(event);"
                    ondragover="dragOverHandler(event);">
                    <p class="btn text-center pos-text text-grey">Drag & Drop your files or Browse </p>
                </div>
                <h4 class="text-grey mt-3">Uploaded file</h4>
                <div id="file_div" class="file-content" >
                    @foreach ($case->uploaded_file ?? [] as $in=>$file)
                        @php
                            if(@$file['status'] == 'hide'){
                                continue;
                            }
                            $url = @$store_url."$hn/$folderdate/pdf/".@$file['new_name'];
                        @endphp
                        <div class="row">
                            <div class="col-11 align-self-center">
                                <div class="border-upload"  id="file{{$in}}a" class="file-box m-1"  style="cursor: pointer;">
                                    <input class="form-check-input ms-3 mb-1 mt-3" type="radio" name="files" data-src="{{$url}}" id="fileupload{{$in}}a" onclick="preview_file('{{$url}}', '{{@$file['new_name']}}')">
                                    <label class="btn text-center text-grey mt-2 file-box-text" for="fileupload{{$in}}a" >
                                        {{ strlen($file['original_name']) > 30 ? substr($file['original_name'], 0, 30) . '...' : $file['original_name'] }}
                                    </label>
                                </div>

                            </div>
                            <div class="col-1 align-self-center {{$in}}a">
                                <i onclick="delete_file('{{$in}}a', '{{@$file['new_name']}}')" class="ri-delete-bin-fill file-delete text-danger"></i>
                            </div>
                        </div>
                        @endforeach
                </div>
                <div class="mt-auto mb-3">
                    <button class="btn btn-success w-100">
                        <i class="ri-folder-add-fill"></i><br>
                        Create Report
                    </button>
                </div>
            </div>
            <div class="col-1"></div>
            <div class="col-7 mb-3">
                <iframe src="" data-file="" frameborder="0" class="iframe-pdf"></iframe>
            </div>

        </div>

    </div>
</div>


<script>
    $.ajaxSetup({headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}});

    var all_files = []
    var submit_status = true

    var first_list = $("#fileupload0a")
    if(first_list){
        $("#fileupload0a").prop('checked', true).click()
    }

    function open_file_input() {
        $('#file_input').trigger("click");
    }

    $('#file_input').on('change', function(e) {
        var files = [...e.target.files]
        upload_files(files, 'manual')
    })

    function dropHandler(ev) {
        ev.preventDefault();
        if (ev.dataTransfer.items) {
            let files = [];
            Array.from(ev.dataTransfer.items).forEach((item) => {
                if (item.kind === 'file') {
                    let file = item.getAsFile();
                    if (file) {
                        console.log('File Name:', file.name);
                        files.push(file);
                    }
                }
            });

            if (files.length > 0) {
                upload_files(files, 'drop');
            }
        }
    }

    function dragOverHandler(ev) {
        ev.preventDefault();
    }

    function upload_files(files, event_type){
        let file_temp = []
        files.forEach((item, i) => {
            let name = item.name
            let ext  = name.split('.').pop().toLowerCase()
            let allowed_ext = ['oxps', 'xps', 'pdf'];
            if (allowed_ext.includes(ext)) {
                file_temp.push(item);
            } else {
                call_alert('wrong type',
                    'Uploaded file is not a valid file. Only OXPS and XPS files are allowed.');
            }

        })

        let box_length = $('.file-box').length
        if(event_type == 'drop'){
            file_temp.forEach((item, i) => {
                append_file(item, box_length)
            });
        } else {
            file_temp.forEach((file, i) => {
                append_file(file, box_length)
            });
        }
    }

    function append_file(file, i) {
        all_files.push(file)
        submit_status = true
        post(all_files[0], i)
    }

    function delete_file(num, file_name) {
        let pdfurl = $('.iframe-pdf').data('file').toLowerCase()
        if(pdfurl.includes(file_name)){
            $('.iframe-pdf').attr('src', '')
        }
        $.post("{{url('api/photo')}}", {
            event:"update_pdffile",
            filename:file_name,
            caseuniq:'{{ @$case->caseuniq }}',
            comcreate:'{{ @$case->comcreate }}',
        }, function (data, status) {
            $(`#file${num}`).remove()
            $(`.${num}`).empty()

        })
    }

    function post(file, i) {
        var formData = new FormData()
        formData.append('files', file)
        formData.append('event', 'upload_pdffile')
        formData.append('_id', '{{ @$case->_id }}')
        formData.append('caseuniq', '{{ @$case->caseuniq }}')
        formData.append('comcreate', '{{ @$case->comcreate }}')
        console.log(formData);

        var ajax = new XMLHttpRequest()
        ajax.upload.addEventListener("progress", progressHandler, false)
        ajax.addEventListener("load", completeHandler, false);
        ajax.addEventListener("error", errorHandler, false);
        ajax.open("POST", "{{url("api/photo")}}");
        ajax.send(formData)

        function progressHandler(evt) {
            // console.log(evt.total, evt.loaded);
        }

        function errorHandler() {

        }

        function completeHandler(e) {
            let res = e.target.responseText;
            let parse = JSON.parse(res)
            if(res){
                let url = `{{@$store_url}}${parse.src}`
                let inp = `
                    <div id="file${i}" class="file-box m-1"  style="cursor: pointer;">
                        <input class="form-check-input ms-3 mb-1" name="files" type="radio" data-src="${url}" id="fileupload${i}" onclick="preview_file('${url}', '${parse.filename}')">
                        <label class="btn text-center text-grey mt-2 file-box-text" for="fileupload${i}" >${parse.oldname}</label>
                        <i onclick="delete_file('${i}', '${parse.filename}')" class="ri-delete-bin-fill file-delete text-danger"></i>
                    </div>
                `
                $('#file_div').append(inp)
                // $('.simplebar-content').append(inp)
            }
            $('#file_input').val('');
            all_files = []

        }

    }

    function preview_file(url, name){
        $('.iframe-pdf').attr('src', url)
        $('.iframe-pdf').data('file', name)
    }


</script>
