<?php
    header("Content-Type:application/json");
    include("../connection.php");
    
    $errMsg = "";
    if ($_SERVER['REQUEST_METHOD']!= "POST") { $errMsg .= "Debe llamarse al servicio usando un POST"; } 
    if (!isset($_REQUEST["user"]) || empty($_REQUEST["user"]) ) { $errMsg .= "No se recibio el Parametro user. "; } 
    if (!isset($_REQUEST["pwd"])  || $_REQUEST["pwd"] == '')    { $errMsg .= "No se recibio el Parametro pwd. "; } 
  
    if (empty($errMsg)){
        if (!is_numeric($_REQUEST["user"])) {
            $errMsg .= "Parametro user inv¨¢lido. ";
        }
    }
    
    $salida = new stdClass();

    if (!empty($errMsg) ){
        http_response_code(400);
        $salida->msg = $errMsg;
        echo (json_encode($salida));
        return;
    }

    $custid = intval($db->real_escape_string($_REQUEST["user"]));
    $pwd    = preg_replace("/[^a-zA-Z0-9*@#_.]/", "", $db->real_escape_string($_REQUEST["pwd"]));

    mysqli_query($db, "SET lc_time_names = 'es_ES'");
/*
    $sql =  "SELECT id, name, IFNULL(defaulthome,'') as defaulthome, DATE_FORMAT(CURDATE(), '%W, %e de %M de %Y') as srvdate, " .
            "       IF(CURDATE()>validthru, 1, 0) as loginvencido, failscount, blocked " . 
            "FROM   users " .
            "WHERE  UPPER(user) = '" . custid . "' " .
            "AND    pwd = '" . $pwd . "' " ;*/
            
    $sql =  "SELECT id, name, DATE_FORMAT(CURDATE(), '%W, %e de %M de %Y') as srvdate, " .
            "       IF(CURDATE()>validthru, 1, 0) as loginvencido, failscount, blocked " . 
            "FROM   customers " .
            "WHERE  UPPER(custid) = ? " .
            "AND    pwd = ? " ;
            
    //Preparamos el statement
    $stmt =  $db->prepare($sql);
    //Remplazamos los parametros en la consulta almacenada
    $stmt->bind_param("ss", $custid, $pwd);
            
    //Validamos la ejecuciÃ³n
    if (!($stmt->execute())){
        http_response_code(500);
        $salida->rsp = false ;
        $salida->sql = $sql ;
        $salida->msg = mysqli_error($db);
        echo (json_encode($salida));
        return;
    }

    //Obtenemos los resultados y recorremos
    $result = $stmt->get_result();
    if (!($rs = mysqli_fetch_array($result))){
    	switch (mysqli_errno($db)){
        	case 0:
                http_response_code(401);
                $salida->rsp = true ;
                $salida->msg = faillogin( $custid );// Se valida el numero de intentos de seguridad, 
                //$salida->errno = 0;
                echo (json_encode($salida));
                return;
                break;
            default:
    	        http_response_code(500);
    	        $salida->rsp = false ;
                $salida->msg = mysqli_error($db);
                echo (json_encode($salida));
                return;
                break;
    	}
    }
    
    if ($rs["id"]<1){
        http_response_code(500);
        $salida->rsp = false ;
        $salida->msg = "NO SE QUE PASO";
        echo (json_encode($salida));
        return;
    }
            
    session_start();
    $sessid             = session_id();
    $usr_name           = $rs["name"];
    $srvdate            = $rs["srvdate"];
    $loginvencido       = $rs["loginvencido"];
    $failscount         = $rs["failscount"];
    $blocked            = $rs["blocked"];

    
    if (!empty($blocked)){
        http_response_code(401);
        $salida->rsp = true;
        $salida->msg = "tiene bloqueado el acceso"; // 
        $salida->errno = 1;
        echo (json_encode($salida));
        return;
    }

    /* Se blanque cualquier otra session con el mismo numero */
    $sql =  "UPDATE customers SET    sessionid = '' WHERE  sessionid = '" . $sessid . "' ";
    if (!(mysqli_query($db, $sql))){
        http_response_code(500);
        $salida->rsp = false ;
        $salida->msg = mysqli_error($db);
        echo (json_encode($salida));
        return;
    }    
    
    /* Se registra la session del usuario y se limpia el numero de intentos fallidos y usuario bloqueado */
    $sql =  "UPDATE customers SET   sessionid = '" . $sessid . "', " .
                            "       failscount = 0, " .
                            "       blocked    = 0, " .
                            "       sessionvalidthru = DATE_ADD(NOW(), INTERVAL 1 DAY) " . 
            "WHERE  id=" . $rs["id"];
    if (!(mysqli_query($db, $sql))){
        http_response_code(500);
        $salida->rsp = false ;
        $salida->msg = mysqli_error($db);
        echo (json_encode($salida));
        return;
    }
        http_response_code(200);
        $salida->rsp = true;
        $salida->idpage = "";
        $salida->sessid = $sessid;
        $salida->userid = $rs["id"]*1;
        $salida->username = $usr_name;
        $salida->srvdate = $srvdate;
    echo (json_encode($salida));


/*
FUNCTION  faillogin( {$user} )

Creacion de proceso de descuento de intentos: 
Si es null (validthru) no se valida
Al realizar un intento fallido incrementas failscount al ser failscount >= failsmax 
se bloquea el usuario y se devuelve error.  
Si se realiza un intento correcto se lleva a 0 el failscount
*/    
function faillogin( $custid){
    global $db;
    
    $sql = "SELECT id, name, validthru, failscount, failsmax, blocked " . 
           "FROM   customers " .
           "WHERE  UPPER(custid) = '" . $custid . "' ";

    if (!($qry = mysqli_query($db, $sql))){
        $salida = "Usuario y/o clave incorrectos"; 
        //"errNo=1 - " . mysqli_error($db);
    }else{
        $rs = mysqli_fetch_array($qry);
        $validthru = ""; 
        $salida = "Usuario y/o clave incorrectos"; 
        if(!is_null($rs)){ 
            $id         = $rs["id"];
            $usr_name   = $rs["name"];
            $validthru  = $rs["validthru"];
            $failsmax   = $rs["failsmax"];
            $blocked    = $rs["blocked"];
            if( is_null($rs["failscount"])){ $failscount = 0;}else{ $failscount = $rs["failscount"];};
        } 
        
        if (is_null($validthru) || empty($validthru)){
            $salida = "Usuario y/o clave incorrectos"; 
        }else{
            $failscount = $failscount + 1;
            if ( $failscount >= $failsmax || $blocked > 0){
                $salida = "fue bloqueado, registrarse nuevamente";
                $sql =  "UPDATE customers SET   blocked = 0,  " .
                        "                       pwd         = NULL, " .
                        "                       validthru   = NULL, " .
                        "                       failscount  = 0 " .
                "WHERE id = " . $id ;
    
                if (!($qry = mysqli_query($db, $sql))){
                    //$salida = "errNo=2 - " . mysqli_error($db);
                    $salida = "Usuario y/o clave incorrectos"; 
                }
            }else{
                $sql =  "UPDATE customers SET failscount = " . ($failscount + 1) . " WHERE id = " . $id ;
                if (!($qry = mysqli_query($db, $sql))){
                    //$salida = "errNo=3 - " . mysqli_error($db);
                    $salida = "Usuario y/o clave incorrectos"; 
                }
            }
        }
    }
    return $salida;
}
    



?>

