<?php

require_once "../header.php";

require_login();

$data = array();
$data["error"] = false;

if ( !isset($_REQUEST['id']) ) pushData("Invalid completion request");
$task = new Task(intval($_REQUEST['id']));
if ( $task->getID() == 0 ) pushData("Task not found");
if ( isset($_REQUEST['incomplete']) && ($_REQUEST['incomplete'] == "1") ) {
    $task->setCompleteTime(Task::INCOMPLETE);
} else {
    $task->setCompleteTime(Task::NOW);
}
$saved = $task->save();
if ( $task->isComplete() ) {
    $data["message"] = "Completed \"{$task->getTitle(HTMLSAFE)}\" on {$task->getCompleteTime(SHORTDATE)}";
} else {
    $data["message"] = "Task \"{$task->getTitle(HTMLSAFE)}\" set to incomplete";
}
$data["task"] = $task;

pushData();

exit();

function pushData($errormsg = null) {
    global $data;

    if ( !is_null($errormsg) ) {
        $data["error"] = true;
        $data["message"] = $errormsg;
    }
    header('Content-Type: application/json');
    echo json_encode($data);
    exit();
}
