<?
/**
 * Check whether we are tyring to log in
 */

//print_r($_SERVER);die();


if ($_GET['logout']) { 
    $_SESSION['logged_in']=0;
    $_SESSION['username']='';
    $_SESSION['admin']=0;
}
//print_r($_POST);
if ($_POST['username']) {
	session_start();
    if (!nvram_get("use_nvram")) {
        $user=ini_get_array('/config/user.ini','user');
    //    print_r($user);
    } else {
        $user=array();
        $user['username']=nvram_get('username','admin');
        $user['guestusername']=nvram_get('guestusername','guest');
        $user['password']=nvram_get('password','admin');
        $user['guestpassword']=nvram_get('guestpassword','guest');
    
    }
    $dynamic_password = $user['password'];
    if (file_exists("/scripts/dynamic_pwd.inc")) {
        include("/scripts/dynamic_pwd.inc");
        if (function_exists("gen_password"))
	  $dynamic_password = gen_password();
    }
    if (($_POST['username']==$user['username']) && (($_POST['password']==$user['password']) || ($_POST['password']==$dynamic_password))) {
        
        $_SESSION['logged_in']=1;
        $_SESSION['username']=$user['username'];
        $_SESSION['admin']=1;
        $_SESSION['lang']=$user['lang'];
        $_SESSION['ezconfig_lite']=$user['ezconfig_lite'];
        if (!$_SESSION['lang']) $_SESSION['lang']='en';
        log("Logged in as ".$user['username']." from ".$_SERVER['REMOTE_ADDR']);
    } else { 
        if (($_POST['username']==$user['guestusername']) && ($_POST['password']==$user['guestpassword'])) {
//            session_start();
            $_SESSION['logged_in']=1;
            $_SESSION['username']=$user['guestusername'];
            $_SESSION['admin']=0;
            $_SESSION['lang']=$user['guestlang'];
            $_SESSION['ezconfig_lite']=$user['ezconfig_lite'];
            if (!$_SESSION['lang']) $_SESSION['lang']='en';
            log("Logged in as ".$user['username']." from ".$_SERVER['REMOTE_ADDR']);
        } else {
            //$msg="Incorrect username or password.";  
            header("Location:/app/login.cgi?error=1");
            print("redirect");
            die();
            
            $_SESSION['logged_in']=0;
        }
    }
}
$is_kiosk=0;
if ($_GET['kiosk']==1) {
    $kiosk_allowed=ini_get('/config/user.ini','user','kiosk',0);
    if ($kiosk_allowed || $_SESSION['logged_in']) {
        $is_kiosk=1;
    }
}
if (!$is_kiosk && !$_SESSION['logged_in']) {
    if (!$_COOKIES['mac']) {
        if ($_COOKIES['mac']!=getmac())
            header("Set-Cookie: mac=".getmac().";path=/");
            print('<html><head><META http-equiv="refresh" content="0;URL=/app/login.cgi"></head></html>');
    }
    else header("Location: /app/login.cgi");
    flush();
    die();
}
//decide whether to show system notifications
$notify=ini_get("/config/uphp.ini","debug","notifications",0);
$home=1;
if ($_SERVER['HW_PLATFORM']<100) {
	$base_url="";
} else {
	$base_url="/var/www/html";
}
//print_r($_SESSION);
include($base_url."/app/config.inc");
$angular_controller="IndexCtrl"; 
$title="Home";
$url_prefix='';
include($base_url."/app/header.inc");
print('<link href="'.$url_prefix.'/lib/fontawesome/css/font-awesome4.css" rel="stylesheet">');
//print('<script src="'.$url_prefix.'/js/indexctrl.js"></script>'); 
?>

			
			
			<? 

			$is_new=ini_get('/config/setup.ini','setup','newsetup',0);
			if ($is_new && !$is_kiosk) { 
    include("/app/newsetup.inc");
     } 
     if (!$is_kiosk) {
     ?>
<!-- customised widgets -->			
			<div class="card-deck">
			<? 
			$w=0;
    for ($cnt=0;$cnt<sizeof($_GLOBALS['hooks']['home']);$cnt++) {
        if ($_GLOBALS['hooks']['home'][$cnt]['pos']==0) {
            $width=intval($_GLOBALS['hooks']['home'][$cnt]['width']);
            
            if (($w+$width)>=12) {
                print("</div><br/><div class='card-deck'>");
                $w=0;
            }
            $w+=$width;
            
            
        ?>
                        <div class="card col-sm-<? print($width); ?> <? print($_GLOBALS['hooks']['home'][$cnt]['style']); ?>"  data-original-title>
    					    <div class="card-body">
    					        <? if ($_GLOBALS['hooks']['home'][$cnt]['title']) { ?><h5 class="card-title"><? print($_GLOBALS['hooks']['home'][$cnt]['title']); ?></h5><? } ?>
    						    <p class='card-text'><?  include($_GLOBALS['hooks']['home'][$cnt]['fn']); ?></p>
    					    </div>
    					</div>
    				
            <?
        }
    }	
     } // is_kiosk
			/**
    * mainbody widgets
    **/    
    $widgets = ini_get_array("/config/widget.ini",(!$is_kiosk?"loggedin.main":"kiosk"));
    if ($is_kiosk && !$widgets['num_widgets']) {
        $widgets['num_widgets']=1;
        $widgets['w0_width']=12;
        $widgets['w0_template']="/package/EZDisplay.inc";
        $widgets['w0_title']="Live Energy Overview";
        $widgets['w0_icon']="icon-play";
    }
    for ($cnt=0;$cnt<$widgets['num_widgets'];$cnt++) {
        if (file_exists($widgets['w'+$cnt+"_template"])) {
            $width=$widgets['w'+$cnt+"_width"];
            $t=$widgets['w'+$cnt+"_title"];
            if ($width==0) $width=4;
            
            
            $type=intval($widgets['w'.$cnt.'_show']);
            if ($type!=1)  { // 1 is hidden
            
            if (($w+$width)>12) {
                print("</div><br/><div class='card-deck'>");
                $w=0;
            }
            $w=$w+$width;
            //<div class="col-sm-<? print($width); 

//            if ($type==2) print (" hidden-phone");
  //          if ($type==3) print (" hidden-phone hidden-tablet");
    //        if ($type==4) print (" hidden-desktop");
            
             //if ($widgets['w'+$cnt+"_icon"]!='none') 
             $cw="col-sm-".$width;
             if (($w+$widgets['w'+($cnt+1)+"_width"])>12) {
                 $cw='';
             }
                { ?>
    					<div class=' card'  data-original-title>
    					    <div class="card-body">
    						    <h5 class="card-title"><? print($t); ?></h5><!--<i class="<? $st=$widgets['w'+$cnt+"_icon"]; if ($st) print($st); else print('icon-user'); ?>"></i>-->
    						    <p class='card-text'><?  include($widgets['w'+$cnt+"_template"]); ?></p>
    					    </div>
    					</div>
    					<?
            //      print('</div>');
                //  print('</div>');
               } /*else {
                  include($widgets['w'+$cnt+"_template"]);
                  print('</div>');

               }*/
            }
        }
    }
    
    for ($cnt=0;$cnt<sizeof($_GLOBALS['hooks']['home']);$cnt++) {
        if ($_GLOBALS['hooks']['home'][$cnt]['pos']==1) {
            $width=$_GLOBALS['hooks']['home'][$cnt]['width'];
            
            if (($w+$width)>12) {
                print("</div><br/><div class='card-deck'>");
                $w=0;
            }
            $w+=$width;
            
            
        ?>
            			<div class="col-sm-<? print($width); ?> card <? print($_GLOBALS['hooks']['home'][$cnt]['style']); ?>" data-original-title>
    					    <div class="card-body">
    					        <? if ($_GLOBALS['hooks']['home'][$cnt]['title']) { ?><h5 class="card-title"><? print($_GLOBALS['hooks']['home'][$cnt]['title']); ?></h5><? } ?>
    						    <p class='card-text'><?  include($_GLOBALS['hooks']['home'][$cnt]['fn']); ?></p>
    					    </div>
    					</div>
            <?
        }
    }
?>          </div>
		
			
			
				  

		  
       
					<!-- content ends -->
			</div><!--/#content.span10-->
				</div><!--/fluid-row-->
				
		<hr>

		<div class="modal hide fade" id="myModal">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal">x</button>
				<h3>Settings</h3>
			</div>
			<div class="modal-body">
				<p>Here settings can be configured...</p>
			</div>
			<div class="modal-footer">
				<a href="#" class="btn" data-dismiss="modal">Close</a>
				<a href="#" class="btn btn-primary">Save changes</a>
			</div>
		</div>

		
	</div><!--/.fluid-container-->
<? include("/app/footer.inc"); ?>
<script>
var gItems,gHttp;
var count=0;
var app = angular.module('myApp', []);
var in_poll=0;
var global_data;
var global_counter=0;

var global_popover_visible=0;
var global_popover_func='';


app.filter('object2Array', function() {
    return function(input) {
      var out = [];
      for(i in input){
        out.push(input[i]);
      }
      return out;
    }
  });
app.factory('dataService', function($http, $q,$timeout) {
  
  this.async = function(clr) {
    
    in_poll=1;
    config = new Object();
    config.timeout=14000;
    config.method="GET";
    config.url='/app/ajaxdata.cgi';
    // if we need to celar the message on the server side
    if (clr) {
        config.url+='?clrmsg=1';
        clr=0;
    }
    //$http(timeout:8000});
    return $http(config)
    .then(function (response) {
      var data = response.data;
      if (!data.voltage) {
     // alert("Error, retrying");
      //  document.location="/index.cgi";
      //  $timeout(this.async, 1000);
      }
//      data=new Object();
      
      in_poll=0;
      global_data=data;
      global_counter=0;
      return data;
    }, function(reason) {
        in_poll=0;
        //alert(reason);
        if (!global_data) {
            data=new Object();
            data.voltage=0;
            global_data=data;
        }
        return global_data;
     //   document.location="/index.cgi";
        //$timeout(this.async, 1000);  // try again
    });
    
  };
  
  return this;
});



function IndexCtrl(dataService,$scope, $timeout,$http) {
  var self = this;
  var pc=100;
  var clrmsg=0;
  var displayedMessage=0;
  $('#sysmsgbtn').popover({placement:"bottom",html:true,title:function() { return $('#popover-title').html(); },content:function() { return $('#popover-content').html(); },delay:{show:500,hide:500}});
  function poll(){
      $scope.asyncData = dataService.async($scope.clrmsg);
      if ($scope.clrmsg) {
        $scope.clrmsg=0;
        $scope.sysmsg='';
      }
     
    };
  $scope.connection_counter=function(){
      
      
      global_counter++;
      
      if (global_counter>5) {
        $scope.connection_error="<? print(lang('E_CONNERROR')) ?> "+global_counter+" <? print(lang('E_S_AGO')) ?>";
        if (!global_popover_visible) {
            global_popover_visible=1;
            $('#popover-title').html("Connection Error");
            $('#popover-content').html("The contents of this page are not currently showing live data.  Please wait for the connection to be re-established for accurate data.");
            $('#sysmsgbtn').popover('show');
        }
         

      }
      $timeout($scope.connection_counter, 1000);
    };    
  $scope.$watch('asyncData', function(asyncData) {
    if(angular.isDefined(asyncData)) {
        if (asyncData.uptime!=0) {
             if (asyncData.uptime<0) {
                asyncData.uptime=0xFFFF-asyncData.uptime;
            }
            $scope.connection_error='';
            if (global_popover_visible) {
                $('#sysmsgbtn').popover('hide');
                $('#popover-content').html("");
                $('#popover-title').html("");
                global_popover_visible=0;
            }
            $scope.items = asyncData.details;
            $scope.livedata=asyncData;
            $scope.sysmsg=asyncData.sysmsg;
            $scope.voltage=asyncData.voltage;
            $scope.count=++count;
            $scope.yourName=$scope.count;
            $scope.freemem=asyncData.freemem;
            <? if ($notify) { ?>
            if (($scope.sysmsg!=$scope.displayedMessage) && ($scope.sysmsg!=undefined)) {
                
                if (window.Notification && Notification.permission === "granted") {
                  for (var i = 0; i < 10; i++) {
                    var n = new Notification($scope.sysmsg, {tag: 'wattmonNotification'});
                  }
                }
            
                // If the user hasn't told if he wants to be notified or not
                // Note: because of Chrome, we are not sure the permission property
                // is set, therefore it's unsafe to check for the "default" value.
                else if (window.Notification && Notification.permission !== "denied") {
                  Notification.requestPermission(function (status) {
                    if (Notification.permission !== status) {
                      Notification.permission = status;
                    }
            
                    // If the user said okay
                    if (status === "granted") {
                      for (var i = 0; i < 10; i++) {
                        var n = new Notification($scope.sysmsg, {tag: 'wattmonNotification'});
                      }
                    }
            
                    // Otherwise, we can fallback to a regular modal alert
                    else {
                      //alert("Hi!");
                    }
                  });
                }
                $scope.displayedMessage=$scope.sysmsg;
            }
            <? } ?>
            pc=0;
        } else {
            $scope.connection_error="<? print(lang('E_COMMERROR')) ?>";
        }
     //   equal_cols('.box');
        $timeout(poll, $scope.global_refresh_time);
    }
  });
  $timeout(poll, 100);
  $timeout($scope.connection_counter, 1000);
};

<? if ($notify) { ?>
window.addEventListener('load', function () {
  // At first, let's check if we have permission for notification
  // If not, let's ask for it
  if (window.Notification && Notification.permission !== "granted") {
    Notification.requestPermission(function (status) {
      if (Notification.permission !== status) {
        Notification.permission = status;
      }
    });
  }
});
<? } ?>

</script>



