<?php
session_start();
if (isset($_SESSION['_session']['user']) &&  (time() - $_SESSION['_session']['LAST_ACTIVITY']  < $_SESSION['_session']['koha'])) {
    $_SESSION['_session']['LAST_ACTIVITY']  = time();

    if ($_SESSION['_session']['my_services_requests'] == 1 || $_SESSION['_session']['my_clinic_service_requests'] == 1) {
        require 'header.php';
?>
        <style>
            .dataTable>tbody>tr>td {
                padding: 1px !important;
            }

            .clicked {
                background-color: beige;
            }

            .cart-inform {
                /* border-style: outset; */
                border-color: #ff9800;
                box-shadow: 0 1px 4px 0 rgb(0 0 0 / 14%);
                border-radius: 10px;
                padding: 0px;
                padding-top: 15px;
                margin-left: 3px;
            }

            .modal-lg {
                max-width: 830px;
            }

            .placeholder {
                position: relative;
                display: inline-block;
            }

            .placeholder::after {
                position: absolute;
                right: 15px;
                top: 1px;
                content: attr(data-placeholder);
                pointer-events: none;
                opacity: 1;
            }
        </style>
        <div class="content-wrapper">
            <div class="content-header">
                <div class="container-fluid" style="padding-top: 20px;">
                    <div class="alert alert-danger" role="alert" style="height: 40px; padding: 10px">Porositë në Pritje</div>
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div id="tabel12"></div>
                                <div id="getpc" class="card-body">

                                    <table id="example1" class="table table-bordered table-hover">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>Institucioni</th>
                                                <th>Personi pergjegjes </th>
                                                <th>Data</th>
                                                <th>Qyteti</th>
                                                <th>Statusi</th>
                                                <th>Mundësia</th>
                                            </tr>
                                        </thead>
                                        <tbody>

                                            <?php
                                            $opts = [
                                                "http" => [
                                                    "method" => "GET",
                                                    "header" => "api_token:" . $token,

                                                ]

                                            ];
                                            $context = stream_context_create($opts);

                                            $str_data = file_get_contents($urlapi . "/getporosite/0", false, $context);
                                            $temp = '';

                                            $data = json_decode($str_data, true);

                                            if ($str_data == "[300]") {
                                            } else {
                                                $length = count($data);
                                                for ($i = 0; $i < $length; $i++) {
                                                    $temp .= "<tr><td>" . $data[$i]["Id"] . "</td>";

                                                    $temp .= "<td>" . $data[$i]["emri_institutit"] . "</td>";
                                                    $temp .= "<td>" . $data[$i]["emri"] . " " . $data[$i]["mbiemri"] . "</td>";

                                                    $temp .= "<td>" . $data[$i]["emri_qytetit"] . "</td>";
                                                    $temp .= "<td>" . $data[$i]["koha"] . "</td>";


                                                    // $temp .= "<td>" . $data[$i]["statusi"] . "</td>";
                                                    switch ($data[$i]["statusi"]) {
                                                        case 3:
                                                            $ngjyra = 'color:red;';

                                                            break;
                                                        case 0:
                                                            $ngjyra = 'color: hsl(47deg 52% 54%);';

                                                            break;
                                                        case 4:
                                                            $ngjyra = 'color:red;';

                                                            break;
                                                        case 2:
                                                            $ngjyra = 'color: green;';

                                                            break;
                                                        case 1:
                                                            $ngjyra = 'color: #ff9e0f;';

                                                            break;
                                                    }
                                                    $temp .= '<td style="' . $ngjyra . ' font-weight: 700">' . $data[$i]["emertimi"] . '</td>';

                                                    $temp .= '<td><button type="button"  onclick="shiko(' . $data[$i]["Id"] . ')" style="padding: 4px" onClick="" class="btn btn-info btn-xs" data-toggle="modal" data-target="#modal-see"><i class="material-icons">edit</i></button></td>
                                                    ';

                                                    $temp .= "</tr>";
                                                }
                                                echo $temp;
                                            }
                                            ?>





                                            </tr>

                                        </tbody>
                                    </table>

                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <script>
            histid = 0;
            cmtotal = 0;

            function shiko(id) {
                histid = id;
                $.ajax({
                    type: 'GET',
                    url: url + "/getporositepopup/" + id,

                    headers: {
                        'api_token': '<?php echo $token ?>'
                    },
                    success: function(data, textStatus, jqXHR) {
                        pj = '';
                        totali = 0.00;
                        for (var r in data) {
                            pj += '<div class="col-lg-12 cart-inform">' +
                                '<div class="row">' +
                                '<div class="col-sm-2">' +
                                '<p>' + data[r].sasia + 'x</p>' +
                                '</div>' +
                                '  <div class="col-sm-8">' +
                                ' <p style="font-size: 14px;">' + data[r].emri_pajisjes + '</p>' +
                                ' </div>' +
                                ' <div class="col-sm-2">' + data[r].cmimi + '€</div>' +
                                '</div>' +
                                ' </div>';

                            totali += parseFloat(data[r].cmimi);

                        }
                        $('#porositl').empty();
                        $(pj).appendTo('#porositl');
                        $('#totalicm').empty();
                        $('#totalicm').append(totali + '€');
                        $('#emrilab').empty();
                        $('#emrilab').append(data[0].emri_institutit);
                        $('#qytetilab').empty();
                        $('#qytetilab').append(data[0].emri_qytetit);
                        $('#emrimbiemrilab').empty();
                        $('#emrimbiemrilab').append(data[0].emri + ' ' + data[0].mbiemri);
                        $('#emaillab').empty();
                        $('#emaillab').append(data[0].perdoruesi);
                        cmtotal = totali;







                    },

                    error: function(request, textStatus, errorThrown) {
                        toastr.error(request.responseJSON.message);

                    }

                });
            }
        </script>
        <!-- Modal for Editin or Viewing Brands & Devices And Services in it -->
        <div class="modal fade" id="modal-see">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title">Kërkesa</h4>
                        <button type="button" id="closesee" class="close" data-dismiss="modal" aria-label="Close">

                            <span aria-hidden="true">×</span>
                        </button>

                    </div>
                    <div class="modal-body">
                        <div class="col-md-12 responsive">
                            <div class="row responsive" id="emridhembiemr">
                                <div class="col-sm-3">
                                    <p>Emri Laboratorit<br> <strong id="emrilab"></strong> </p>
                                </div>
                                <div class="col-sm-3">
                                    <p>Qyteti<br> <strong id="qytetilab"></strong> </p>
                                </div>
                                <div class="col-sm-3">
                                    <p>Personi përgjegjës<br> <strong id="emrimbiemrilab"></strong></p>
                                </div>
                                <div class="col-sm-3">
                                    <p>Emaili<br> <strong style="word-break: break-all;" id="emaillab"></strong></p>
                                </div>
                            </div>
                        </div>


                        <hr>
                        <div class="col-md-12" style="max-height: 420px; overflow-y: auto; overflow-x:hidden; " id="porositl">

                        </div>
                        <hr>
                        <div class="col-md-12" style="justify-content: space-between;">
                            <div class="row">
                                <div class="col-sm-10">
                                    <strong> TOTAL:</strong>
                                </div>
                                <div class="col-sm-2"><strong id="totalicm"></strong></div>
                            </div>
                            <div class="row" id="totalilr" style="display: none;">
                                <div class="col-sm-10">
                                    <strong> TOTAL ME LIRIM:</strong>
                                </div>
                                <div class="col-sm-2"><strong id="totalimelirim"></strong></div>
                            </div>
                        </div>
                        <hr>
                        <div class="col-md-12">
                            <div class="row" id="rrethporosise">
                                <div class="col-sm-2">
                                    <label>
                                        <input type="checkbox" id="koha_liferimit" name=""> Koha liferimit:
                                    </label>
                                    <script>
                                        $('#koha_liferimit').click(function(e) {
                                            if ($('#koha_liferimit').is(':checked')) {
                                                $('#datalf').show();
                                            } else {
                                                $('#datalf').val('');

                                                $('#datalf').hide();

                                            }


                                        });
                                    </script>
                                    <!-- if isnt checked date remain disable -->
                                    <input type="date" id="datalf" class="form-control" max="9999-12-31" style="display: none;">
                                </div>
                                <!-- koha liferimit ka me qen opsionale -->
                                <div class="col-sm-2">
                                    <label>
                                        Lirimi:
                                    </label>
                                    <div class="placeholder" data-placeholder="%">
                                        <input type="number" oninput="calculatePerc()" id="lirimi" max="100" class="form-control">
                                        <script>
                                            function calculatePerc() {
                                                lirimi1 = $('#lirimi').val();
                                                    lirimi = cmtotal - (cmtotal * lirimi1 / 100);
                                                    lirimi = lirimi.toFixed(2);
                                                $('#totalimelirim').text(lirimi+'€');
                                                if(cmtotal==0 ||lirimi==0.00 || lirimi1==null || lirimi1==0  ){
                                                     $('#totalilr').hide();
                                                }else{
                                                    $('#totalilr').show();
                                                }
                                            }
                                        </script>
                                    </div>

                                </div>
                                <div class="col-sm-2">
                                    <label>
                                        Afati Pageses:
                                    </label>

                                    <!-- if isnt checked date remain disable -->
                                    <input type="date" id="afatipages" class="form-control" max="9999-12-31">
                                </div>

                                <!-- komenti nese refuzohet patjeter duhet me komentu se pse po refuzohet si ktu si te kerkesa -->
                                <div class="col-sm-6 form-group bmd-form-group">
                                    <label class="form-floating bmd-label-static" style="background-color: white; left: 15px;">Komento</label>
                                    <textarea type="text" class="form-control resizable" id="komenti" style="border: 1px solid green; border-radius: 6px; "></textarea>
                                </div>
                            </div>
                        </div>

                    </div> <!-- body -->

                    <div class="modal-footer justify-content-between">
                        <button class="btn btn-sm btn-danger" id="btnrefuzo">Refuzo porosinë</button>
                        <button class="btn btn-sm btn-success" id="btnprano">Prano porosinë</button>
                        <!-- shkon direkt ne perfundim -->
                    </div>
                </div>
            </div>
        </div>
        <script>
            $('#btnrefuzo').click(function(e) {
                e.preventDefault();
                if ($('#komenti').val().length != 0) {
                    ajax = {
                        histid: histid,
                        sts: 3,
                        userid: <?php echo $_SESSION['_session']['id']; ?>,
                        Komenti: $('#komenti').val(),
                        kmnt: 1
                    }
                    $.ajax({
                        type: 'PUT',
                        url: url + "/porosiasts",
                        data: ajax,
                        headers: {
                            'api_token': '<?php echo $token ?>'
                        },
                        success: function(data, textStatus, jqXHR) {
                            toastr.success('Refuzuar me sukses');
                            setTimeout(function() {
                                window.location.replace("./Porosite_anuluara.php");
                            }, 1000);
                        },

                        error: function(request, textStatus, errorThrown) {

                        }
                    });
                } else {
                    toastr.error('Ju lutem jepni komentin');
                }
            });
            $('#btnprano').click(function(e) {
                e.preventDefault();
                validation = 0;
                if ($('#koha_liferimit').is(':checked') && $('#datalf').val().length != 0) {
                    validation = 1;
                }
                if ($('#koha_liferimit').is(':checked') == false) {
                    validation = 1;
                }
                if (validation == 1) {
                    ajax = {
                        histid: histid,
                        sts: 2,
                        userid: <?php echo $_SESSION['_session']['id']; ?>,
                        Komenti: $('#komenti').val(),
                    
                    }
                    $.ajax({
                        type: 'PUT',
                        url: url + "/porosiasts",
                        data: ajax,
                        headers: {
                            'api_token': '<?php echo $token ?>'
                        },
                        success: function(data, textStatus, jqXHR) {

                        },

                        error: function(request, textStatus, errorThrown) {

                        }
                    });
                    if ($('#datalf').val().length == 0) {
                        datall = null;
                    } else {
                        datall = $('#datalf').val();
                    }
                    if ($('#afatipages').val().length == 0) {
                        dataaf = null;
                    } else {
                    dataaf = $('#afatipages').val();
                    }
                    ajax1 = {
                        histid: histid,
                        kohaliferimit: datall,
                        Komenti: $('#komenti').val(),
                        pranuar_nga: '<?php echo  $_SESSION['_session']['id']; ?>',
                        lirimi: $('#lirimi').val(),
                       afatipages:dataaf
                    }
                    $.ajax({
                        type: 'PUT',
                        url: url + "/pranoporosi",
                        data: ajax1,
                        headers: {
                            'api_token': '<?php echo $token ?>'
                        },
                        success: function(data, textStatus, jqXHR) {
                            toastr.success('Pranuar me sukses');
                            setTimeout(function() {
                                window.location.replace("./Porosite_perfunduara.php");
                            }, 1000);
                        },

                        error: function(request, textStatus, errorThrown) {

                        }
                    });
                } else {
                    toastr.error('Ju lutem jepni daten');

                }
            });
            $('.resizable').each(function() {
                this.setAttribute('style', 'height: 60px !important;overflow-y:hidden;');
            }).on('input', function() {
                this.style.height = 'auto';
                $('.resizable').attr('style', 'height: ' + (this.scrollHeight) + 'px !important;overflow-y:hidden;');

            });
        </script>
        <!-- END modal for editin or viewing BRANDS & dEVICES and Services -->

        <script src="plugins/datatables/jquery.dataTables.min.js"></script>
        <script src="plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
        <script src="plugins/datatables-responsive/js/dataTables.responsive.min.js"></script>
        <script src="plugins/datatables-responsive/js/responsive.bootstrap4.min.js"></script>
        <script src="plugins/datatables-buttons/js/dataTables.buttons.min.js"></script>
        <script src="plugins/datatables-buttons/js/buttons.bootstrap4.min.js"></script>
        <script src="plugins/jszip/jszip.min.js"></script>
        <script src="plugins/pdfmake/pdfmake.min.js"></script>
        <script src="plugins/pdfmake/vfs_fonts.js"></script>
        <script src="plugins/datatables-buttons/js/buttons.html5.min.js"></script>
        <script src="plugins/datatables-buttons/js/buttons.print.min.js"></script>
        <script src="plugins/datatables-buttons/js/buttons.colVis.min.js"></script>
        <script src="plugins/moment/moment.min.js"></script>

        <script>
            $('#pershkrimi').each(function() {
                this.setAttribute('style', 'height:  auto  !important;overflow-y:hidden;');
            });
            $(function() {

                // start of oTable
                oTable = $("#example1").DataTable({

                    "responsive": true,
                    "lengthChange": false,
                    "autoWidth": false,
                    "buttons": ["copy", "csv", "excel", "pdf", "print", "colvis"],
                    "order": [
                        [0, "desc"]
                    ],
                    "language": {
                        "search": "",
                        "searchPlaceholder": "Kërko",
                        "lengthMenu": "Shfaq _MENU_ të dhëna për faqe",
                        "zeroRecords": "Nuk u gjet asgjë",
                        "info": "Shfaqur faqja _PAGE_ prej _PAGES_",
                        "infoEmpty": "Nuk ka të dhëna",
                        "infoFiltered": "(Filtruar _MAX_ të gjithave)",

                        "loadingRecords": "Loading...",
                        "processing": "Duke procesuar...",

                        "paginate": {
                            "first": "E para",
                            "last": "E fundit",
                            "next": "Tjetra",
                            "previous": "Para"
                        },
                    },
                    "pageLength": 10,
                    // "columnDefs": [{
                    //   "targets": [0],
                    //   "visible": false,
                    //   "order": [1, "desc"],
                    // }]

                });
                $('#example1_wrapper .col-md-6:eq(0)').append('<div class="row" ' +
                    '<div class="input-group col-3">' +
                    '<div class="col"><input class=form-control date" type="date" id="min" /></div>' +
                    '<div class="col"><input class=form-control date" type="date" id="max" /></div>' +
                    '<div class="col"><i class="material-icons dp48" id="searchbydate">search</i></div>' +
                    '</div></div>').ready(function() {
                    $('#min').val(new Date().toISOString().split('T')[0]);
                    $('#max').val(new Date().toISOString().split('T')[0]);
                });
                $('#searchbydate').on('click', function() {
                    $.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
                        var min = $('#min').val();
                        var max = $('#max').val();
                        var date = new Date(data[3]);
                        date = JSON.stringify(date);
                        date = date.slice(1, 11);
                        if ((min === '' && max === '') || (min === '' && date <= max) || (min <= date && max === '') || (min <= date && date <= max)) {
                            return true;
                        }
                        return false;
                    });

                    oTable.draw();
                });
            });
        </script>

<?php require 'footer.php';
    } else {
        header("location:./dashboard.php");
    }
} else {
    header("location:../logout.php");
}
?>