<?php
/**
 * Class represents records from table countries
 * {autogenerated}
 * @property int $country_id PK
 * @property string $country
 * @property string $alpha2
 * @property string $alpha3
 * @property int $numeric
 * @property string|null $title
 * @property int|null $tag
 * @property string|null $phone_code
 * @property string|null $status 'added'|'changed'
 * {/autogenerated}
 */

class Country 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<Country>
 * @method Country|null findFirstByCountry($value)
 * @method Country|null findFirstByPhoneCode($value)
 * @method Country|null findFirstByTitle($value)
 */
class CountryTable extends Am_Table
{
    protected $_key = 'country_id';
    protected $_table = '?_country';
    protected $_recordClass = 'Country';

    function sortByTagAndTitle($a, $b)
    {
        if ($a['tag'] != $b['tag']) return ($a['tag'] > $b['tag'] ? -1 : 1);
        return strcmp($a['title'], $b['title']);
    }

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

    function getOptions($addEmpty = false)
    {
        //if admin show all countries, if user show only active countries
        $where = defined('AM_ADMIN') ? '' : 'WHERE tag>=0';
        $res = $this->_db->select("SELECT country AS ARRAY_KEY,
                CASE WHEN tag<0 THEN CONCAT(title, ' (disabled)') ELSE title END AS title
                , tag
                FROM ?_country $where
                ORDER BY tag DESC, title");

        if (strpos($this->getDi()->app->getDefaultLocale(), 'en')!==0) {
            $tr = $this->getDi()->locale->getTerritoryNames();
            foreach ($res as $k => $v) {
                if (array_key_exists($k, $tr)) {
                    $res[$k]['title'] = $tr[$k];
                }
            }
        }
        uasort($res, [$this, 'sortByTagAndTitle']);
        $res = array_map(function($l) {return $l["title"];}, $res);
        if ($res && $addEmpty) {
            $res = array_merge(['' => ___('[Select country]')], $res);
        }
        return $res;
    }

    function getPhoneCodeOptions()
    {
        $res = $this->_db->selectPage($total, "SELECT country, title, phone_code FROM ?_country WHERE phone_code IS NOT NULL ORDER BY title");
        $options = [];
        $key = fn($code, $country) => $country."+".preg_replace("/[^0-9]/", "", $code);
        $value = fn($title, $code) => $title." ( "."+".$code." ) ";
        foreach ($res as $line) {
            if (strpos($line['phone_code'], ',')!== false) {
                foreach (explode(",",$line['phone_code']) as $pc) {
                    $options[] = ['key'=> $key($pc, $line['country']), 'value' => $value($line['title'], $pc)];
                }
            } else {
                $options[] = ['key' => $key($line['phone_code'], $line['country']), 'value' => $value($line['title'], $line['phone_code'])];
            }
        }
        return $options;
    }
}