<?php

require dirname(__FILE__).'/../common.php';
require dirname(__FILE__).'/../lib/auth.php';

if ($_SERVER["REQUEST_METHOD"] != "POST") {
    return_generic_error("invalid_method");
    exit(405);
}

$query_builder = $db_conn->createQueryBuilder();

if (!isset($_GET['id'])) {
    return_generic_error("need_id");
}

$json = file_get_contents('php://input');
if (!$json) {
    return_generic_error("need_json");
}

$param = json_decode($json, true);

$id = intval($_GET['id']);
$query = $query_builder->update('publications', 'p')->where('p.id=:id')->setParameter('id', $id);

$data = ['id'=>$id];

$something_set = false;
if (isset($param['owned'])) {
    $owned = boolval($param['owned']);
    $data['owned'] = $owned;
    $query->set("p.owned", $owned ? '1' : '0');
    $something_set = true;
}

if (!$something_set) {
    return_generic_error("nothing_set");
}

$db_conn->beginTransaction();
try {
    $stmt = $query->executeStatement();
    $db_conn->commit();
    return_ok(['result'=>$data]);
} catch (\Exception $e) {
    $db_conn->rollBack();
    return_error($e, ['sql'=>(string)$query]);
}
