<?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/like.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"));
if(!empty($data->gallery_id)) {
	$existentLike = Like::get($db, $userId, $data->gallery_id);
	if ($existentLike) {
		// Like already exists, return the existent one
		http_response_code(201);
		echo json_encode($existentLike);
		return;
	}

    $like = new Like($db);
    $like->user_id = $userId;
    $like->gallery_id = $data->gallery_id;

	$id = $like->create();
    if($id){
		$like->id = $id;
        // set response code - 201 created
        http_response_code(201);
        echo json_encode($like);
    } else {
        // unable to create
        http_response_code(500);
        echo json_encode(array("error" => "Unable to create Like."));
    }
} else {
    // Missing parameters
    http_response_code(400);
    echo json_encode(array("error" => "Unable to create Like. Missing gallery_id."));
}

?>