<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * This class supports Services
 *
 * @package    Domain
 * @category   Models
 * @author     Deon George
 * @copyright  (c) 2009-2013 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Model_Service_Plugin_Domain extends Model_Service_Plugin {
	protected $_table_name = 'service__domain';
	protected $_created_column = FALSE;
	protected $_updated_column = FALSE;

	// Relationships
	protected $_has_one = array(
		'host'=>array('model'=>'Service_Plugin_Host','through'=>'service','far_key'=>'service_id','foreign_key'=>'service_id'),
		'registrar'=>array('model'=>'Domain_Registrar','foreign_key'=>'id','far_key'=>'domain_registrar_id'),
		'tld'=>array('model'=>'Domain_TLD','foreign_key'=>'id','far_key'=>'domain_tld_id'),
	);

	protected $_display_filters = array(
		'domain_expire'=>array(
			array('Config::date',array(':value')),
		),
		'domain_name'=>array(
			array('strtoupper',array(':value')),
		),
		'registrar_lastsync'=>array(
			array('Config::date',array(':value')),
		),
	);

	protected $_save_message = TRUE;

	// Required abstract functions

	public function expire() {
		return $this->domain_expire;
	}

	public function name() {
		return sprintf('%s.%s',$this->display('domain_name'),$this->tld->display('name'));
	}

	public function password() {
		return $this->registrar_password;
	}

	public function username() {
		return $this->registrar_username;
	}

	// Local functions

	/**
	 * This provides us with a manage button to jump to the registrar
	 * to manage the domain.
	 */
	public function manage_button($t='') {
		if (! parent::manage())
			return NULL;

		return ($this->username() AND $this->password()) ? $this->registrar->manage_button($this,$t) : _('Please contact us');
	}

	public function manage_button_dns() {
		return $this->host->manage_button('host');
	}

	/**
	 * Search for services matching a term
	 * @todo This search doesnt pick up the TLD of domain names
	 */
	public function list_autocomplete($term,$index,$value,array $label,array $limit=array(),array $options=NULL) {
		// We only show domain names.
		if (is_numeric($term))
			return array();

		$ao = Auth::instance()->get_user();

		$options['key'] = 'id';
		$options['object'] = DB::select($this->_table_name.'.id',$this->_table_name.'.domain_name')
			->from($this->_table_name)
			->join('service')
			->on('service.id','=',$this->_table_name.'.service_id')
			->where('service.account_id','IN',$ao->RTM->customers($ao->RTM))
			->and_where($this->_table_name.'.domain_name','like','%'.$term.'%');

		return parent::list_autocomplete($term,$index,$value,$label,$limit,$options);
	}
}
?>
