<?php
/**
 * @package    Proxim
 * @author     Dominic Tanui <dominic@codeworldweb.com | https://codeworldweb.com>
 * @copyright  2019 Proxim
 * @version    1.5.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 `' . DB_PREFIX . 'site`');
			$this->id = $site_id;
		}

		$this->force_id = true;

		return parent::add($autodate, $null_values);
    }

    public static function getSites() 
    {
        return Db::getInstance()->executeS('
            SELECT s.*
            FROM ' . Db::prefix('site') . ' s
            ORDER BY s.name
        ');
    }
    
    public function getNextSiteId()
    {
        return Db::getInstance()->getValue('
            SELECT site_id
            FROM ' . Db::prefix('site') . '
			WHERE site_id > ' . (int) $this->id . ' 
            ORDER BY site_id ASC'
        );
    }
}