<?php

/**
 * Class represents records from table policy
 * {autogenerated}
 * @property int $agreement_revision_id PK
 * @property string $type
 * @property string $title
 * @property string|null $url
 * @property string|null $body
 * @property string|null $comment
 * @property timestamp $dattm
 * @property int $is_current
 * @property string|null $meta_title
 * @property string|null $meta_keywords
 * @property string|null $meta_description
 * @property mixed|null $meta_robots
 * @property string|null $rules
 * {/autogenerated}
 */
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(['type' => $this->type, 'revision_id' => $this->revision_id]);
        parent::delete();
    }
}

/** @extends Am_Table<Agreement> */
class AgreementTable extends Am_Table
{
    protected $_key = 'agreement_revision_id';
    protected $_table = '?_agreement';
    protected $_recordClass = 'Agreement';

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

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

    function getTypeOptions()
    {
        return array_map(
            ['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(['type' => $type]);
        $this->getDi()->userConsentTable->deleteBy(['type' => $type]);
    }
}