<?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 {
	protected $_belongs_to = array(
		'account'=>array(),
		'product'=>array(),
		'service'=>array(),
	);

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

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

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

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

	/**
	 * 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);
		}
	}

	/** REQUIRED ABSTRACT METHODS **/

	/** LOCAL METHODS **/

	/**
	 * Return the Invoice Item object for this charge
	 */
	public function iio() {
		$iio = ORM::factory('Invoice_Item');
		if ($this->processed) {
			$iio->where('module_id','=',$this->mid())
				->where('module_ref','=',$this->id)
				->find();
		}

		return $iio;
	}

	public function name($variable=NULL) {
		return StaticList_ItemType::get($this->type);
	}

	public function namesub($variable=NULL) {
		return sprintf('%d@%2.2f - %s (%s)',$this->quantity,$this->amount,($this->description ? ' '.$this->description : '').($this->attributes ? ' ['.join('|',$this->attributes).']' : ''),$this->display('date_charge'));
	}
	public function total($format=FALSE) {
		$result = $this->quantity * $this->amount;

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

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