<?php

require_once "../header.php";

require_login();

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

$id = 0;
if ( isset($_REQUEST["id"]) ) $id = intval($_REQUEST["id"]);
if ( $id < 0 ) {
    pushData("Invalid task ID: {$id}");
}

$title = "";
if ( isset($_REQUEST["title"]) ) $title = $_REQUEST["title"];
if ( strlen($title) == 0 ) pushData("Task titles cannot be blank");

$description = "";
if ( isset($_REQUEST["description"]) ) $description = $_REQUEST["description"];

if ( !isset($_REQUEST["priority"]) ) pushData("Task must have a priority");
$priority = intval($_REQUEST["priority"]);
if ( ($priority < 1) || ($priority > 10) ) pushData("Task priority must be between 1 and 10");

$duedate = "";
if ( isset($_REQUEST["duedate"]) ) $duedate = $_REQUEST["duedate"];
if ( strlen($duedate) == 0 ) pushData("Task due date must be provided");
$parts = explode("/", $duedate);
if ( count($parts) != 3 ) pushData("Task due date must be in the format MM/DD/YYYY");
$m = $parts[0];
$d = $parts[1];
$y = $parts[2];
$dim = intval(date('t', mktime(0, 0, 0, intval($m), 1, intval($y))));
if ( (intval($m) < 1) || (intval($m) > 12) || (intval($d) < 1) || (intval($d) > $dim) ) {
    pushData("Improperly formatted or invalid due date: {$duedate}");
}
$duetime = "{$y}-{$m}-{$d} 00:00:00";

$task = new Task($id);
$task->setTitle($title);
$task->setDescription($description);
$task->setPriority($priority);
$task->setDueTime($duetime);
$saved = $task->save();
if ( !$saved ) pushData("Server Error: Task could not be saved to the database");
if ( $id == 0 ) {
    $data["message"] = "Task created successfully";
} else {
    $data["message"] = "Task edited successfully";
}
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();
}
