<?php

namespace Velis\Bpm;

use Velis\Model\DataObject;
use Velis\Model\Cacheable;
use Velis\Bpm\Country\Units;
use Velis\ParameterBag;

/**
 * Coutry model
 * @author Bartosz Izdebski <bartosz.izdebski@velis.pl>
 */
class Country extends DataObject implements Cacheable
{
    protected static $_listDefaultOrder = 'name';
    protected static $_filterListParams = true;


    /**
     * Returns related sql table
     * @return string
     */
    protected function _getTableName()
    {
        return 'app.country_tab';
    }


    /**
     * Returns currency name
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }


    /**
     * {@inheritDoc}
     */
    public static function getList($page = 1, $params = null, $order = null, $limit = self::ITEMS_PER_PAGE, $fields = null): array
    {
        $params = new ParameterBag($params);

        if ($params['search']) {
            self::$_listConditions[] = '(name ILIKE :search)';
            self::$_listParams['search'] = '%' . $params['search'] . '%';
        }

        return parent::getList($page, $params, $order, $limit, $fields);
    }


    /**
     * Returns available country dail codes
     * @return array
     */
    public static function listDialCodes()
    {
        return self::$_db->getAll(
            "SELECT * FROM app.country_tab
                WHERE dial_code IS NOT NULL
                ORDER BY sort_order NULLS LAST, name"
        );
    }


    /**
     * Returns country units
     * @return array
     */
    public function listUnits()
    {
        return Units::getByCountry($this->id());
    }
}
