<?php

class Dog extends Model
{
    protected $dbTable = "dogs";
    protected $dbFields = array(
        'registered' => ['type' => 'datetime', 'required', 'unique', 'autoValMethod' => 'getDateTime'],
        'name' =>  ['type' => 'text'],
        'kennel_name' =>   ['type' => 'text'],
        'breed' =>   ['type' => 'text'],
        'size' =>   ['type' => 'text'], //in cm
        'birthday' => ['type' => 'text'],
        'agility_size' =>   ['type' => 'text'], //S,M,I,L
        'photo' =>  ['type' => 'text', 'default' => 'https://pictshare.net/1ch3e5.png'],
        'active' =>   ['type' => 'bool', 'default' => 1]
    );

    function getResults($dogid=false)
    {
        if(!$dogid)
            $dogid = $this->id;
        $res = new Result();
        $keys = $GLOBALS['redis']->keys($res->getTable() . ':*');
        $results = [];
        foreach ($keys as $key) {
            $id = end(explode(':', $key));
            $res = new Result();
            $res->load($id);
            if ($res->data['dog'] == $dogid) {
                $results[] = $res->data;
            }
        }
        return $results;
    }

    function getRuns()
    {
        $run = new Run();
        $keys = $GLOBALS['redis']->keys($run->dbTable . ':*');
        $runs = [];
        foreach ($keys as $key) {
            $id = end(explode(':', $key));
            $run = new Run();
            $run->load($id);
            if ($run->data['dog'] == $this->id)
                $runs[] = $run->data;
        }
        return $runs;
    }

    function isMyDog($dog = false)
    {
        if ($dog == false)
            $dog = $this->id;

        if (!$this->exists($dog))
            return false;
        else if(!is_array($_SESSION['user']->data['dogs']))
            return false;
        else {
            if (in_array($dog, $_SESSION['user']->data['dogs']))
                return true;
            else return false;
        }
    }
}