<?php

/**
 * Session.class [ HELPER ]
 * Responsável pelas estatísticas, sessões e atualizações de tráfego do sistema!
 * 
 * @copyright (c) 2014, Robson V. Leite UPINSIDE TECNOLOGIA
 */
 
class Session {

    private $Date;
    private $Cache;
    private $Traffic;
    private $Bropder;


function __construct($Cache = null) {
        !session_start();
        $this->CheckSession($Cache);
}
		

       private function CheckSession($Cache = null) {
		//  Set Timestep  ###############
        $timeoutseconds = 2500;
        $timestamp = time();
        $timeout = $timestamp - $timeoutseconds;
        $this->Date = $timeout;
        $this->Cache =  $timeout;

		
		$readSiteViews = new Core_select;
        $readSiteViews->ExeRead(" * ", 'pd_useronline', "WHERE ip = :date", "date={$this->Date}");
        if ($readSiteViews->getRowCount()):
        $this->Traffic = $readSiteViews->getResult()[0];
        endif;
		
		//Verifica e executa todos os métodos da classe!
		
        if (empty($_SESSION['useronline'])):
            //$this->setTraffic();
          $this->setSession();
		  $this->setUserOnline();
          $this->CheckBropder();
           // $this->setUsuario();
            //$this->Bropder_Update();
        else:
		$this->setSession();
           // $this->Traffic_Update();
           // $this->session_Update();
           $this->CheckBropder();
           // $this->Usuario_Update();
		   $this->setUserOnline();
		  
        endif;
	
        $this->Date = null;
		
    }
	
    //Inicia a sessão do usuário
    private function setSession() {
		
        $_SESSION['useronline'] = [
            "online_session" => session_id(),
            "online_ip" => filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP),
            "online_url" => filter_input(INPUT_SERVER, 'REQUEST_URI', FILTER_DEFAULT),
            "online_agent" => filter_input(INPUT_SERVER, "HTTP_USER_AGENT", FILTER_DEFAULT)
        ];
    }	
	
	 //Identifica navegador do usuário!
    private function CheckBropder() {
        $this->Bropder = $_SESSION['useronline']['online_agent'];
        if (strpos($this->Bropder, 'Chrome')):
            $this->Bropder = 'Chrome';
        elseif (strpos($this->Bropder, 'Firefox')):
            $this->Bropder = 'Firefox';
        elseif (strpos($this->Bropder, 'MSIE') || strpos($this->Bropder, 'Trident/')):
            $this->Bropder = 'IE';
        else:
            $this->Bropder = 'Outros';
        endif;
    }
	
	private function setUserOnline(){
	
		$sessao = $_SESSION['useronline']['online_session'];
		$readSiteViews = new Core_select;
        $readSiteViews->ExeRead(" * ", 'pd_useronline', "WHERE sessao = :sessao", "sessao={$sessao}");
        if (!$readSiteViews->getRowCount()):
        $ArrSiteViews  = [ 'sessao' => $sessao, 'ip' => $_SESSION['useronline']['online_ip'], 'timestamp' => $this->Date , 'agent' => $this->Bropder];
        $createSiteViews = new Core_create;
        $createSiteViews->ExeCreate('pd_useronline', $ArrSiteViews);
		$this->checkTimestapBb();
        endif;
		
	}
 

//  Rand Number   ###############
private function rand_number(){
$a = array();
$novo_valor = "";
$valor = "0123456789";
srand((double)microtime()*1000000);
for ($i=0; $i<12; $i++){$novo_valor.= $valor[rand()%strlen($valor)];}
}

private function checkTimestapBb(){
	
	    $Delete_useronline = new Core_delete;
		echo $this->Date;
       // $Delete_useronline->ExeDelete('pd_useronline', '', "WHERE timestamp >= :timestamp", "timestamp={$this->Date}");	
		
}

/*
mysql_query("DELETE FROM pd_useronline WHERE timestamp<$timeout");

////////////////  CHECK UPDATE DB  /////////////////////////////////////////////////////
if(isset($_SESSION[tema.'pd-session'])){
$Sessao_id     = $_SESSION[tema.'pd-session'];
$Online        = mysql_query ("SELECT sessao FROM pd_useronline WHERE sessao='$Sessao_id'");
$Online_total  = mysql_num_rows($Online);
if($Online_total == 0){
$retry =$novo_valor.time();
$_SESSION[tema.'pd-session'] = $retry;	
$Sessao_id = $retry;
mysql_query("INSERT INTO pd_useronline (timestamp,ip,sessao) VALUES ('$timestamp','$ip','$Sessao_id')");
}else{	
mysql_query("UPDATE pd_useronline SET timestamp='$timestamp' WHERE sessao='$Sessao_id'");		
}}else{
$retry =$novo_valor.time();
$_SESSION[tema.'pd-session'] = $retry;
$Sessao_id = $retry;	
mysql_query("INSERT INTO pd_useronline (timestamp,ip,sessao) VALUES ('$timestamp','$ip','$Sessao_id')");	
}

*/

}
