<?php

class Period
{
    private $id;
    protected $label;
    protected $start;
    protected $end;

    protected function Period($data)
    {
        $this->id = $data["id"];
        $this->label = $data["label"];
        $this->start = $data["start"];
        $this->end = $data["end"];
    }

    public function getId() { return md5(SALT .$this->id); }

    public function getLabel()
    {
        return $this->label;
    }

    public function getStart()
    {
        return $this->start;
    }

    public function getEnd()
    {
        return $this->end;
    }

    public function isEnded()
    {
        return $this->end != null;
    }

    public static function LoadPendingPeriods()
    {
        global $account;

        $data = rawQuery("select * from periods where end is null and userid=? order by start desc", array($account->getId()));
        $result = [];
        foreach ($data as $i)
            array_push($result, new Period($i));
        return $result;
    }

    public static function LoadPastPeriods()
    {
        global $account;

        $data = rawQuery("select * from periods where end is not null and userid=? order by end DESC, start DESC", array($account->getId()));
        $result = [];
        foreach ($data as $i)
            array_push($result, new Period($i));
        return $result;
    }

    public static function FromHashed($hash) {
        global $account;

        $data = rawQuery("select * from periods where userid=? and md5(concat(?, id)) =? LIMIT 1", array($account->getId(), SALT, $hash));
        $result = array();
        foreach ($data as $i)
            return new Period($i);
        return null;
    }
}

