<?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/presence.php';
include_once '../authenticator.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();

$auth = new Authenticator($db);
$userId = $auth->authenticate();

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

$p = new Presence($db);
$p->userId = $userId;
$p->willBePresent = $data->willBePresent;
$p->notes = $data->notes;

if($p->create()){
    // set response code - 201 created
    http_response_code(201);
    echo json_encode($p);
} else {
    // unable to create
    http_response_code(500);
    echo json_encode(array("error" => "Unable to create Presence."));
}

?>