<?php

class Event
{
    private $id;
    protected $paymentDate;
    protected $context;
    protected $beneficiary;
    protected $label;
    protected $amount;

    public function Event($data)
    {
        $this->id = $data["id"];
        $this->paymentDate = DateTime::createFromFormat("Y-m-d H:i:s", $data["payment_date"]);
        $this->context = array();
        $contexts = array_unique(array_filter(explode(',', substr($data["context"], 1, -1)), "strlen"));
        Context::Load($contexts);
        foreach ($contexts as $i)
            array_push($this->context, Context::Get($i));
        $this->beneficiary = Beneficiary::Get($data["beneficiary"]);
        $this->label = $data["label"];
        $this->amount = $data["amount"];
    }

    public function getId() { return md5(SALT .$this->id); }
    public function getDbId() { return $this->id; }
    public function getPaymentDate() { return $this->paymentDate; }
    public function getContext() { return $this->context; }
    public function getBeneficiary() { return $this->beneficiary; }
    public function getLabel() { return $this->label; }
    public function getAmount() { return $this->amount; }

    public function toArray()
    {
        $result = array(
            "id"            => $this->getId(),
            "date"          => $this->paymentDate->format("Y-m-d"),
            "context"       => array(),
            "beneficiary"   => $this->beneficiary->getLabel(),
            "label"         => $this->label,
            "amount"        => $this->amount
        );
        foreach ($this->context as $i)
            array_push($result["context"], $i->getLabel());
        return $result;
    }

    public function save()
    {
        global $account;

        $contexts = Context::Serialize($this->context);
        if ($this->id == null)
            $this->id = insertQuery("insert into events (userid, label, payment_date, context, beneficiary, amount) VALUES (?, ?, ?, ?, ?, ?)", array(
                $account->getId(),
                $this->label,
                $this->paymentDate->format("Y-m-d H:i:s"),
                $contexts,
                $this->beneficiary->getId(),
                $this->amount
            ));
        else
            rawQuery("update events set label=?, payment_date=?, context=?, beneficiary=?, amount=? WHERE id=?", array(
                $this->label,
                $this->paymentDate->format("Y-m-d H:i:s"),
                $contexts,
                $this->beneficiary->getId(),
                $this->amount,
                $this->id
            ));
    }

    public function delete() {
        global $account;
        rawQuery("delete from events where userid=? and id=?", array($account->getId(), $this->id));
    }

    public static function LoadForPeriod($period)
    {
        global $account;

        $data = $period->isEnded() ?
            rawQuery("select * from events where userid=? and payment_date >=? and payment_date <= ?", array($account->getId(), $period->getStart(), $period->getEnd())):
            rawQuery("select * from events where userid=? and payment_date >=?", array($account->getId(), $period->getStart()));
        $result = array();
        $contextToLoad = array();
        $beneficiariesToLoad = array();
        foreach ($data as $i)
        {
            foreach (explode(',', substr($i["context"], 1, -1)) as $ctx)
                if (!in_array($ctx, $contextToLoad))
                    array_push($contextToLoad, $ctx);
            if (!in_array($i["beneficiary"], $beneficiariesToLoad))
                array_push($beneficiariesToLoad, $i["beneficiary"]);
        }
        Beneficiary::Load($beneficiariesToLoad);
        Context::Load($contextToLoad);
        foreach ($data as $i)
            array_push($result, new Event($i));
        return $result;
    }

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

        $data = rawQuery("select * from events where userid=? and md5(concat(?, id)) =? LIMIT 1", array($account->getId(), SALT, $hash));
        $result = array();
        $contextToLoad = array();
        $beneficiariesToLoad = array();
        foreach ($data as $i)
        {
            foreach (explode(',', substr($i["context"], 1, -1)) as $ctx)
                if (!in_array($ctx, $contextToLoad))
                    array_push($contextToLoad, $ctx);
            if (!in_array($i["beneficiary"], $beneficiariesToLoad))
                array_push($beneficiariesToLoad, $i["beneficiary"]);
        }
        Beneficiary::Load($beneficiariesToLoad);
        Context::Load($contextToLoad);
        foreach ($data as $i)
            return new Event($i);
        return null;
    }
}

