<?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 (!ctype_alnum($_REQUEST["user"])){
            $errMsg = "Parametro user invalido. ";
        }
    }
    $salida = new stdClass();

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

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

    //mysql_query("SET lc_time_names = 'es_ES'");
    mysqli_query($db, "SET lc_time_names = 'es_ES'");
    
    //Solo en esta consulta es necesario porque se manipulan parametros recibidos
    $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, status " . 
            "FROM   users " .
            "WHERE  UPPER(user) = ? " .
            "AND    pwd = ? ";
            
    //Preparamos el statement
    $stmt =  $db->prepare($sql);
    //Remplazamos los parametros en la consulta almacenada
    $stmt->bind_param("ss", $userid, $pwd);

    //Validamos la ejecución
    if (!($stmt->execute())){
        //header("HTTP/1.1 500");
        http_response_code(500);
        $salida->rsp = false ;
        //$salida->msg = mysql_error();
        $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:
    	    //header("HTTP/1.1 401");
            http_response_code(401);
            $salida->rsp = true ;
            $salida->msg = faillogin( $userid ); // Se valida el numero de intentos de seguridad, 
            $salida->errno = 0;
            echo (json_encode($salida));
            return;
            break;
        default:
	        //header("HTTP/1.1 500");
	        http_response_code(500);
	        $salida->rsp = false ;
            //$salida->msg = mysql_error();
            $salida->msg = mysqli_error($db);
            echo (json_encode($salida));
            return;
            break;
    	}
    }


    $usr_name           = $rs["name"];
    $srvdate            = $rs["srvdate"];
    $loginvencido       = $rs["loginvencido"];
    $failscount         = $rs["failscount"];
    $blocked            = $rs["blocked"];
    $status             = $rs["status"]*1;
    $home               = $rs["defaulthome"];
    
/*    
    if (!empty($blocked)){
        header("HTTP/1.1 401");
        $salida->rsp = true;
        $salida->msg = "Acceso bloqueado"; // 
        $salida->errno = 1;
        echo (json_encode($salida));
        return;
    }
*/    
    if ($status == 0){
        //header("HTTP/1.1 401");
        http_response_code(401);
        $salida->rsp = true;
        $salida->msg = "Acceso bloqueado"; // 
        $salida->errno = 1;
        echo (json_encode($salida));
        return;
    }
/*    
    if (!empty($loginvencido)){
        header("HTTP/1.1 401");
        $salida->rsp = true;
        $salida->msg = "Su ingreso a caducado"; // 
        $salida->errno = 1;
        echo (json_encode($salida));
        return;
    }
*/    

    if ($rs["id"]<1){
        //header("HTTP/1.1 500");
        http_response_code(500);
        $salida->rsp = false ;
        $salida->msg = "Falla desconocida";
        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"];
    $status             = $rs["status"]*1;

    
    if (!empty($blocked)){
        //header("HTTP/1.1 401");
        http_response_code(401);
        $salida->rsp = true;
        $salida->msg = "Acceso bloqueado"; // 
        $salida->errno = 1;
        echo (json_encode($salida));
        return;
    }
    
    /* Se blanque cualquier otra session con el mismo numero */
    $sql =  "UPDATE users SET    sessionid = '' WHERE  sessionid = '" . $sessid . "' ";
    if (!(mysqli_query($db, $sql))){
    //if (!(mysql_query($sql))){
        //header("HTTP/1.1 500");
        http_response_code(500);
        $salida->rsp = false ;
        //$salida->msg = mysql_error();
        $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 users SET   sessionid = '" . $sessid . "', " .
                        "       failscount = 0, " .
                        "       blocked    = 0, " .
                        "       sessionvalidthru = DATE_ADD(NOW(), INTERVAL 1 DAY) " . 
            "WHERE  id=" . $rs["id"];
    //if (!(mysql_query($sql))){
    if (!(mysqli_query($db, $sql))){
        //header("HTTP/1.1 500");
        http_response_code(500);
        $salida->rsp = false ;
        //$salida->msg = mysql_error();
        $salida->msg = mysqli_error($db);
        echo (json_encode($salida));
        return;
    }
    //header("HTTP/1.1 200");
    http_response_code(200);
        $salida->rsp = true;
        $salida->idpage = $home;
        $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( $userid){
    global $db;
    $sql = "SELECT id, name, validthru, failscount, failsmax, blocked, status " . 
           "FROM   users " .
           "WHERE  UPPER(user) = '" . $userid. "' ";

    /*if (!($qry = mysql_query($sql))){
        $salida = "errNo=1 - " . mysql_error();*/
    if (!($qry = mysqli_query($db, $sql))){
        $salida = "errNo=1 - " . mysqli_error($db);
    }else{
        //$rs = mysql_fetch_array($qry);
        $rs = mysqli_fetch_array($qry);
            
        $id         = $rs["id"]*1;
        $usr_name   = $rs["name"];
        $validthru  = $rs["validthru"];
        if( is_null($rs["failscount"])){ $failscount = 0;}else{ $failscount = $rs["failscount"];};
        $failsmax   = $rs["failsmax"];
        $blocked    = $rs["blocked"];
        $status     = $rs["status"];
        $salida     = "Datos errados";   
        
        if ($id>0){
            if ($failsmax == 0){
                $failsmax = 5; // Fallas por default
            }
            $failscount = $failscount + 1;
            if ( $failscount >= $failsmax || $status == 0){
                $salida = "fue bloqueado";
                $sql =  "UPDATE users SET   blocked = 0, status = 0, " .
                        "                   pwd         = NULL, " .
                        "                   validthru   = NULL, " .
                        "                   failscount  = 0 " .
                        "WHERE id = " . $id ;
    
                //if (!($qry = mysql_query($sql))){
                if (!($qry = mysqli_query($db, $sql))){
                    $salida = "errNo=2 - ".$sql."/". mysqli_error($db); //mysql_error();
                }
            }else{
                $sql =  "UPDATE users SET failscount = " . ($failscount + 1) . " WHERE id = " . $id ;
                //if (!($qry = mysql_query($sql))){
                if (!($qry = mysqli_query($db, $sql))){
                    $salida = "errNo=3 - " . mysqli_error($db);
                }
            }
        }
    }
    return $salida;
}
    



?>

