<?php
define("TIEMPO_CADUCA", 1000);


function _generate_token($key){
    $token = $key;
    return $token;
}

function evolution_login($user,  $key){
    $sql = new sqldata();
   
    $acc = $sql->get_tabla("_ACCOUNTS", "USERNAME = '".$user."' AND KEY_ACC = '".$key."' AND IP = '".$_SERVER['REMOTE_ADDR']."'");
    
    if ($acc){
        $actual = time();
        $sql->delete("_REMOTE_TRANSACTION", "TIME < ".($actual - TIEMPO_CADUCA) );


        $tok_actual = $sql->get_tabla("_REMOTE_TRANSACTION", "ACCOUNT_ID = '".$acc[0]['ID']."'");


        if ($tok_actual){
            $token = $tok_actual[0]['TOKEN'];
        }
        else{
            $token = _generate_token($key);

            $sql->insert(
                    "_REMOTE_TRANSACTION", array(
                    "ACCOUNT_ID"=>$acc[0]['ID'],
                    "TIME"=>time(),
                    "STATUS"=>1,
                    "TOKEN"=>$token,
            ));
        }


        
        $rtn = array("STATUS"=>1, "TOKEN"=>$token);
    }
    else{
        $rtn = array("STATUS"=>0);
    }

    return json_encode($rtn);
}

function _is_logged($token){
    $actual = time();
    $sql = new sqlData();

    $sql->delete("_REMOTE_TRANSACTION", "TIME < ".($actual - TIEMPO_CADUCA) );

    $reg = $sql->get_tabla("_REMOTE_TRANSACTION", "TOKEN = '".$token."'");

    if ($reg){
 
        if (time() - $reg[0]['TIME'] < TIEMPO_CADUCA ){
            $sql->update("_REMOTE_TRANSACTION",array(
                "TIME"=>time()), "TOKEN = '".$token."'"
            );
            
            return true;
        }
    }
    return false;

}

function _logthis($str){
    file_put_contents("log.lg", $str);
}




?>