<?php
session_start();
error_reporting(0);
include('includes/config.php');
if(strlen($_SESSION['alogin'])=="")
    {   
    header("Location: index.php"); 
    }
    else{
        ?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
    	<meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Automatic Weather Station System | Dashboard</title>
        <link rel="stylesheet" href="css/bootstrap.min.css" media="screen" >
        <link rel="stylesheet" href="css/font-awesome.min.css" media="screen" >
        <link rel="stylesheet" href="css/animate-css/animate.min.css" media="screen" >
        <link rel="stylesheet" href="css/lobipanel/lobipanel.min.css" media="screen" >
        <link rel="stylesheet" href="css/toastr/toastr.min.css" media="screen" >
        <link rel="stylesheet" href="css/icheck/skins/line/blue.css" >
        <link rel="stylesheet" href="css/icheck/skins/line/red.css" >
        <link rel="stylesheet" href="css/icheck/skins/line/green.css" >
        <link rel="stylesheet" href="css/main.css" media="screen" >
    	<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
	    <!--<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" />-->
        
         
    </head>
    <body class="top-navbar-fixed">
        <div class="main-wrapper">
              <?php include('includes/topbar.php');?>
            <div class="content-wrapper">
                <div class="content-container">

                   

                    <div class="main-page">
                        <div class="container-fluid">
                            <div class="row page-title-div">
                                <div class="col-sm-6">
                                    <h2 class="title">Dashboard</h2>
                                  
                                </div>
                                <!-- /.col-sm-6 -->
                            </div>
                            <!-- /.row -->
                      
                        </div>
                        <!-- /.container-fluid -->

                        <section class="section">
                            <div class="container-fluid">
				<div class="row">
    				<div id="reportrange" class="col-md-6" style="left:17px;margin-bottom:10px;background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc;">
    				    <i class="fa fa-calendar"></i>&nbsp;
    				    <span></span> <i class="fa fa-caret-down"></i>
    				</div>
				    <div class="col-md-6" style="left: 25px;">
				        <!--<button type="button" id="showlive" class="btn btn-success">Show Live</button> -->
				        <span style="margin-left: 110px;"><strong> Last Updated : </strong> <span style="color:green; font-weight:bold;" class="lastupdated"> </span> </span>
				    </div>
				</div>
				<div id='temp'><!-- Plotly chart will be drawn inside this DIV --></div>
				<br/><br/>
				<!--<div id='wrose'></div> <!-- Plotly chart will be drawn inside this DIV -->
                                <div class="row">
                                    <div id="" class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
                						<?php 
                						    $selectTable = SELECT_TABLE;
                							$sql1 = "SELECT * from $selectTable order by CreationDate desc limit 20";
                							$query1 = $dbh->prepare($sql1);
                							$query1->execute();
                							$results1 = $query1->fetchAll(PDO::FETCH_OBJ);
                							//$totalstudents=$query1->rowCount();
                						?>
                                    </div>

                                </div>
                                <!-- /.row -->
                            </div>
                            <!-- /.container-fluid -->
                        </section>
                        <!-- /.section -->

                    </div>
                    <!-- /.main-page -->

                    
                </div>
                <!-- /.content-container -->
            </div>
            <!-- /.content-wrapper -->

        </div>
        <!-- /.main-wrapper -->

        <!-- ========== COMMON JS FILES ========== -->
        <script src="js/jquery/jquery-2.2.4.min.js"></script>
        <script src="js/jquery-ui/jquery-ui.min.js"></script>
        <script src="js/bootstrap/bootstrap.min.js"></script>
        <script src="js/pace/pace.min.js"></script>
        <script src="js/lobipanel/lobipanel.min.js"></script>
        <script src="js/iscroll/iscroll.js"></script>

	<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
	<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
	<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
		<!--<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/js/all.min.js"></script>-->
        <!-- ========== PAGE JS FILES ========== -->
        <script src="js/prism/prism.js"></script>
        <!--script src="js/waypoint/waypoints.min.js"></script-->
        <!--script src="js/counterUp/jquery.counterup.min.js"></script-->
        <script src="js/amcharts/amcharts.js"></script>
        <script src="js/amcharts/serial.js"></script>
        <script src="js/amcharts/plugins/export/export.min.js"></script>
        <link rel="stylesheet" href="js/amcharts/plugins/export/export.css" type="text/css" media="all" />
        <script src="js/amcharts/themes/light.js"></script>
        <script src="js/toastr/toastr.min.js"></script>
        <script src="js/icheck/icheck.min.js"></script>
        <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>

        <!-- ========== THEME JS ========== -->
        <script src="js/main.js"></script>
        <script src="js/production-chart.js"></script>
        <script src="js/traffic-chart.js"></script>
        <script src="js/task-list.js"></script>
        <script>
            //$(function(){
	    $(document).ready(function(){
		var stTime = moment().subtract({'days': 1}).format('YYYY-MM-DD hh:mm:ss')
		//var enTime = moment().subtract({'days': 10}).format('YYYY-MM-DD hh:mm:ss')
		var enTime = moment().add({'days': 1}).format('YYYY-MM-DD hh:mm:ss')
		var mPlot = document.getElementById('temp')
		//console.log(mPlot);
		localStorage.setItem("filter", false);

		function testFilter(){
			//console.log("Testing...")
			var filter = localStorage.getItem("filter");
			console.log("Testing...", filter);
			if(filter == "false"){
			    console.log("Calling...", filter);
			    applyFilter(stTime, enTime);
			}
		}
		
		$( "#showlive" ).click(function() {
		    console.log("Now Live")
            localStorage.setItem("filter", false);
            applyFilter(stTime, enTime);
            
        });
        
     
        
		(function worker() {
		    testFilter()
		    setTimeout(worker, 10000);
		})();

		applyFilter(stTime, enTime);
		//var simple = '<?php echo $results1; ?>';
		//var awsData = <?php echo json_encode($results1); ?>;
		//console.log("results", awsData)

                // Welcome notification
                toastr.options = {
                  "closeButton": true,
                  "debug": false,
                  "newestOnTop": false,
                  "progressBar": false,
                  "positionClass": "toast-top-right",
                  "preventDuplicates": false,
                  "onclick": null,
                  "showDuration": "300",
                  "hideDuration": "1000",
                  "timeOut": "5000",
                  "extendedTimeOut": "1000",
                  "showEasing": "swing",
                  "hideEasing": "linear",
                  "showMethod": "fadeIn",
                  "hideMethod": "fadeOut"
                }
                toastr["success"]( "Welcome to Automatic Weather Station System!");


	    function applyFilter(start, end) {
		//console.log("applying filter", start, end)
		if (start === '' && end === '') {
			start = moment().subtract({'hours': 1})
			end = moment()
		}
		
		$.ajax({                                                                                                             	
                   type: "POST",
                   url: 'applyfilter.php',
                   async:false,
                   data: {start: start, end: end },
                   success: function(res)
                   {
                      //console.log('res is ', JSON.parse(res));
                	sensData = JSON.parse(res);
                                                                                                                                      
                      //parseData(resParse)
                                                                                                                                      
                      var TempMin = [];
                      var TempAvg = [];
                      var TextData = [];
                      
                      var RainAvg = [];
                      var RainMinMax = [];
                      var TextRain = [];
                      
                      var RHAvg = [];
                      var RHMinMax = [];
                      var TextRH = [];
                      
                      var BPAvg = [];
                      var BPMinMax = [];
                      var TextBP = [];
                      
                      var SolarAvg = [];
                      var SolarMinMax = [];
                      var TextSolar = [];
                      
                      var WSAvg = [];
                      var WSMinMax = [];
                      var TextWS = [];
                      
                      var WD = [];
                      
                      
                      var timestamp = [];
                      
               
               if (sensData.length > 0) {
                      $('.lastupdated').empty();
                      $('.lastupdated').html(sensData[sensData.length - 1]["CreationDate"]);
                                                                                                                                      
                                                                                                                                      
                      for (let i = 0; i < sensData.length; i++) {  			
                      	//Temp Data
                      	//console.log("Data is ", sensData[i])
                      	a = {"max": sensData[i]["TMPmax"], "min": sensData[i]["TMPmin"]}
                      	TempMin[i] = a;
                      	TempAvg[i] = sensData[i]["TMPavg"]
                                                                                                   
                      	//b = {"max": sensData[i]["RAINmax"], "min": sensData[i]["RAINmin"]}
                      	RainAvg[i] = sensData[i]["RAINavg"]
                      	//RainMinMax[i] = b
                                                                                                   
                      	//c = {"max": sensData[i]["BPmax"], "min": sensData[i]["BPmin"]}
                      	BPAvg[i] = sensData[i]["BPavg"]
                      	//BPMinMax[i] = c
                                                                                                   
                      	d = {"max": sensData[i]["RHmax"], "min": sensData[i]["RHmin"]}
                      	RHAvg[i] = sensData[i]["RHavg"]
                      	RHMinMax[i] = d
                                                                                                   
                      	//e = {"max": sensData[i]["SOLARmax"], "min": sensData[i]["SOLARmin"]}
                      	SolarAvg[i] = sensData[i]["SOLARavg"]
                      	//SolarMinMax[i] = e
                                                                                                   
                      	f = {"max": sensData[i]["WSmax"], "min": sensData[i]["WSmin"]}
                      	WSAvg[i] = sensData[i]["WSavg"]
                      	WSMinMax[i] = f
                      	
                      	WD[i] = sensData[i]["WD"]
                                                                                                   
                      	timestamp[i] =  sensData[i]["CreationDate"]
                      }
                      
               }
                               
                    //console.log("Temp data", TempAvg, RHAvg, BPAvg, SolarAvg, WSAvg, RainAvg, TempMin)                                                                                                                  
                                                                                                                                      
                //       for (let i = 0; i < TempAvg.length; i++) { 
                //       	TextData[i] = "Max: " + TempMin[i]["max"].toString() + " Min: " + TempMin[i]["min"].toString()
                //       }
                //     //   for (let i = 0; i < RainAvg.length; i++) { 
                //     //   	TextRain[i] = "Max: " + RainMinMax[i]["max"].toString() + " Min: " + RainMinMax[i]["min"].toString()
                //     //   }
                //       for (let i = 0; i < RHAvg.length; i++) { 
                //       	TextRH[i] = "Max: " + RHMinMax[i]["max"].toString() + " Min: " + RHMinMax[i]["min"].toString()
                //       }
	               ////   for (let i = 0; i < SolarAvg.length; i++) { 
                // //       	TextSolar[i] = "Max: " + SolarMinMax[i]["max"].toString() + " Min: " + SolarMinMax[i]["min"].toString()
                // //       }
                //     //   for (let i = 0; i < BPAvg.length; i++) { 
                //     //   	TextBP[i] = "Max: " + BPMinMax[i]["max"].toString() + " Min: " + BPMinMax[i]["min"].toString()
                //     //   }
                //       for (let i = 0; i < WSAvg.length; i++) { 
                //       	TextWS[i] = "Max: " + WSMinMax[i]["max"].toString() + " Min: " + WSMinMax[i]["min"].toString()
                //       }
                      		
                     
                                                                                                                                      
                      var RainAvg2 = {
                        y: RainAvg,
                        x : timestamp,
                        //type: 'scatter',
                        name: 'Rain',
                        mode: 'lines+markers',
                        //text : TextRain
                      };
                      
                      var RHAvg2 = {
                        y: RHAvg,
                        x : timestamp,
                        //type: 'scatter',
                        name: 'Humidity',
                       // text : TextRH,
                        mode: 'lines+markers'
                      };
                      
                      var TempAvg2 = {
                        y: TempAvg,
                        x : timestamp,
                        text : TextData,
                        name: 'Temperature Avg',
                        //type: 'scatter',
                        mode: 'lines+markers',
                
                      };
                      
                      
                      var SolarAvg2 = {
                        y: SolarAvg,
                        x : timestamp,
                        //type: 'lines',
                        //type: 'scatter',
                        name: 'Solar Avg',
                        //text : TextSolar,
                         type: 'scatter',
                         mode: 'lines+markers'
                      };
                      
                      var WSAvg2 = {
                        y: WSAvg,
                        x : timestamp,
                        //type: 'scatter',
                        name: 'WS Avg',
                        //text : TextWS,
                         type: 'scatter',
                         mode: 'lines+markers'
                      };
                      
                      var BPAvg2 = {
                        y: BPAvg,
                        x : timestamp,
                        //type: 'scatter',
                        name: 'BP Avg',
                        //text : TextWS
                         type: 'scatter',
                         mode: 'lines+markers'
                      };
                      
                      var WD2 = {
                        y: WD,
                        x : timestamp,
                        //type: 'scatter',
                        name: 'Wind Direction',
                        //text : TextWS
                         type: 'scatter',
                         mode: 'lines+markers'
                      };
                      
                      var layout = {
                        hovermode:'closest',
                        title: 'AWS Data',
                        
                      };
                      var data = [TempAvg2, RainAvg2, BPAvg2, SolarAvg2, WSAvg2, RHAvg2, WD2];
                      //console.log('mplot', mPlot);
                      var config = {responsive: true}
                      
                      Plotly.newPlot('temp', data, layout, config);
                      
                      
                    //   var data1 = [{
                    //     r: WSAvg,
                    //     theta: ["North", "N-E", "East", "S-E", "South", "S-W", "West", "N-W"],
                    //     name: "11-14 m/s",
                    //     marker: {color: "rgb(106,81,163)"},
                    //     type: "barpolar"
                    //   }]
                    //   var layout1 = {
                    //         title: "Wind Speed Distribution in Noida, NE",
                    //         font: {size: 16},
                    //         legend: {font: {size: 16}},
                    //         polar: {
                    //           barmode: "overlay",
                    //           bargap: 0,
                    //           radialaxis: {ticksuffix: "%", angle: 45, dtick: 20},
                    //           angularaxis: {direction: "clockwise"}
                    //         }
                    //     }
                        
                    //     Plotly.newPlot("wrose", data1, layout1)
                      
                      
                   },
                   error: function() {
                        console.log("unsuccessful");
                                                                                     
                   }
              //     }   
                   
                });
                
	    }
	    //var mPlot = document.getElementById('temp')
	   // console.log('mplot', mPlot);
	    mPlot.on('plotly_legendclick', function(data){
	        //console.log('mplot', mPlot);
	        localStorage.setItem("filter", true);

	    })
	    mPlot.on('plotly_legenddoubleclick', function(data){
	        //console.log('mplot d click', mPlot);
	        localStorage.setItem("filter", true);
	        
	    });

// [layerslider id="2"]
	    
	    var start = moment().subtract(29, 'days');
	    var end = moment();
	    
	    function cb(start, end) {
	        $('#reportrange span').html(start.format('MMMM D, YYYY hh:mm A') + ' - ' + end.format('MMMM D, YYYY hh:mm A'));
	    }
	    
	    $('#reportrange').daterangepicker({
	        timePicker: true,
	        startDate: start,
	        endDate: end,
	        locale: {
	           format: 'M/DD hh:mm A'
	        },
	        ranges: {
	           'Today': [moment(), moment()],
	           'Last 1 hour': [moment().subtract({'hours': 1}), moment()],
	           'Last 24 hour': [moment().subtract({'hours': 25}), moment()],
	           'Last 12 hour': [moment().subtract({'hours': 13}), moment()],

	    //       'Last 7 Days': [moment().subtract(6, 'days'), moment()],
	     //      'Last 30 Days': [moment().subtract(29, 'days'), moment()],
	      //     'This Month': [moment().startOf('month'), moment().endOf('month')],
	        //   'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
	        }
	    }, cb);
	    
	    cb(start, end);
	    
	    var mself = this
	    $('#reportrange').on('apply.daterangepicker', function(ev, picker) {
		  //console.log(picker.startDate.format('YYYY-MM-DD hh:mm:ss'));
		  //console.log(picker.endDate.format('YYYY-MM-DD hh:mm:ss'));
		  var start = picker.startDate.format('YYYY-MM-DD hh:mm:ss')
		  var end = picker.endDate.format('YYYY-MM-DD hh:mm:ss')
		  localStorage.setItem("filter", true);

		  applyFilter(start, end) 

	    });
	  
	    
	    
          });

        </script>
    </body>
</html>
<?php } ?>
