<?php
// cms/api/login/login
    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");

    // parametros obligatorios
    $parmsob = array("usr","pwd");
    if (!parametrosValidos($_REQUEST, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    }
    
    $out= new stdClass;
    $usr = $_REQUEST["usr"];
    $pwd = $_REQUEST["pwd"];
    
    $sessid = randomString(32);
    
    // Validamos que el usuario exista
    $sql = "SELECT COUNT(id) AS qty ".
    "       FROM cmsusers ".
    "       WHERE MD5(LOWER(usr))='".mysqli_real_escape_string($db, $usr)."' ";
    //die($sql);
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $res->fetch_assoc();
    
    if($row['qty'] == 0){
        badEnd("500", array("msg"=>'Usuario no existe'));
    }
    
    // destruir cualquier session anterior existente
    $sql =  "UPDATE cmsusers " .
            "SET    sessionid = '" . $sessid . "', ".
            "       validthru = DATE_ADD(NOW(), INTERVAL 1 HOUR),".
            "       lastsession =  NOW(),".
            "       fails = 0 ".
            "WHERE  MD5(LOWER(usr))='".mysqli_real_escape_string($db, $usr)."' ".
            "AND    pwd='".mysqli_real_escape_string($db, $pwd)."' " .
            "AND    status<>0";
    if (!$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    if ($db->affected_rows == 0){
        // se incrementa los reintentos y se desactiva la cuenta en caso de llegar al maxfails
        $sql =  "UPDATE cmsusers " .
                "       SET fails = " .
                "             CASE WHEN fails < maxfails THEN " .
                "               fails + 1 " .
                "             ELSE " .
                "               fails " .
                "             END, " .
                "           status = " .
                "             CASE WHEN fails >= maxfails THEN " .
                "               0 " .
                "             ELSE " .
                "               status " .
                "             END " .
                "WHERE  MD5(LOWER(usr))='".mysqli_real_escape_string($db, $usr)."' " .
                "AND    fails < maxfails";
        if (!$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $sql = "SELECT status FROM cmsusers WHERE MD5(LOWER(usr))='".mysqli_real_escape_string($db, $usr)."' ";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $row = $rs->fetch_assoc();
        
        if($row["status"] == "0")
            badEnd("402",array("msg"=>"Usuario bloqueado"));
            
            
        badEnd("401", array("msg"=>"Usuario/Clave Inválidos"));
    }
        
    $sql =  "SELECT  id, sessionid,  DATE_FORMAT(validthru, '%Y%m%d%H%i%s') vt, name ".
            "FROM    cmsusers ".
            "WHERE   MD5(LOWER(usr))='".mysqli_real_escape_string($db, $usr)."' ".
            "AND     pwd='".mysqli_real_escape_string($db, $pwd)."'";
    if (!$rs = $db->query($sql)){
        badEnd("500", array("msg"=>determinateDBError($db)));
    }
    
    $row = $rs->fetch_assoc();
    
    $out->id = (int)$row["id"];
    $out->sessionid = $row["sessionid"];
    $out->validthru = $row["vt"];
    $out->name = $row["name"];
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>

