<?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'] != 'DELETE') {
    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();

if(array_key_exists("id", $_GET) && $_GET["id"]) {
	$db->beginTransaction();
	// Get like before deleting
	$existentLike = Like::byUserAndId($db, $userId, $_GET["id"]);
	if(!$existentLike) {
		http_response_code(404);
		return;
	}
	
	$success = Like::delete($db, $_GET["id"]);
	$db->commit();
    if($success){
        // set response code - 200 ok
		echo json_encode($existentLike);
        http_response_code(200);
    } else {
        // unable to create
        http_response_code(500);
        echo json_encode(array("error" => "Unable to delete Like."));
    }
} else {
    // Missing parameters
    http_response_code(400);
    echo json_encode(array("error" => "Unable to delete Like. Missing id."));
}

?>