<?php

// get the HTTP method, path and body of the request
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'), true); 


// Tratamiento del metodo OPTIONS
if ($method == "OPTIONS") {
  header('Access-Control-Allow-Origin: *');
  header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Z-Key');
  //header('Content-Type: application/json');
  header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE');
  header('HTTP/1.1 200 OK');
  die();    
}

array_shift($request);
$key = array_shift($request);





// connect to the mysql database
$link = mysqli_connect('localhost', 'mparra1_dp', 'psosamparra1970', 'mparra1_danyplacards');
mysqli_set_charset($link,'utf8');
 
// quita la palabra api que genera Celerio por default

$myfile = fopen("dump_variables.txt", "a") or die("Unable to open file!");
fwrite($myfile, "Hasta aca llegue");
fwrite($myfile,  "\n");
//
if ($key==='login') 
    { 
        $username = mysqli_real_escape_string($link, $input['j_username']);
        $password = mysqli_real_escape_string($link, $input['j_password']);


fwrite($myfile, $username);
fwrite($myfile,  "\n");
fwrite($myfile, $password);
fwrite($myfile,  "\n");
fwrite($myfile, $input[0]);
fwrite($myfile,  "\n");
//fwrite($myfile, $sql);

        
        echo $input['j_username']; 
        echo $input['j_password'];
        
        $sql = "SELECT nombre FROM usuarios WHERE habilitado=1 and login='$username' and clave='$password'";
        
        fwrite($myfile, $sql);
        fwrite($myfile,  "\n");
        fclose($myfile);
        //echo $sql;
        $result = mysqli_query($link, $sql);
         
        // die if SQL statement failed
        if (!$result) 
        {
            http_response_code(404);
            echo false;
            die(mysqli_error($link));
        }
        else
        {
            if (mysqli_num_rows($result)>0) {
                http_response_code(200);
                echo true;
                die();
            }
            else
            {
                // No esta logueado
                http_response_code(401);
                echo 'false';
                die();
            }
                
        }
        mysqli_close($link);
    }
    
 

    if ($key==='authenticated') 
        {
            echo 'false';
        }
        else 
        {
            http_response_code(200);
        }


?>