<?php

class Task implements JsonSerializable {
    private $id = 0;
    private $title = "";
    private $description = "";
    private $priority = 5;
    private $createtime = null;
    private $duetime = null;
    private $completetime = null;

    const INCOMPLETE = 1000301;
    const COMPLETE   = 1000302;
    const ALLTASKS   = 1000303;
    const OVERDUE    = 1000304;
    const NOW        = 1000305;

    public function getID() {
        return intval($this->id);
    }

    public function getTitle($flag = 0) {
        switch ($flag) {
            case HTMLSAFE:
                return htmlspecialchars($this->title);
                break;
            case HTMLFORMSAFE:
                return htmlspecialchars($this->title, ENT_QUOTES);
                break;
            case CSVSAFE:
                return str_replace('"', '""', $this->title);
                break;
            default:
                return $this->title;
                break;
        }
    }

    public function getDescription($flag = 0) {
        switch ($flag) {
            case HTMLSAFE:
                return htmlspecialchars($this->description);
                break;
            case HTMLFORMSAFE:
                return htmlspecialchars($this->description, ENT_QUOTES);
                break;
            case CSVSAFE:
                return str_replace('"', '""', $this->description);
                break;
            default:
                return $this->description;
                break;
        }
    }

    public function getPriority() {
        return intval($this->priority);
    }

    public function getCompleted($flag = 0) {
        switch ($flag) {
            case AppDB::BOOLEANDB:
                return ($this->completed) ? "true" : "false";
                break;
            default:
                return $this->completed;
                break;
        }
    }

    public function getCreateTime($flag = 0) {
        switch ($flag) {
            case TIMESTAMP:
                return strtotime($this->createtime);
                break;
            case PRETTY:
                return date("F j Y H:i:s", strtotime($this->createtime));
                break;
            case SHORTDATE:
                return date("m/d/Y", strtotime($this->createtime));
                break;
            default:
                return $this->createtime;
                break;
        }
    }

    public function getDueTime($flag = 0) {
        switch ($flag) {
            case TIMESTAMP:
                return strtotime($this->duetime);
                break;
            case PRETTY:
                return date("F j Y H:i:s", strtotime($this->duetime));
                break;
            case SHORTDATE:
                return date("m/d/Y", strtotime($this->duetime));
                break;
            default:
                return $this->duetime;
                break;
        }
    }

    public function getCompleteTime($flag = 0) {
        switch ($flag) {
            case TIMESTAMP:
                return strtotime($this->completetime);
                break;
            case PRETTY:
                return date("F j Y H:i:s", strtotime($this->completetime));
                break;
            case SHORTDATE:
                return ((is_null($this->completetime)) ? null : date("m/d/Y", strtotime($this->completetime)));
                break;
            default:
                return $this->completetime;
                break;
        }
    }

    public function setID($id = null) {
        if (is_null($id)) return false;
        $id = intval($id);
        if ($id <= 0) return false;
        $this->id = $id;
        return true;
    }

    public function setTitle($title = null) {
        if (is_null($title) || ($title == "")) return false;
        settype($title, "string");
        $this->title = $title;
        return true;
    }

    public function setDescription($description = null) {
        if (is_null($description) || ($description == "")) return false;
        settype($description, "string");
        $this->description = $description;
        return true;
    }

    public function setPriority($p = null) {
        if (is_null($p)) return false;
        $p = abs(intval($p));
        if ($p == 0) return false;
        $this->priority = $p;
        return true;
    }

    public function setDueTime($time = null) {
        if ( is_null($time) ) return false;
        $duedate = new DateTime($time);
        if ( $time !== $duedate->format("Y-m-d H:i:s") ) return false;
        $this->duetime = $time;
        return true;
    }

    public function setCompleteTime($time = null) {
        if ( $time === Task::NOW ) {
            $completetime = new DateTime();
            $this->completetime = $completetime->format("Y-m-d H:i:s");
            return true;
        } elseif ( is_null($time) || ($time === Task::INCOMPLETE) ) {
            $this->completetime = null;
            return true;
        } else {
            $completetime = new DateTime($time);
            if ( $time !== $completetime->format("Y-m-d H:i:s") ) return false;
            $this->completetime = $time;
            return true;
        }
    }

    public function setIncomplete() {
        $this->completetime = null;
        return true;
    }

    public function isComplete($flag = 0) {
        if ( is_null($this->completetime) ) {
            return false;
        } else {
            return true;
        }
    }

    public function isOverdue() {
        $duedate = new DateTime($this->getDueTime());
        $now = new DateTime();
        if ( $now >= $duedate ) {
            return true;
        } else {
            return false;
        }
    }

    public function getDaysLeft() {
        if ( $this->isOverdue() ) {
            return 0;
        } else {
            $now = new DateTime();
            return intval($now->diff(new DateTime($this->getDueTime()))->format('%a')) + 1;
        }
    }

    public function jsonSerialize():array {
        return [
            'id' => $this->getID(),
            'title' => $this->getTitle(),
            'title_safe' => $this->getTitle(HTMLSAFE),
            'description' => $this->getDescription(),
            'description_safe' => $this->getDescription(HTMLSAFE),
            'priority' => $this->getPriority(),
            'completed' => $this->isComplete(),
            'overdue' => $this->isOverdue(),
            'daysleft' => $this->getDaysLeft(),
            'createtime' => $this->getCreateTime(),
            'createdate' => $this->getCreateTime(SHORTDATE),
            'duetime' => $this->getDueTime(),
            'duedate' => $this->getDueTime(SHORTDATE),
            'completetime' => $this->getCompleteTime(),
            'completedate' => $this->getCompleteTime(SHORTDATE)
        ];
    }

    public static function getStats() {
        $time = new DateTime();
        $index = 5;
        $curweeks = array("", "", "", "", "", "");
        while ( $index >= 0 ) {
            $curweeks[$index] = $time->format("YW");
            $time->modify("-7 day");
            $index--;
        }
        $data["weeks"] = $curweeks;
        $data["createdtasks"] = array(0, 0, 0, 0, 0, 0);
        $data["completedtasks"] = array(0, 0, 0, 0, 0, 0);
        $query = "SELECT COUNT(id) AS count, YEARWEEK(completetime) AS w, ";
        $query .= "YEARWEEK(NOW()) AS cur FROM " . AppDB::TABLE_TASKS . " ";
        $query .= "WHERE completetime IS NOT NULL and YEARWEEK(completetime) IN (";
        $query .= "YEARWEEK(NOW()), ";
        $query .= "YEARWEEK(DATE_SUB(NOW(), INTERVAL 1 WEEK)), ";
        $query .= "YEARWEEK(DATE_SUB(NOW(), INTERVAL 2 WEEK)), ";
        $query .= "YEARWEEK(DATE_SUB(NOW(), INTERVAL 3 WEEK)), ";
        $query .= "YEARWEEK(DATE_SUB(NOW(), INTERVAL 4 WEEK)), ";
        $query .= "YEARWEEK(DATE_SUB(NOW(), INTERVAL 5 WEEK))";
        $query .= ") GROUP BY w ORDER BY w DESC LIMIT 6";
        $sth = AppDB::getSTH($query);
        if ( $sth === false ) return $data;
        $sth->execute();
        while ( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
            $index = 5;
            while ( $index >= 0 ) {
                if ( $row['w'] == $curweeks[$index] ) $data["completedtasks"][$index] = intval($row["count"]);
                $index--;
            }
        }
        $query = "SELECT COUNT(id) AS count, YEARWEEK(createtime) AS w, ";
        $query .= "YEARWEEK(NOW()) AS cur FROM " . AppDB::TABLE_TASKS . " ";
        $query .= "WHERE createtime IS NOT NULL and YEARWEEK(createtime) IN (";
        $query .= "YEARWEEK(NOW()), ";
        $query .= "YEARWEEK(DATE_SUB(NOW(), INTERVAL 1 WEEK)), ";
        $query .= "YEARWEEK(DATE_SUB(NOW(), INTERVAL 2 WEEK)), ";
        $query .= "YEARWEEK(DATE_SUB(NOW(), INTERVAL 3 WEEK)), ";
        $query .= "YEARWEEK(DATE_SUB(NOW(), INTERVAL 4 WEEK)), ";
        $query .= "YEARWEEK(DATE_SUB(NOW(), INTERVAL 5 WEEK))";
        $query .= ") GROUP BY w ORDER BY w DESC LIMIT 6";
        $sth = AppDB::getSTH($query);
        if ( $sth === false ) return $data;
        $sth->execute();
        while ( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
            $index = 5;
            while ( $index >= 0 ) {
                if ( $row['w'] == $curweeks[$index] ) $data["createdtasks"][$index] = intval($row["count"]);
                $index--;
            }
        }
        return $data;
    }

    public static function findTasks($search = "") {
        $thelist = [];
        if ( strlen($search) < 3 ) return $thelist;
        $query = "SELECT id FROM " . AppDB::TABLE_TASKS . " ";
        $query .= "WHERE LOWER(title) LIKE CONCAT('%',:search1,'%') ";
        $query .= "OR LOWER(description) LIKE CONCAT('%',:search2,'%') ";
        $query .= "ORDER BY title";
        $sth = AppDB::getSTH($query);
        if ( $sth === false ) return $thelist;
        $sth->bindValue(":search1", $search, PDO::PARAM_STR);
        $sth->bindValue(":search2", $search, PDO::PARAM_STR);
        $sth->execute();
        while ( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
            $thelist[] = new Task($row[':id']);
        }
        return $thelist;
    }

    public static function getList($flag = Task::INCOMPLETE) {
        $query = "SELECT id FROM " . AppDB::TABLE_TASKS . " ";
        if ( $flag == Task::INCOMPLETE ) {
            $query .= "WHERE completetime IS NULL ORDER BY priority ASC, duetime ASC";
        } else {
            $query .= "ORDER BY createtime ASC";
        }
        $sth = AppDB::getSTH($query);
        if ( $sth === false ) return $thelist;
        $sth->execute();
        $thelist = [];
        while ( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
            $thelist[] = new Task($row['id']);
        }
        return $thelist;
    }

    public function delete() {
        $query = "DELETE FROM " . AppDB::TABLE_TASKS . " WHERE id=:id";
        try {
            $sth = AppDB::getSTH($query);
            $sth->bindValue(":id", (int) $this->getID(), PDO::PARAM_INT);
            if ( $sth === false ) return false;
            $sth->execute();
        } catch(PDOException $e) {
            return false;
        }
        return true;
    }

    public function save() {
        if ( $this->getTitle() == "" ) return false;
        if ( is_null($this->getDueTime()) ) return false;
        $query = "INSERT INTO " . AppDB::TABLE_TASKS . " ";
        $query .= "(id, title, description, priority, createtime, duetime, completetime) ";
        $query .= "VALUES(:id, :title, :description, :priority, NOW(), :duetime, :completetime) ";
        $query .= "ON DUPLICATE KEY UPDATE ";
        $query .= "title=:title, description=:description, priority=:priority, duetime=:duetime, completetime=:completetime";
        try {
            $sth = AppDB::getSTH($query);
            if ( $sth === false ) return $thelist;
            $sth->bindValue(":id", (int) $this->getID(), PDO::PARAM_INT);
            $sth->bindValue(":title", $this->getTitle(), PDO::PARAM_STR);
            $sth->bindValue(":description", $this->getDescription(), PDO::PARAM_STR);
            $sth->bindValue(":priority", (int) $this->getPriority(), PDO::PARAM_INT);
            $sth->bindValue(":duetime", $this->getDueTime(), PDO::PARAM_STR);
            $sth->bindValue(":completetime", $this->getCompleteTime(), PDO::PARAM_STR);
            $sth->execute();
        } catch(PDOException $e) {
            return false;
        }
        if ( $this->getID() == 0 ) $this->setID(AppDB::getLastInsertId());
        return true;
    }

    function __construct($reqid = 0) {
        $reqid = intval($reqid);
        $query = "SELECT id, title, description, priority, createtime, duetime, completetime ";
        $query .= "FROM " . AppDB::TABLE_TASKS . " WHERE id=:id";
        $sth = AppDB::getSTH($query);
        if ( $sth === false ) return $thelist;
        $sth->bindValue(":id", $reqid, PDO::PARAM_INT);
        $sth->execute();
        if ( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
            $this->setID($row['id']);
            $this->setTitle($row['title']);
            $this->setDescription($row['description']);
            $this->setPriority($row['priority']);
            $this->createtime = $row['createtime'];
            $this->setDueTime($row['duetime']);
            $this->completetime = $row['completetime'];
        }
    }
}

// vim: sw=4 ts=4 ai: