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

/**
 * This class supports SSL
 *
 * @package    OSB
 * @subpackage SSL
 * @category   Models
 * @author     Deon George
 * @copyright  (c) 2010 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Model_SSL_CA extends ORMOSB {
	protected $_updated_column = FALSE;

	// Relationships
	protected $_belongs_to = array(
	);

	protected $_has_many = array(
		'service'=>array('through'=>'service__ssl'),
	);

	protected $_display_filters = array(
		'sign_cert'=>array(
			array('SSL::subject',array(':value')),
		),
	);

	public function expires($format=FALSE) {
		return SSL::expire($this->sign_cert,$format);
	}

	public function issuer() {
		return SSL::issuer($this->sign_cert);
	}

	public function subject() {
		return SSL::subject($this->sign_cert);
	}

	public function save(Validation $validation = NULL) {
		// If our parent_ssl_ca_id is null, we'll need to work it out
		if (is_null($this->parent_ssl_ca_id)) {
			$i = SSL::issuer($this->sign_cert);

			$po = NULL;
			foreach (ORM::factory('ssl_ca')->find_all() as $sco)
				if ($sco->subject() == $i) {
					$po = $sco;
					break;
				}

			if (is_null($po)) {
				SystemMessage::add(array(
					'title'=>'Certificate NOT Recorded',
					'type'=>'warning',
					'body'=>sprintf('Parent Certificate is not available (%s)',$this->issuer()),
				));

				return FALSE;
			} else
				$this->parent_ssl_ca_id = $po->id;
		}

		// Save the record
		return parent::save($validation);
	}

	public function list_issued() {
		return $this->service->find_all();
	}
}
?>
