<?php
/**
 * @package    Proxim
 * @author     Davison Pro <davisonpro.coder@gmail.com | https://davisonpro.dev>
 * @copyright  2019 Proxim
 * @version    1.0.0
 * @since      File available since Release 1.0.0
 */

namespace Proxim\Site;

use Db;
use Proxim\Database\DbQuery;
use Proxim\Cache\Cache;
use Proxim\ObjectModel;
use Proxim\Util\ArrayUtils;
use Proxim\Util\DateUtils;
use Proxim\Validate;
use Proxim\Tools;

/**
 * Site
 */
class Site extends ObjectModel
{
	/** @var $id Site ID */
	public $id;
	
	/** @var string name */
	public $name;

	/** @var string email */
	public $email;

	/** @var string domain */
    public $domain;
    
    /** @var int customers */
    public $customers = 0;
    
    /** @var int orders */
    public $orders = 0;
    
    /** @var float payments */
	public $payments = 0;

	/** @var string date_upd */
	public $date_upd;
	
	/** @var string date_add */
	public $date_add;
	
	/**
     * @see ObjectModel::$definition
     */
    public static $definition = array(
        'table' => 'site',
        'primary' => 'site_id',
        'fields' => array(
			'name' => array('type' => self::TYPE_STRING, 'validate' => 'isGenericName'),
			'email' => array('type' => self::TYPE_STRING, 'validate' => 'isEmail'),
            'domain' => array('type' => self::TYPE_STRING, 'validate' => 'isUrl'),
			'customers' => array('type' => self::TYPE_INT, 'validate' => 'isInt'),
            'orders' => array('type' => self::TYPE_INT, 'validate' => 'isInt'),
            'payments' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'),
			'date_upd' => array('type' => self::TYPE_DATE, 'validate' => 'isDateOrNull'),
            'date_add' => array('type' => self::TYPE_DATE, 'validate' => 'isDateOrNull'),
        ),
    );

    /**
     * constructor.
     *
     * @param null $id
     */
    public function __construct($id = null) {
		parent::__construct($id);
	}

    public function add($autodate = true, $null_values = true) {
        if ( !$this->getNextSiteId() ) {
			$this->id = Tools::randomGen(9, 'NUMERIC');
		} else {
			$site_id = Db::getInstance()->getValue('SELECT MAX(`site_id`)+20 FROM `' . PROX_DB_PREFIX . 'site`');
			$this->id = $site_id;
		}

		$this->force_id = true;

		return parent::add($autodate, $null_values);
    }
    
    public function getNextSiteId()
    {
        return Db::getInstance()->getValue('
            SELECT site_id
            FROM ' . PROX_DB_PREFIX . 'site
			WHERE site_id > ' . (int) $this->id . ' 
            ORDER BY site_id ASC');
    }
}