@extends('layouts.layouts_ipad.layouts_Newipad')


@section('style')
    <style>
        .select2-container--default .select2-selection--single {
            background: #2B2F34 !important;
            border: none !important;
        }

        .btn-operation-start-ipad {
            color: #ffffff;
            background: #F06548;
            height: 10vh;
            width: 100%;
            font-size: 18px;

        }

        .btn-operation-start-ipad:hover {
            color: #ffffff;
            background: #ca4d34;
            height: 10vh;
            width: 100%;
            font-size: 18px;

        }

        .btn-operation-ipad {
            color: #ffffff;
            background: #F06548;
            height: 10vh;
            width: 100%;
            font-size: 18px;

        }

        .btn-operation-ipad:hover {
            color: #ffffff;
            background: #ca4d34;
            height: 10vh;
            width: 100%;
            font-size: 18px;

        }

        .btn-count-operation {
            color: #ffffff;
            background: #222529;
            height: 10vh;
            width: 100%;
            font-size: 18px;

        }

        .btn-count-operation:hover {
            color: #ffffff;
            background: #222529;
            height: 10vh;
            width: 100%;
            font-size: 18px;

        }

        .border-upload-op {
            border: 1px solid #ffffff80;
            border-style: dashed;
            height: 250px;
            padding: 5.5em 0 0;
            color: #ffffff;
            text-align: center;
            border-radius: 4px;
            font-size: 18px;
        }


        .btn-time-dark {
            color: #ffffff;
            background: #2B2F34;
        }

        .btn-time-dark:hover {
            color: #ffffff;
            background: #393e44;
        }

        input::placeholder {
            text-align: center;
        }

        input {
            text-align: center;
        }

        .btn-refresh-ope {
            background: transparent;
            color: #ffffff;
        }

        .text-bg-darkk {
            background: #000000;
            color: #ffffff;
            cursor: pointer;
        }
    </style>
@endsection
@section('tophead')
    Operation Detail
@endsection
@section('modal')
    @include('EndoCAPTURE.ipad.modal.modal_pviewphoto')
    @include('EndoCAPTURE.ipad.modal.modal_pviewvideo')
@endsection
@section('content')

    <div class="row">
        <span class="text-white fs-16">
            &nbsp; Patient Detail : &ensp; &ensp; &ensp;
            {{ @$case->hn }} &ensp; &ensp; &ensp;
            {{-- @dd($patient); --}}
            {{ @$patient->firstname . ' ' . @$patient->middlename . ' ' . @$patient->lastname }} &ensp; &ensp; &ensp;
            @php
                $gender = isset($patient->gender) ? 'Male' : 'Female';
            @endphp
            Gender: {{ $gender }} &ensp; &ensp; &ensp;
            @php
                $birthdate = format_date($patient->birthdate , "d M,y")
            @endphp
            {{ $birthdate }}  ({{ age($patient->birthdate) }})
        </span>
        <div class="col-12 p-2 text-white fs-16">
            &nbsp;&nbsp; Procedure : {{@$case->procedurename}}
        </div>
        <div class="col-6">
            <div class="Operation-Ipad-button">
                @php
                    $start_status  = @$case->datetime_start."" != "" ? 'none' : 'block';
                    $time_status   = @$case->datetime_start."" != "" && @$case->datetime_end."" != "" ? 'block' :'none';
                    $finish_status = 'none';

                    // $date        = @$case->appointment."" != "" ? explode(' ', $case->appointment)[0] : '';

                    $time_start  = @$case->datetime_start."" != "" ? @$case->datetime_start."" : "00:00:00";
                    $time_end    = @$case->datetime_end."" != "" ? @$case->datetime_end."" : "00:00:00";
                    if($time_start != "00:00:00" && $time_end != "00:00:00"){
                        try{
                            $datetime_start = new DateTime("$time_start");
                            $time_start = $datetime_start->format('d F, Y H:i:s');
                        } catch (\Exception $e){}

                        try{
                            $datetime_end = new DateTime("$time_end");
                            $time_end = $datetime_end->format('d F, Y H:i:s');
                        } catch (\Exception $e){}
                    }

                    // if (isset($case->photo)) {
                    //     if (is_array($case->photo)) {
                    //         if (count($case->photo) > 0) {
                    //             $start_status = 'none';
                    //             $finish_status = 'block';
                    //         }
                    //     }
                    // }
                @endphp
                <button class="btn btn-operation-start-ipad btn_changestatus" data-type="Operation" hn="{{ @$case->case_hn }}"
                    style="display: {{ @$start_status }};"> &nbsp; Press for Start Operation !!</button>
                <button class="btn btn-count-operation operation-start" data-type="Operation" hn="{{ @$case->case_hn }}" style="display: {{ @$time_status }};">
                    &nbsp; Operation Started (Duration) <br> {{@$time_start}}</button>

                {{-- <button class="btn btn-operation-ipad btn_changestatus" data-type="Recovery" hn="{{@$case->case_hn}}" style="display: {{@$finish_status}};"><i class="ri ri-checkbox-circle-line ri-lg"></i> &nbsp; Operation
                    Finished</button> --}}
            </div>
        </div>
        <div class="col-1 align-self-center">
            <button class="btn btn-refresh-ope" style="display: {{ @$time_status }};"><i class=" ri-refresh-line ri-xl" ></i></button>
        </div>
        <div class="col-5">
            <button class="btn btn-operation-ipad btn_changestatus" data-type="Recovery" hn="{{ @$case->case_hn }}"
                style="display: {{ @$finish_status }};">
                &nbsp; Press for Finish Operation !!</button>
            <button class="btn btn-count-operation operation-end" data-type="Operation" hn="{{ @$case->case_hn }}" style="display: {{ @$time_status }};"> &nbsp;
                Operation Ended (Duration) <br> {{@$time_end}}</button>

        </div>
    </div>


    <div class="row p-2 font-gray">
        <div class="card mt-2 p-3">
            <div class="col-12">
                Operation Detail
                <div class="col-12 mt-1">
                    <div class="row mt-2 text-center">
                        <div class="col-2">
                            <span>Patient In</span> <br>
                            <input type="text" class=" mt-1 form-control form-control-sm time_patientin time-cleave" data-class="time_patientin" placeholder="hh:ss:mm"
                                value={{ @$case->datetime_patientin ? explode(' ', @$case->datetime_patientin)[1] ?? '' : '' }}>
                            <button id="" type="button"
                                class="btn btn-time-dark w-100 waves-effect mt-1 waves-light get-timestamp" data-class="time_patientin">
                                <i class="ri-timer-fill ri-lg"></i></button>
                        </div>
                        <div class="col-2 mt-1">
                            <span>Sedate Time</span> <br>
                            <input type="text" class="mt-1 form-control form-control-sm time_sedate time-cleave" data-class="time_sedate" placeholder="hh:ss:mm"
                                value={{ @$case->datetime_sedate ? explode(' ', @$case->datetime_sedate)[1] ?? '' : '' }}>

                            <button id="" type="button"
                                class="btn btn-time-dark waves-effect w-100 mt-1 waves-light get-timestamp" data-class="time_sedate"><i
                                    class=" ri-timer-fill ri-lg"></i></button>
                        </div>
                        <div class="col-2 mt-1">
                            <span>Incision </span> <br>
                            <input type="text" class="mt-1 form-control form-control-sm time_incision time-cleave" data-class="time_incision" placeholder="hh:ss:mm"
                            value={{ @$case->datetime_incision ? explode(' ', @$case->datetime_incision)[1] ?? '' : '' }}>

                            <button id="" type="button"
                                class="btn btn-time-dark waves-effect mt-1 w-100 waves-light get-timestamp" data-class="time_incision"><i
                                    class=" ri-timer-fill ri-lg"></i></button>
                        </div>
                        <div class="col-2 mt-1">
                            <span>Operation Start</span> <br>
                            <input type="text" class="mt-1 form-control form-control-sm time_start time-cleave" data-class="time_start"
                                placeholder="hh:ss:mm" value={{ @$case->datetime_start ? explode(' ', @$case->datetime_start)[1] ?? '' : '' }}>

                            <button id="" type="button"
                                class="btn btn-time-dark waves-effect mt-1 w-100 waves-light get-timestamp" data-class="time_start"><i
                                    class=" ri-timer-fill ri-lg"></i></button>
                        </div>
                        <div class="col-2 mt-1">
                            <span>Operation End</span> <br>
                            <input type="text" class="mt-1 form-control form-control-sm time_end time-cleave" data-class="time_end"
                                placeholder="hh:ss:mm" value={{ @$case->datetime_end ? explode(' ', @$case->datetime_end)[1] ?? '' : '' }}>

                            <button id="" type="button"
                                class="btn btn-time-dark waves-effect mt-1 w-100 waves-light get-timestamp" data-class="time_end"><i
                                    class=" ri-timer-fill ri-lg"></i></button>
                        </div>
                        <div class="col-2 mt-1">
                            <span>Suture</span> <br>
                            <input type="text" class="mt-1 form-control form-control-sm time_sature time-cleave"  data-class="time_sature"
                                placeholder="hh:ss:mm" value={{ @$case->datetime_sature ? explode(' ', @$case->datetime_sature)[1] ?? '' : '' }}>

                            <button id="" type="button"
                                class="btn btn-time-dark waves-effect mt-1 w-100 waves-light get-timestamp" data-class="time_sature"><i
                                    class=" ri-timer-fill ri-lg"></i></button>
                        </div>
                    </div>


                    {{-- <div class="row mt-2 text-center">
                        <div class="col-2">
                            <span>Patient In</span> <br>
                            <input type="text" class="form-control form-control-sm time_patientin mt-1" placeholder="hh:ss:mm" value="{{@$case->time_patientin}}">
                            <button id="time_patientin" type="button" class="btn btn-time-dark w-100 waves-effect mt-1 waves-light get-timestamp">
                                <i class="ri-timer-fill ri-lg"></i></button>
                        </div>
                        <div class="col-2">
                            <span>Operation Start</span> <br>
                            <input type="text" class="form-control form-control-sm time_start" placeholder="hh:ss:mm" value="{{@$case->time_start}}">

                            <button id="time_start" type="button" class="btn btn-time-dark waves-effect w-100 mt-1 waves-light get-timestamp"><i
                                class=" ri-timer-fill"></i></button>
                        </div>
                        <div class="col-2">
                            <span>Withdrawal</span> <br>
                            <input  type="text" class="form-control form-control-sm time_withdrawal" placeholder="hh:ss:mm" value="{{@$case->time_withdrawal}}">

                            <button id="time_withdrawal" type="button" class="btn btn-time-dark waves-effect mt-1 w-100 waves-light get-timestamp"><i
                                class=" ri-timer-fill"></i></button>
                        </div>
                        <div class="col-2">
                            <span>Operation End</span> <br>
                            <input  type="text" class="form-control form-control-sm time_withdrawal" placeholder="hh:ss:mm" value="{{@$case->time_withdrawal}}">

                            <button id="time_end" type="button" class="btn btn-time-dark waves-effect mt-1 w-100 waves-light get-timestamp"><i
                                class=" ri-timer-fill"></i></button>
                        </div>
                    </div> --}}


                    {{-- <div class="row mt-2">
                        <div class="col-3 align-self-center">
                            <span>Operation End</span>
                        </div>
                        <div class="col-3 p-0">
                            <input type="text" class="form-control form-control-sm time_end" placeholder="hh:ss:mm" value="{{@$case->time_end}}">
                        </div>
                        <div class="col-1">
                            <!-- Buttons Group -->
                            <button id="time_end" type="button" class="btn btn-time-dark waves-effect btn-sm waves-light get-timestamp"><i
                                    class=" ri-timer-fill"></i></button>
                        </div>
                    </div> --}}
                </div>
            </div>


        </div>
    </div>
    <div class="row p-2">
        <div class="card p-3">
            <div class="row">
                <div class="col-6">
                    Video & Photo (Click on photo to drawing)
                </div>
                <!-- <div class="col-6">
                    <button type="button" class="btn btn-primary " data-bs-toggle="modal" data-bs-target="#modal_prevideo" id="btn-openprevideo">Standard Modal</button>
                    {{-- <button type="button" class="btn btn-primary " data-bs-toggle="modal" data-bs-target="#modal_prephoto" id="btn-openprevideo">Standard Modal</button> --}}

                </div> -->
            </div>
            <div class="row p-2 mt-2" id="img_div">
                <div class="col-3 mt-2">
                    <div id="upload_photo_div" class="align-self-center takephotohide border-upload-op">
                        +
                    </div>
                    <form action="{{ url('tablet/nursenote') }}" id="upload_image_form" method="post" hidden
                        enctype="multipart/form-data">
                        @csrf
                        <input type="text" name="event" value="upload_images">
                        <input type="text" name="cid" value="{{ @$case->_id }}">
                        <input type="file" name="images[]" id="file_input" multiple>
                    </form>
                </div>
                @foreach (isset($photo) ? $photo : [] as $p)
                    @php
                        if($p['ns'] == 0){
                            continue;
                        }
                    @endphp
                    <div class="col-3 mt-2 image{{@$p['nu']}}">
                        <div class="col-12 mb-0 text-end">
                            <i class="ri-close-circle-fill ri-lg text-danger  " onclick="unselect_img('{{ @$case->_id }}', '{{ @$p['nu'] }}')"></i>
                        </div>
                        <img src="{{ mePHOTO($case->case_hn, $p['na'], $folderdate) }}?a={{ RandomString() }}"
                            class="w-100" height="250px;" alt="" style="cursor: pointer" case_id="{{ $cid }}" onclick='preview_photo("{{ mePHOTO($case->case_hn, $p["na"], $folderdate) }}?a={{ RandomString() }}")'>
                        <span onclick="to_drawing('{{ @$case->_id }}', '{{ @$p['na'] }}')"
                            class="badge text-bg-darkk d-block"><i class="ri-image-edit-fill"></i> Drawing</span>
                    </div>
                @endforeach
                @foreach ($video as $i=>$v)
                @php
                        $video_status = $case->video_status ?? [];
                        try{
                            if($video_status[$i] == 'hide'){
                                continue;
                            }
                        } catch(\Exception $e){}
                        $url = $video_url.'/'.@$v."";
                        @endphp
                    <div class="col-3 mt-2 video{{@$i}}">
                        <div class="col-12 mb-0 text-end">
                            <i class="ri-close-circle-fill ri-lg text-danger  " onclick="unselect_vdo('{{ @$case->_id }}', '{{ @$i }}')"></i>
                        </div>
                        {{-- @dd($video_url,$v); --}}
                        {{-- <video src="{{ $video_url}}/{{@$v}}?a={{ RandomString() }}" --}}
                        <video src="{{ $url}}" onclick="preview_video('{{ $url}}')"
                        class="w-100" height="250px;" alt="" style="cursor: pointer" case_id="{{ $cid }}">

                            {{-- class="w-100" height="250px;" alt="" style="cursor: pointer" case_id="{{ $cid }}" onclick="preview_video('{{ $video_url}}/{{@$v}}')"> --}}
                        </video>
                    </div>
                @endforeach
            </div>
            <div class="col-12">
                <button type="button" id="save_file" class="btn btn-primary m-3"
                    style="display: none;float: right">Upload</button>
            </div>
        </div>
    </div>

    <div class="col-12 text-end">
        <button class="btn btn-primary btn-label waves-effect right waves-light">Confirm <i
                class="ri-check-double-line label-icon"></i></button>
    </div>
@endsection

@section('script')
    <script src="{{ url('assets/libs/cleave.js/cleave.min.js') }}"></script>




    <script>

        function preview_photo(src) {
            $(".preview-img").attr('src', src)
            $("#modal_prephoto").modal("show");
        }

        function preview_video(url){
            console.log(url, 'a');
            $('.preview-video').attr('src', url)
            $("#modal_prevideo").modal('show');
        }


        // $("#btn-openprevideo").click(function() {
        //     $("#modal_prephoto").modal('show');
        // })



    </script>

    <script>
        $(".btn_changestatus").click(function() {
            let datatype = $(this).attr("data-type");
            let hn = $(this).attr("hn");
            console.log(datatype + hn);

            $.post('{{ url('api/case') }}', {
                event: 'statuschange',
                cid: "{{ @$case->_id }}",
                datatype: datatype,
                hn: hn,
            }, function(d, s) {

            });
        });

        function unselect_img(cid, img_index){
            $.post("{{url('api/photo')}}", {
                event:"unselect_image",
                cid:cid,
                img_index:img_index
            }, function(data, status){
                if(data=='success'){
                    $(`.image${img_index}`).remove()
                }
            })
        }

        function unselect_vdo(cid, vdo_index){
            $.post("{{url('api/photo')}}", {
                event:"unselect_vdo",
                cid:cid,
                vdo_index:vdo_index
            }, function(data, status){
                if(data=='success'){
                    $(`.video${vdo_index}`).remove()
                }
            })
        }

        // ----------------------------------------------------------------------------------------- //
        // timer
        var timer = null
        var elapsed_sec = 0
        var start_time = ''
        var end_time = ''

        function check_time(){
            $.post("{{url('api/case')}}",{
                event:"check_casetime",
                cid:"{{@$case->_id}}"
            }, function (data, status) {
                if(data != ''){
                    // let today           = new Date().toISOString().slice(0, 10);
                    let curr_timestart  = new Date(`${data}`)
                    let now             = new Date()
                    elapsed_sec         = Math.floor((now - curr_timestart) / 1000)
                    let split           = data.split('T')
                    start_time          = get_current_time(false, split[1])
                    change_button_status('start')
                    start_timer()
                }
            })
        }

        function start_timer() {
            timer = setInterval(function() {
                elapsed_sec++;
                update_timer_text();
            }, 1000);
        }

        function format_time(sec){
            let h = Math.floor(sec / 3600)
            let m = Math.floor((sec % 3600) / 60)
            let s = sec % 60
            return `${pad(h)}:${pad(m)}:${pad(s)}`
        }

        function pad(value) {
            return value.toString().padStart(2, '0')
        }

        function update_timer_text() {
            $('.operation-start').html(`Operation Started (Duration) <br>${format_time(elapsed_sec)}`);
        }

        function get_current_time(only_time=false, input_time=null) {
            let now = new Date();
            if(input_time){
                if (input_time.includes('T')) {
                    now = new Date(input_time);
                } else {
                    let time_parts = input_time.split(':')
                    if (time_parts.length === 3) {
                        now.setHours(parseInt(time_parts[0], 10));
                        now.setMinutes(parseInt(time_parts[1], 10));
                        now.setSeconds(parseInt(time_parts[2], 10));
                    }
                }
            }
            let date    = now.getDate();
            let month   = now.toLocaleString('default', { month: 'short' });
            let year    = now.getFullYear();
            let hours   = now.getHours();
            let minutes = now.getMinutes();
            let seconds = now.getSeconds();
            return only_time ? `${pad(hours)}:${pad(minutes)}:${pad(seconds)}` : `${pad(date)} ${month}, ${year} ${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
        }

        function get_current_date(){
            let now = new Date()
            return now.toISOString().slice(0, 10)
        }

        function set_finish(){
            console.log(start_time, end_time);
            $('.operation-start').html(`Operation Started  <br>${start_time}`);
            $('.operation-end').html(`Operation End <br>${end_time}`);
        }

        function set_casetime(key, val){
            $.post("{{url('api/case')}}",{
                event:"set_casetime",
                key:key,
                val:val,
                cid:"{{@$case->_id}}"
            }, function (data, status) {
                console.log(data);
            })
        }

        function change_button_status(type){
            if(type == 'start'){
                $(".btn-operation-start-ipad").hide();
                $(".btn-operation-ipad").show();
                $('.btn-refresh-ope').show()
                $('.operation-start').show()
                $(".takephotohide").show();
            } else if(type == 'stop'){
                $('.btn-refresh-ope').show()
                $('.operation-end').show()
            } else if(type == 'refresh'){
                $(".btn-operation-start-ipad").show();
                $(".btn-operation-ipad").hide();
                $('.btn-refresh-ope').hide()
                $('.operation-start').hide()
                $('.operation-end').hide()
            }

        }

        $(".btn-operation-start-ipad").click(function() {
            change_button_status('start')
            start_time  = get_current_time()
            elapsed_sec = 0
            update_timer_text()
            $('.time_start').val(get_current_time(true))
            set_casetime('datetime_start', `${ get_current_date()} ${get_current_time(true)}`)
            start_timer()

        })

        $(".btn-operation-ipad").on('click', function () {
            $(this).hide();
            $.post("{{url('api/case')}}",{
                event:"check_casetime",
                cid:"{{@$case->_id}}"
            }, function (data, status) {
                if(data != ''){
                    start_time          = get_current_time(false, data)
                    end_time = get_current_time()
                    $('.time_end').val(get_current_time(true))
                    set_casetime('datetime_end', `${ get_current_date()} ${get_current_time(true)}`)
                    clearInterval(timer);
                    change_button_status('stop')
                    set_finish()
                }
            })
        })

        $('.btn-refresh-ope').on('click', function () {
            // if(timer){ clearInterval(timer)  }
            // start_time = get_current_time()
            // set_casetime('datetime_start', `${ get_current_date()} ${get_current_time(true)}`)
            // elapsed_sec = 0
            // $('.operation-start').html(`Operation Started (Duration)  <br>00:00:00`);
            // start_timer()
            set_casetime('datetime_start', ``)
            set_casetime('datetime_end', ``)
            change_button_status('refresh')
        })

        check_time()

        // ----------------------------------------------------------------------------------------- //
        // operation detail

        function init_cleave(classname){
            let cleave = new Cleave(`.${classname}`, {
                time: true,
                timePattern: ['h', 'm', 's']
            });
        }

        for (let i = 0; i < $('.time-cleave').length; i++) {
            let class_name = $($('.time-cleave')[i]).data('class')
            init_cleave(class_name)
        }

        $('.get-timestamp').on('click', function (){
            let class_name = $(this).data('class')
            let curr_time  = get_current_time(true)
            $(`.${class_name}`).val(curr_time)
            set_casetime(`date${class_name}`, `${get_current_date()} ${curr_time}`)
        })

        $('.time-cleave').on('focusout', function(){
            let class_name = $(this).data('class')
            let text       = $(this).val()
            edit_time(text, class_name)
        })

        function validate_timestr(time){
            let new_time = time.trim().replace(/:/g, '');
            if(new_time.length <= 2) {
                new_time += '00';
            } else if(new_time.length === 3) {
                new_time = new_time.substring(0, 2) + '0' + new_time.substring(2);
            } else if(new_time.length > 4) {
                new_time = new_time.substring(0, 4);
            }
            let hours = new_time.substring(0, 2);
            let minutes = new_time.substring(2, 4);
            return  `${hours}:${minutes}:00`;
        }

        function edit_time(text, class_name){
            let time_value = text.trim()
            let parts = time_value.split(':').filter(part => part !== '')
            parts = parts.map((part, index) => {
                if(index === 0 || index === 2){
                    return part.padStart(2, '0')
                }
                if(index == 1 && part.length == 1){
                    return part + '0'
                }
                return part
            })

            if(parts.length == 1){
                parts.push('00', '00')
            }

            if(parts.length == 2){
                parts.push('00')
            }

            new_value = parts.slice(0, 3).join(':')
            if(parts[0]){
                if(parts[0].length >= 3 ){
                    new_value  = validate_timestr(new_value)
                }
            }

            $(`.${class_name}`).val(new_value)
            set_casetime(`date${class_name}`, `${get_current_date()} ${new_value}`)
        }

        // ------------------------------------------------------------------------------------------ //

        // $('#upload_photo_div').on('click', function (){
        //     $('#file_input').trigger("click");
        // })

        // $('#file_input').on('change', function(e) {
        //     var files = [...e.target.files]
        //     can_submit = false
        //     files.forEach((item, i) => {
        //         if ((item.type == 'image/jpeg' || item.type == 'image/png' || item.type == 'video/mp4') || item.type == 'image/tiff' ) {
        //             can_submit = true
        //         } else {
        //             can_submit = false
        //         }
        //     })
        //     if(files.length > 0 && can_submit){
        //         $('#upload_image_form').submit()
        //     }
        // })

        // ----------------------------------------------------------------------------------------- //
        // video & photo upload

        var all_files = []
        var count_file = 0
        var submit_status = true
        var scope_id = 0
        var div_id = []
        var img_src = ''

        $('#upload_photo_div').on('click', function() {
            $('#file_input').trigger("click");
        })

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

        function upload_files(files, event_type) {
            let file_temp = []
            files.forEach((item, i) => {
                if ((item.type == 'image/jpeg' || item.type == 'image/png' || item.type == 'video/mp4' || item.type == 'video/quicktime') || item
                    .type == 'image/tiff') {
                    file_temp.push(item)
                } else {
                    // call_alert('wrong type',
                    //     'Uploaded file is not a valid file. Only JPG and PNG files are allowed.')
                }
            })


            file_temp.forEach((file, i) => {
                count_file += 1
                append_file(file, count_file)
            });

            $('#save_file').css('display', 'block')
        }

        function append_file(file, i) {
            var filesize = formatBytes(parseInt(file.size))
            var inp = ''
            if (file.type == 'image/jpeg' || file.type == 'image/png') {
                inp = `<img id="preview${i}" src="" width="185px"  alt="">`
            } else if(file.type == 'video/mp4' || file.type == 'video/quicktime'){
                inp = `<video width="250" autoplay>
                          <source src="" id="preview${i}">
                       </video>`
            }

            $('#img_div').append(`
            <div class="col-auto file-upload mt-3" id="file${i}">
                ${inp}
            </div>
        `)

            $('#total_file').html(`${i}`)

            if (file.type == 'image/jpeg' || file.type == 'image/png') {
                document.getElementById(`preview${i}`).src = window.URL.createObjectURL(file)
            }
            else if(file.type == 'video/mp4' || file.type == 'video/quicktime') {
                var source = $(`#preview${i}`);
                source[0].src = URL.createObjectURL(file);
                source.parent()[0].load();
            }

            all_files.push(file)
            submit_status = true
        }

        function formatBytes(bytes, decimals = 2) {
            if (!+bytes) return '0 Bytes'
            const k = 1024
            const dm = decimals < 0 ? 0 : decimals
            const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
            const i = Math.floor(Math.log(bytes) / Math.log(k))
            return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`
        }

        function delete_file(num, file_name) {
            $(`#file${num}`).remove()
            var file_index = 99
            all_files.forEach((file, i) => {
                if (file.name == file_name) {
                    file_index = i
                }
            })
            all_files.splice(file_index, 1)
            count_file -= 1
            if (count_file < 0) {
                count_file = 0
            }
            $('#total_file').html(`${count_file}`)

        }

        $('#save_file').on('click', function() {
            if (count_file > 0) {
                $(this).attr('disabled', true)
                scope_id = '0'
                var total_files = $('.file-upload').length
                for (let j = 0; j < total_files; j++) {
                    div_id.push($($('.file-upload')[j]).prop('id'))
                }
                console.log(submit_status);
                if (submit_status) {
                    setTimeout(() => {
                        post(all_files[0], 0)
                    }, 0);
                    submit_status = false

                }
            }
        })

        function post(file, index) {
            var formData = new FormData()
            formData.append('files', file)
            formData.append('scope_id', scope_id)
            formData.append('event', 'upload_photo')
            formData.append('_id', '{{ @$case->_id }}')
            formData.append('hn', '{{ @$case->case_hn }}')
            formData.append('caseuniq', '{{ @$case->caseuniq }}')
            formData.append('index', index)

            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) {}

            function errorHandler() {
                count_file = $('.file-upload').length
                $('#curr_file').html(`${count_file}`)
            }

            function completeHandler() {
                if (index < all_files.length - 1) {
                    post(all_files[index + 1], index + 1)
                } else if (index == all_files.length - 1) {
                    submit_status = true
                    $('#save_file').attr('disabled', false)
                    all_files = []
                    count_file = 0
                    $.post("{{ url('api/photo') }}", {
                        "event": "get_screenrecord_photo",
                        "_id": "{{ @$case->_id }}"
                    }, function(data, status) {
                        console.log(data);
                        if (data == 'success') location.reload()
                    })
                }
            }
        }

        // ------------------------------------------------------------------------------------------------ //

        function to_drawing(cid, imgname) {
            location.href = `{{ url('tablet/procedure') }}?action=drawing&cid=${cid}&imgname=${imgname}`
        }

        // ------------------------------------------------------------------------------------------------ //

        function get_time() {
            let now = new Date();
            let hour = now.getHours().toString().padStart(2, '0')
            let min = now.getMinutes().toString().padStart(2, '0')
            let sec = now.getSeconds().toString().padStart(2, '0')
            let curr = hour + ':' + min + ':' + sec
            return curr
        }

        $('.get-timestamp').on('click', function() {
            let id = $(this).attr('id')
            let time = get_time()
            $(`.${id}`).val(time)
            $.post('{{ url('api/procedure') }}', {
                "event": "savejson",
                "id": "{{ @$case->_id }}",
                "name": id,
                "value": time,
                "procedure": "{{ @$case->case_procedurecode }}"
            }, function(data, status) {
                console.log(data);
            })
        })
    </script>
@endsection
