<?php
    report();
    $device = (string)($_GET["device"] ?? "");
    $agent = $_SERVER["HTTP_USER_AGENT"];
    $shelly = preg_match ("@Shelly@mus", $agent);
    if (!strlen($device) && $shelly)
        $device = "loka-cerkev";
    $iframe = (int)($_GET["iframe"] ?? 0);
    $json = $_GET["json"] ?? 0;
    include ("../sql_functions.php");
    sql_connect ("localhost", "iot", "krneki2000", "iot");

    function dan_v_tednu ($time = 0){
        if (!$time)
            $time = time();
        $dnevi = ["Nedelja", "Ponedeljek", "Torek", "Sreda", "Četrtek", "Petek", "Sobota"];
        return $dnevi[date ("w", $time)];
    }


    date_default_timezone_set('Europe/Ljubljana');
    // oblikuj tole HTML kodo med prvim in EOT za izpis

    $html =<<<EOT
    <div style="text-align: center;">{zadnji_podatki}⌚&nbsp; {cas}, 🌡️&nbsp;{temperatura}&nbsp;&deg;C, 💦&nbsp;{vlaga}%</div>
EOT;


// THE THINGS NETWORK INPUT DATA - Janez Frančiškani Maribor naprimer
$txt = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
    $txt .= file_get_contents("php://input");
    //else $txt = '{"end_device_ids":{"device_id":"mb-bazilika","application_ids":{"application_id":"otx-room-monitor"},"dev_eui":"00D10CE4D3C0C0E2","join_eui":"70B3D57ED0034217","dev_addr":"260B3F7D"},"correlation_ids":["as:up:01FPBE6KP7HASWNPB9SRYPK60A","gs:conn:01FPB7528X0E05SNBMZ4PYHWPB","gs:up:host:01FPB7529CTRE04HSXH8YFHG41","gs:uplink:01FPBE6KFN8JR2Z62JBX002X2E","ns:uplink:01FPBE6KFPJA9NDHYYSAV1NXX5","rpc:/ttn.lorawan.v3.GsNs/HandleUplink:01FPBE6KFP2YAS50AKR3JTQ099","rpc:/ttn.lorawan.v3.NsAs/HandleUplink:01FPBE6KP77M854KBSA5R9HD3Z"],"received_at":"2021-12-07T21:53:39.017103922Z","uplink_message":{"session_key_id":"AX1xoN+DlCafy7mxmjvMDA==","f_port":1,"f_cnt":183,"frm_payload":"AawCWw==","decoded_payload":{"Humidity":60.3,"Temperature":12.799999999999997},"rx_metadata":[{"gateway_ids":{"gateway_id":"maribor-pohorje-gateway"},"time":"2021-12-07T21:53:38Z","timestamp":3839868996,"rssi":-113,"channel_rssi":-113,"snr":-12,"uplink_token":"ChsKGQoXbWFyaWJvci1wb2hvcmplLWdhdGV3YXkQxID/pg4aDAjir7+NBhCli/v/AiCgk5zQ4OwB"}],"settings":{"data_rate":{"lora":{"bandwidth":125000,"spreading_factor":12}},"coding_rate":"4/5","frequency":"867700000","timestamp":3839868996},"received_at":"2021-12-07T21:53:38.806260175Z","consumed_airtime":"1.318912s","locations":{"user":{"latitude":46.56012658084421,"longitude":15.649978816509249,"source":"SOURCE_REGISTRY"}},"version_ids":{"brand_id":"onethinx","model_id":"otx18","hardware_version":"18.02","firmware_version":"1.0","band_id":"EU_863_870"},"network_ids":{"net_id":"000013","tenant_id":"ttn","cluster_id":"ttn-eu1"}}}';
if (strlen ($txt)){
    $data = json_decode ($txt, true);
    $device = "mb-bazilika";
    if (is_array($data)){
        $id = $data["end_device_ids"]["device_id"];
        $ts = iso8601_to_timestamp ($data["received_at"]);
        @$temp = $data["uplink_message"]["decoded_payload"]["Temperature"];
        @$hum = $data["uplink_message"]["decoded_payload"]["Humidity"];
        if ($temp && $hum){
            $sql = "INSERT INTO data VALUES (0, '{$id}', FROM_UNIXTIME({$ts}), {$temp}, {$hum});";
            //echo $sql;
            sql_query ($sql);
            report($id);
        }
    }
    //mb_send_mail ("matej.nastran@gmail.com", "The Things Network", $txt."\n\n".$sql, "From: iot@mase.si", "-f iot@mase.si");
    die ();
    //print_r ($data);
}


// SHELLY INPUT DATA
$temp = (float)($_GET["temp"] ?? 0.0);
$hum = (float)($_GET["hum"] ?? 0.0);
// novi shelly imajo bodisi samo hum ali samo temp parameter, stari pa vedno oba, zato za nove poiščem podatek v bazi
if (($temp != 0.0 || $hum != 0.0) && $shelly){
    if ($hum == 0.0)
        $hum = (float)get_value ("SELECT * FROM data WHERE device = '{$device}' AND hum > 0 ORDER BY ts DESC LIMIT 1;", "hum");
    if ($temp == 0.0)
        $temp = (float)get_value ("SELECT * FROM data WHERE device = '{$device}' AND temp > 0 ORDER BY ts DESC LIMIT 1;", "temp");
    $ts = time();
    $sql = "INSERT INTO data VALUES (0, '{$device}', FROM_UNIXTIME({$ts}), {$temp}, {$hum});";
    //echo $sql;
    sql_query ($sql);
    report($device, $sql);
    die ();
    die  ("Izvedel ".$sql);
}

if (!strlen($device))
    die ("Nic ni tu za vas.");


/////////////////// od tu naprej pravilo stvari ne spreminjaš
    if (!$json){

    ?>
    <!DOCTYPE html>
    <html lang="sl">
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Temperatura in vlaga v <?=$device;?></title>
        <?php             if (!$iframe){ ?>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" integrity="sha512-s+xg36jbIujB2S2VKfpGmlC3T5V2TF3lY48DX7u2r9XzGzgPsa6wTpOQA7J9iffvdeBN0q9tKzRxVxw1JviZPg==" crossorigin="anonymous"></script>
        <?php } ?>
    </head>
      <body>
    <?php
    } // not json    

        //var_dump ($rows);
        //die();
        $device2 = sql_escape ($device);
        $days = (int)($_GET["days"] ?? 0);
        if (!$days)
            $days = 7;
        if ($iframe)
            $days = 99999;
        $data = get_rows ($sql = "SELECT *, UNIX_TIMESTAMP(ts) AS ts2 FROM data WHERE device LIKE '{$device2}' AND DATE_ADD(ts, INTERVAL {$days} DAY) > NOW() ORDER BY ts;");
        if (count($data) == 0)
            die ("Ta naprava ne obstaja ali pa v zadnjih {$days} ni poslala podatkov!");
        $t_data = $v_data = [];
        foreach ($data as $row){
            $t_data [] = "{x: moment(\"".date("Y-m-d H:i:s", $row["ts2"])."\"), y: {$row["temp"]}}";
            $v_data [] = "{x: moment(\"".date("Y-m-d H:i:s", $row["ts2"])."\"), y: {$row["hum"]}}";
            $last_row = $row;
       }
       //$html = str_replace (["{zadnji_podatki}", "{cas}", "{temperatura}", "{vlaga}"], [$iframe ? "" : "Zadnji podatki: ", dan_v_tednu($last_row["ts2"]).date (" G:i", $last_row["ts2"]), $last_row["temp"], $last_row["hum"]], $html);
       if ($json){
        $out = ["datetime"=>$last_row["ts"], "timestap"=>$last_row["ts2"],  "temperature"=>$last_row["temp"], "humidity"=>$last_row["hum"]];
        header('Content-Type: application/json; charset=utf-8');
        die (json_encode ($out));
       }
       $html = str_replace (["{zadnji_podatki}", "{cas}", "{temperatura}", "{vlaga}"], [$iframe ? "" : "Zadnji podatki: ", date ("j. n. Y G:i", $last_row["ts2"]), $last_row["temp"], $last_row["hum"]], $html);
       $dni = "";
       $tmp = preg_replace ("@[\?&]days=\d+@mius", "", $_SERVER["REQUEST_URI"]);
       foreach ([1, 3, 7, 14, 21, 30, 60, 90, 180, 365, 999] as $m){
           $dni .= "&nbsp;<a href=\"{$tmp}&amp;days={$m}\">{$m}</a>&nbsp;";
       }
       if (!$iframe) {
    ?>
    <div style="width:100%;">
    <div style="text-align: center"><?=$html;?>
<br>
Podatki zadnjih: <?=$dni;?> dni</div>
        <canvas id="canvas"></canvas>
    </div>
    <script>
    var ctx = document.getElementById('canvas').getContext('2d');
    var timeFormat = 'DD.MM.YYYY HH:mm';
    var myChart = new Chart(ctx, {
        type: 'line',
        data:
            { datasets:
                [
                    { label: "Temperatura", fill: false, borderColor: "Red", data: [
                     <?= implode (", ", $t_data); ?>
                ]},
             { label: "Vlaga", fill: false, borderColor: "Blue", data: [
                <?= implode (", ", $v_data); ?>

                ]
            }]},
        options: {

         responsive: true,
                title:      {
                    display: true,
                    text:    "Temperatura in vlaga v <?=$device;?>"
                },




           scales: {
                        xAxes: [{
                            type: "time",
                            time:       {
                               format: timeFormat,
                               tooltipFormat: timeFormat
                            },
                            display: true,
                            scaleLabel: {
                                display: true,
                                labelString: 'Kdaj'
                            }
                        }],
                        yAxes: [{
                            display: true,
                            scaleLabel: {
                                display: true,
                                labelString: 'Vrednost'
                            }
                        }]
             }


       }

    });</script>
<?php
}    // if (!$iframe)
else echo $html;
?>
    </body>
    </html>
<?php

function iso8601_to_timestamp ($iso){
    return strtotime (preg_replace ("@\.\d+(Z)$@mius", "\\1", $iso));
}

function report ($device = "", $sql = ""){
    return;
    $url = "https://iot.mase.si/?device=".rawurlencode ($device);
    $txt = "\n----------------------------\n".date ("j.n.Y G:i:s")."\n{$url}\n";
    if (strlen ($sql))
        $txt .= "SQL: {$sql}\n";
    $txt .= file_get_contents("php://input")."\n";   
    $txt .= print_r ($_REQUEST, true);
    $txt .= print_r ($_SERVER, true);
    
    mb_send_mail ("matej.nastran@gmail.com", "IOT {$device} data 🌡️💦", $txt, "From: iot@mase.si", "-f iot@mase.si");
}
