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

/**
 * This class provides charge item capabilities.
 *
 * @package    Charge
 * @category   Models
 * @author     Deon George
 * @copyright  (c) 2009-2013 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Model_Charge extends ORM_OSB implements Invoicable {
	protected $_belongs_to = array(
		'account'=>array(),
		'product'=>array(),
		'service'=>array(),
	);
	protected $_has_one = array(
		'invoice_item'=>array('far_key'=>'id'),
	);

	protected $_nullifempty = array(
		'attributes',
	);

	protected $_serialize_column = array(
		'attributes',
	);

	protected $_display_filters = array(
		'amount'=>array(
			array('Currency::display',array(':value')),
		),
		'date_orig'=>array(
			array('Config::date',array(':value')),
		),
		'date_charge'=>array(
			array('Config::date',array(':value')),
		),
		'processed'=>array(
			array('StaticList_YesNo::get',array(':value',TRUE)),
		),
		'sweep_type'=>array(
			array('StaticList_SweepType::get',array(':value')),
		),
		'void'=>array(
			array('StaticList_YesNo::get',array(':value',TRUE)),
		),
	);

	/**
	 * Temporarily override our parent call to reformat old data
	 */
	public function __get($column) {
		switch ($column) {
			case 'attributes':
				$x = parent::__get($column);

				if (is_string($this->_object[$column]) AND preg_match('/==/',$this->_object[$column])) {
					$x = explode("\n",$this->_object[$column]);

					foreach ($x as $k=>$v) {
						if (preg_match('/==/',$x[$k]))
							$x[$k] = preg_replace('/==\s*/',':',$v);

						if (preg_replace('/^ADSL Service:/',"",$x[$k]) == $this->service->plugin()->service_number)
							unset($x[$k]);
					}

					sort($x);
				}

				$this->{$column} = $x;

				return $x;

			default: return parent::__get($column);
		}
	}

	public function invoice_item($item_type) {
		switch ($item_type) {
			case 5:
				return sprintf('%s (%s x %s%s%s) %s',
					StaticList_ItemType::get($item_type),
					$this->quantity,
					$this->display('amount'),
					($this->description ? ' '.$this->description : ''),
					($this->attributes ? ' ['.join('|',$this->attributes).']' : ''),
					$this->display('date_charge'));

			default:
				return sprintf('%s %s',StaticList_ItemType::get($item_type),$this->display('date_charge')).($this->description ? ' ('.$this->description.')' : '');
		}
	}

	/**
	 * Render some details for specific calls, eg: invoice
	 */
	public function details($type) {
		switch ($type) {
			case 'invoice_detail_items':
				return array('Other Charge'=>sprintf('%s (%s@%s)',$this->description,$this->quantity,Currency::display($this->amount)));

			default:
				throw new Kohana_Exception('Unkown detail request :type',array(':type'=>$type));
		}
	}

	public function total($format=FALSE) {
		$result = $this->quantity * $this->amount;

		if ($this->taxable)
			$result = Tax::add($result);

		return $format ? Currency::display($result) : $result;
	}
}
?>