<?php
    //header("Content-Type:application/json");
    include("../connection.php");
    $errMsg = "";
    if (!isset($_REQUEST["clave"])  || empty($_REQUEST["clave"]) )  { $errMsg .= "No se recibio el Parametro clave. "; }
    if (!isset($_REQUEST["hash"])   || empty($_REQUEST["hash"]) )   { $errMsg .= "No se recibio el Parametro hash. "; } 
    
    $salida = new stdClass();

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

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

    mysqli_query($db, "SET lc_time_names = 'es_ES'");
 
    $sql =  "SELECT id as userid  " .
            "FROM   users " .
            "WHERE  pin = ? ".
            "AND    IF(CURDATE() < validthru, 1, 0) ";
    
    //Preparamos el statement
    $stmt =  $db->prepare($sql);
    //Remplazamos los parametros en la consulta almacenada
    $stmt->bind_param("s", $hash);        
    
    if (!($stmt->execute())){
        http_response_code(500);
        $salida->rsp = false;
        $salida->msg = mysqli_error($db);
        echo (json_encode($salida));
        return;
    }
    //Obtenemos los resultados y recorremos
    $result = $stmt->get_result();
    $rs = mysqli_fetch_array($result);
    if (empty($rs)){
        http_response_code(401);
        $salida->rsp = true;
        $salida->msg = "Su tiempo vencio";
        //$salida->sql = $sql;
        echo (json_encode($salida));
        return;
    }

    $userid = $rs["userid"];

    $sql =  "UPDATE users SET   sessionid = '', " .
                            " pwd = ?, " .
                            " pin = '', " .
                            " failscount = 0, " .
                            " blocked    = 0, " .
                            " sessionvalidthru = NULL " . 
            "WHERE  id=" . $userid;
            
    //Preparamos el statement
    $stmt =  $db->prepare($sql);
    //Remplazamos los parametros en la consulta almacenada
    $stmt->bind_param("s", $clave);        
    
    if (!($stmt->execute())){
        http_response_code(500);
        $salida->msg = mysqli_error($db);
        echo (json_encode($salida));
        return;
    }
    
    http_response_code(200);
    $salida->rsp    = true;
    $salida->msg    = "Actualizacion de datos realizado";
    $salida->userid = $userid;
    echo (json_encode($salida));
 ?>
 