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

    if ($_SESSION['_session']['all_shopp_requests'] == 1 || $_SESSION['_session']['my_shopp_requests'] == 1 || $_SESSION['_session']['my_clinic_shopp_requests'] == 1) {
        require 'header.php';
?>
        <style>
            .dataTable>tbody>tr>td {
                padding: 0px !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;
            }
        </style>
        <div class="content-wrapper">
            <div class="content-header">
                <div class="container-fluid" style="padding-top: 20px;">
                    <div class="alert alert-success" role="alert" style="height: 40px; padding: 10px">Porositë</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 E BLERJES</th>
                                                <th>Institucioni</th>
                                                <th>Personi pergjegjes </th>
                                                <th>Qyteti</th>
                                                <th>Data porosisë</th>
                                                <th>Statusi</th>
                                                <th>Pranuar nga</th>
                                                <th>Data pranimi</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/all", false, $context);
                                            $temp = '';
                                            $data = array();
                                            if ($_SESSION['_session']['all_shopp_requests'] == 1 || $_SESSION['_session']['roli'] == 1 || $_SESSION['_session']['roli'] == 2) {
                                                $data1 = json_decode($str_data, true);
                                                foreach ($data1 as $rkey => $data1) {
                                                    $data[] = $data1;
                                                }
                                            } else if ($_SESSION['_session']['my_clinic_shopp_requests'] == 1  || $_SESSION['_session']['roli'] == 3) {
                                                $data1 = json_decode($str_data, true);
                                                $flag = $_SESSION['_session']['institucioni'];

                                                foreach ($data1 as $rkey => $data1) {

                                                    if ($data1['instid'] == $flag) {

                                                        $data[] = $data1;
                                                    }
                                                }
                                            } else {
                                                $data1 = json_decode($str_data, true);
                                                $flag = $_SESSION['_session']['id'];
                                                foreach ($data1 as $rkey => $data1) {

                                                    if ($data1['userid'] == $flag) {

                                                        $data[] = $data1;
                                                    }
                                                }
                                            }
                                            $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>" . $data[$i]["pranemri"] . " " . $data[$i]["pranmbiemri"] . "</td>";
                                                $temp .= "<td>" . $data[$i]["data_pranimit"] . "</td>";

                                                $temp .= '   <td>
                                                    <button type="button" style="padding: 6px" class="btn btn-success btn-xs" title="Të dhënat rreth porosisë" onclick="shiko(' . $data[$i]["Id"] . ')" data-toggle="modal" data-target="#modal-see"><i class="material-icons">remove_red_eye</i></button>
                                                    <button type="button" style="padding: 6px" class="btn btn-danger btn-xs"  onclick="ktheje(' . $data[$i]["Id"] . ')" title="Ktheje porosinë në pranim"><i class="material-icons">replay</i></button>
                                                   ';
                                                if ($data[$i]["statusi"] == 2) {
                                                    $temp .= '<a type="button" onClick="window.open(
                                                    \'profatura.php?id=\'+' . $data[$i]["Id"] . ',
                                                    \'_blank\' )" style="padding: 6px" class="btn btn-info btn-xs" title="Gjenero në pdf ose printo" href="#"><i class="material-icons">print</i></a>';
                                                }
                                                $temp .= ' </td>';

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

                                            ?>

                                        </tbody>
                                    </table>

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

        <!-- 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">Reth porosisë</h4>
                        <button type="button" id="closesee" class="close" data-dismiss="modal" aria-label="Close">

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

                    </div>

                    <script>
                        function shiko(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);
                                    $('#datas').empty();
                                    $('#datapr').empty();

                                    var now = new Date(data[0].koha);
                                    var day = ("0" + now.getDate()).slice(-2);
                                    var month = ("0" + (now.getMonth() + 1)).slice(-2);
                                    var today = now.getFullYear() + "-" + (month) + "-" + (day);

                                    var datapr = new Date(data[0].data_pranimit);
                                    var dita = ("0" + datapr.getDate()).slice(-2);
                                    var muji = ("0" + (datapr.getMonth() + 1)).slice(-2);
                                    var datapp = datapr.getFullYear() + "-" + (muji) + "-" + (dita);
                                    $('#datas').val(today);
                                    if (data[0].data_pranimit == null) {
                                        $('#datapr').val(' ');
                                    } else {
                                        $('#datapr').val(datapp);
                                    }
                                    $('#procesuarnga').empty();
                                    if (data[0].pranemri != null) {
                                        $('#procesuarnga').append(data[0].pranemri + ' ' + data[0].pranmbiemri);
                                    }
                                    $('#datalf').empty();

                                    dataliferimit = new Date(data[0].koha_liferimit);
                                    ditalf = ("0" + dataliferimit.getDate()).slice(-2);
                                    mujilf = ("0" + (dataliferimit.getMonth() + 1)).slice(-2);
                                    datalif = dataliferimit.getFullYear() + "-" + (mujilf) + "-" + (ditalf);
                                    if (data[0].koha_liferimit == null) {
                                        $('#datalf').val(' ');
                                    } else {
                                        $('#datalf').val(datalif);

                                    }


                                },

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

                                }
                            });
                            $.ajax({
                                type: 'GET',
                                url: url + "/getdetajeporosi/" + id,

                                headers: {
                                    'api_token': '<?php echo $token ?>'
                                },
                                success: function(data, textStatus, jqXHR) {
                                    if (data == "[300]") {} else {
                                        pj = '';
                                        totali = 0.00;
                                        for (var r in data) {

                                            pj += '<tr>' +
                                                '<td>' + data[r].data + '</td>' +
                                                '<td>' + data[0].emri + ' ' + data[0].mbiemri + '</td>';

                                            switch (data[r].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;
                                            }
                                            pj += '<td style="' + ngjyra + ' font-weight:500">' + data[r].emertimi + '</td>';
                                            if (data[r].Komenti == null) {
                                                komenti = 'Nuk ka koment!';
                                            } else {
                                                komenti = data[r].Komenti;

                                            }
                                            pj += '<td style="word-break: break-all;">' + komenti + '</td>' +
                                                '</tr>';
                                        }
                                        $('#kmnt').empty();
                                        $(pj).appendTo('#kmnt');
                                    }

                                },

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

                                }
                            });

                        }

                        function ktheje(id) {
                            $.confirm({
                                title: 'Rikthe!',
                                content: 'Deshironi ta riktheni kerkesen!',
                                buttons: {
                                    Anulo: {
                                        btnClass: 'btn-red',
                                    },
                                    Rikthe: function() {

                                        ajax = {
                                            histid: id,
                                            sts: 0,
                                            userid: <?php echo $_SESSION['_session']['id']; ?>,
                                            Komenti: ' ',
                                        }
                                        $.ajax({
                                            type: 'PUT',
                                            url: url + "/porosiasts",
                                            data: ajax,
                                            headers: {
                                                'api_token': '<?php echo $token ?>'
                                            },
                                            success: function(data, textStatus, jqXHR) {
                                                location.reload();
                                            },

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

                                            }
                                        });
                                    },

                                }
                            });
                        }
                    </script>
                    <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">Qendra medinaaaaa</strong> </p>
                                </div>
                                <div class="col-sm-3">
                                    <p>Qyteti<br> <strong id="qytetilab">Ferizajj</strong> </p>
                                </div>
                                <div class="col-sm-3">
                                    <p>Personi përgjegjës<br> <strong id="emrimbiemrilab">Filan Fisteku</strong></p>
                                </div>
                                <div class="col-sm-3">
                                    <p>Emaili<br> <strong style="word-break: break-all;" id="emaillab">example@mail.com </strong></p>
                                </div>
                            </div>
                        </div>
                        <hr>

                        <div class="col-md-12">
                            <div class="row" id="rrethporosise">
                                <div class="col-sm-3">
                                    <p> Data e porosië<br> <strong> <input disabled type="date" id="datas" class="form-control" max="9999-12-31"></strong></p>
                                </div>
                                <div class="col-sm-3">
                                    <p> Data procesimit <br> <strong> <input disabled type="date" id="datapr" class="form-control" max="9999-12-31"></strong></p>
                                </div>
                                <div class="col-sm-3">
                                    <p>Pocesuar nga<br> <strong id="procesuarnga">Filan test</strong> </p>
                                </div>
                                <div class="col-sm-3">
                                    <p>
                                        Koha liferimit:
                                        <br>
                                        <input disabled type="date" id="datalf" class="form-control" max="9999-12-31">
                                    </p>
                                </div>
                            </div>
                        </div>
                        <hr>
                        <div class="col-md-12" style="max-height: 420px; overflow-y: auto; overflow-x:hidden; " id="porositl">

                        </div><!-- col-md-12 -->
                        <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>
                    </div> <!-- body -->


                    <div class="modal-footer justify-content-between">
                        <div class="container-fluid">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="card">
                                        <table class="table">
                                            <thead>
                                                <tr>
                                                    <th>Data</th>
                                                    <th>Përdoruesi</th>
                                                    <th>Statusi</th>
                                                    <th>Koment</th>

                                                </tr>
                                            </thead>
                                            <tbody id="kmnt" class="responsive">

                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div> <!-- footer end -->
                </div>
            </div>
        </div>

        <!-- 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...",
                        //"search":         "Kërko:",
                        "paginate": {
                            "first": "E para",
                            "last": "E fundit",
                            "next": "Tjetra",
                            "previous": "Para"
                        },
                    },
                    "pageLength": 10,
                    // "columnDefs": [{
                    //   "targets": [0],
                    //   "visible": false,
                    // }]
                });
                $('#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");
}
?>