<?php
class tbl_const
{

    public $database;

    public $items;

    /**
     * Required to access the other library functions
     * @param  class  &$database
     */
    public function __construct(&$database)
    {
        $this->database = $database;
        $items = array();
    }

    public function new()
    {
        return new tbl_const_item();
    }

    public function fetch($const)
    {
        $query = "SELECT `tbl_const`.`const`, `tbl_const`.`value`, `tbl_const`.`note`, `tbl_const`.`datecreated`
                    FROM `tbl_const`
                    WHERE `tbl_const`.`const` = '$const';";
        $data = $this->database->query(0, $query);
        $result = !empty($data) ? $this->format($data[0]) : new tbl_const_item();
        return $result;
    }

    public function all()
    {
        $result = array();
        $query = "SELECT `tbl_const`.`const`, `tbl_const`.`value`, `tbl_const`.`note`, `tbl_const`.`datecreated`
                    FROM `tbl_const`;";
        $data = $this->database->query(0, $query);
        foreach ($data as $item) {
            $result[] = $this->items[] = $this->format($item);
        }
        return $result;
    }

    private function format($data)
    {
        $item = $this->new();
        foreach ($data as $col => $val) {
            eval('$item->' . $col . ' = $val;');
        }
        return $item;
    }

    public function add($item)
    {
        $this->items[] = $item;
    }

    public function save()
    {
        if (!empty($this->items)) {
            foreach ($this->items as $item) {
                $inputs = array(
                    ":const" => $item->const,
                    ":value" => $item->value,
                    ":note" => $item->note
                );
                if ($item->datecreated === null) {
                    $query = "INSERT INTO `tbl_const`
                        (`const`,
                            `value`,
                            `note`,
                            `datecreated`)
                        VALUES
                        (:const,
                            :value,
                            :note,
                            NOW());";
                    $this->database->query(1, $query, $inputs);
                    $item = $this->fetch($item->const);
                } else {
                    $query = "UPDATE `tbl_const`
                        SET `value` = :value,
                            `note` = :note
                        WHERE `const` = :const";
                    $this->database->query(1, $query, $inputs);
                }
            }
        }
    }
}

class tbl_const_item
{
    public $const;
    public $value;
    public $note;
    public $datecreated;
}
