<?php

/**
 * Class represents records from table policy
 * {autogenerated}
 * @see Am_Table
 */
class Agreement extends Am_Record
{
    function setCurrent()
    {
        $this->getTable()->setCurrent($this);
    }

    function insert($reload = true)
    {
        if(!$this->getTable()->getCurrentByType($this->type)){
            $this->is_current =1;
        }
        return parent::insert($reload);
    }

    function delete()
    {
        $this->getDi()->userConsentTable->deleteBy(array('type' => $this->type, 'revision_id' => $this->revision_id));
        parent::delete();
    }
}

class AgreementTable extends Am_Table
{
    protected
        $_key = 'agreement_revision_id';
    protected
        $_table = '?_agreement';
    protected
        $_recordClass = 'Agreement';

    function getCurrentByType($type)
    {
        return $this->findFirstBy(array('is_current' => 1, 'type' => $type));
    }

    function getTypes()
    {
        return $this->_db->selectCol('SELECT DISTINCT `type` FROM ?_agreement');
    }

    function getTypeOptions(){
        return
        array_map(
            array('Am_Html', 'escape'),
            $this->_db->selectCol(
                "SELECT `type` as ARRAY_KEY, CONCAT('(', `type`, ') ', title)
                FROM ?_agreement
                WHERE is_current=1"
                ));

    }

    function setCurrent(Agreement $agreement)
    {
        $this->_db->query(
            "UPDATE ?_agreement SET is_current=0, dattm = dattm WHERE type=?", $agreement->type
        );
        $this->_db->query(
            "UPDATE ?_agreement SET is_current=1, dattm = dattm WHERE agreement_revision_id=?", $agreement->pk()
        );
    }

    function deleteByType($type)
    {
        $this->deleteBy(array('type' => $type));
        $this->getDi()->userConsentTable->deleteBy(array('type' => $type));
    }
}