<?php
    //http://stackoverflow.com/questions/18382740/cors-not-working-php
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }

    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

        exit(0);
    }

    //http://stackoverflow.com/questions/15485354/angular-http-post-to-php-and-undefined
    $postdata = file_get_contents("php://input");
    if (isset($postdata)) {
        $request = json_decode($postdata, true);
        
    }
    else {
        exit(0);
    }


//    header('Access-Control-Allow-Origin: *');
//    header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Z-Key');
//    header('Access-Control-Allow-Methods: POST, GET, OPTIONS');

    require('config.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('HTTP/1.1 200 OK');
//        die();    
//    }

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

    // Conectar la BD
    $link = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die('Error de conexion con base de datos: ' . mysqli_connect_errno());
    mysqli_set_charset($link,'utf8');

    $username = mysqli_real_escape_string($link, $request['user']);
    $password = mysqli_real_escape_string($link, $request['clave']);

    $sql = "SELECT login, clave, perfil_id, habilitado, nombre, sector_id FROM usuarios WHERE habilitado=1 and login='$username' and clave='$password'";
    $result = mysqli_query($link, $sql);
     
    // die if SQL statement failed
    if (!$result) 
    {
        http_response_code(404);
        echo '';
        die(mysqli_error($link));
    }
    else
    {
        if (mysqli_num_rows($result)>0) {
            http_response_code(200);
            echo json_encode(mysqli_fetch_object($result), JSON_NUMERIC_CHECK);
            die();
        }
        else
        {
            // No esta logueado
            http_response_code(401);
            echo '';
            die();
        }
            
    }
    mysqli_close($link);
    
 

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


?>