<?php
/**
 * Class represents records from table states
 * {autogenerated}
 * @property int $state_id PK
 * @property string $state
 * @property string $country
 * @property string|null $title
 * @property string|null $status 'added'|'changed'
 * @property int|null $tag
 * {/autogenerated}
 */

class State extends Am_Record
{
    const STATUS_ADDED = 'added';
    const STATUS_CHANGED = 'changed';

    function insert($reload = true)
    {
        $this->status = self::STATUS_ADDED;
        parent::insert($reload);
    }

    function update()
    {
        $this->status = get_first($this->status, self::STATUS_CHANGED);
        parent::update();
    }
}

/** @extends Am_Table<State> */
class StateTable extends Am_Table
{
    protected $_key = 'state_id';
    protected $_table = '?_state';
    protected $_recordClass = 'State';

    function getTitleByCode($country, $code)
    {
        return ___($this->_db->selectCell("SELECT title
            FROM ?_state
            WHERE country=? AND state=?", $country, $code));
    }

    function getOptions($country, $add_empty=false)
    {
        $tag = defined('AM_ADMIN') ? '' : 'AND tag>=0';
        $res = $this->_db->selectCol("SELECT state as ARRAY_KEY,
                    CASE WHEN tag<0 THEN CONCAT(title, ' (disabled)') ELSE title END AS title
                    FROM ?_state WHERE country=? $tag
                    ORDER BY tag DESC, title", $country);

        $res = array_map('___', $res);

        if ($res && $add_empty) {
            $res = array_merge(['' => ___('[Select state]')], $res);
        }
        return $res;
    }
}