<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

include_once '../../config/database.php';
include_once '../objects/token.php';
include_once '../objects/user.php';

if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    http_response_code(400);
    echo json_encode(array("error" => "Method not accepted."));
    exit();
}

$database = new Database();
$db = $database->getConnection();

$token = new Token($db);

// get posted data
$data = json_decode(file_get_contents("php://input"));

if(!empty($data->code)){
        // Check user existence
        $query = "SELECT * FROM user WHERE UPPER(code) = UPPER(:code) LIMIT 1";
        $stmt = $db->prepare($query);
        $stmt->bindParam(":code", $data->code);
        if($stmt->execute()){
            if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                // User found
                $token->userId = $row['id'];
                $token->user = User::createFromRow($row);
                if($token->create()){
                    // set response code - 201 created
                    http_response_code(201);
                    echo json_encode($token);
                } else {
                    // unable to create
                    http_response_code(500);
                    echo json_encode(array("error" => "Unable to create Token."));
                }
            } else {
                // User not found

                // Wait 5 secs to slow down bruteforce attacks
                sleep(5);

                http_response_code(404);
                echo json_encode(array("error" => "Unable to create Token. User not found."));
            }
        }

} else {
    // Missing parameters
    http_response_code(400);
    echo json_encode(array("error" => "Unable to create Token. code is mandatory."));
}
?>
