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

/**
 * This class supports Services
 *
 * @package    OSB
 * @subpackage Hosting
 * @category   Models
 * @author     Deon George
 * @copyright  (c) 2010 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Model_Service_Plugin_Host extends Model_Service_Plugin {
	protected $_table_name = 'service__hosting';
	protected $_created_column = FALSE;
	protected $_updated_column = FALSE;
	protected $_serialize_column = array(
		'server_data_date',
	);

	// Relationships
	protected $_has_one = array(
		'domain_tld'=>array('foreign_key'=>'id','far_key'=>'domain_tld_id'),
		'host_server'=>array('far_key'=>'host_server_id','foreign_key'=>'id'),
	);
	protected $_belongs_to = array(
		'service'=>array(),
	);

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

	public function rules() {
		return array_merge(parent::rules(),array(
			'server_data_date'=>array(
				array('ORMOSB::serialize_array',array(':model',':field',':value')),
			),
		));
	}

	// Required abstract functions
	public function admin_update() {
		return '';
	}

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

	public function service_view() {
		return View::factory('service/user/plugin/host/view')
			->set('so',$this);
	}

	/**
	 * This provides us with a manage button to jump to the hosting server
	 * to manage the domain.
	 */
	public function manage_button() {
		$k = Random::char();
		Session::instance()->set('manage_button',$k);

		Script::add(array('type'=>'stdin','data'=>'
			$(document).ready(function() {
				var x=0;
				$("button[name=submit]").click(function() {
					if (x++) { alert("Please refresh the page"); return false; }
					$.getJSON("'.URL::site('user/service/ajaxmanage/'.$this->service_id).'", { k: "'.$k.'" }, function(data) {
						$.each(data, function(key, val) { $("#"+key).val(val); });
					}).error(function() { alert("There was a problem with the request"); return false; }).success(function() { $("#manage").submit(); });
				});
			});'
		));

		// @todo Convert this to a Static_List display
		if ($this->service->queue == 'PROVISION')
			return _('To Be Provisioned');

		return ($this->host_username AND $this->host_password) ? $this->host_server->manage_button($this->host_username,substr(md5($this->host_password),0,8),$this->name()) : '';
	}
}
?>
