<?php
/**
* @version	$Id: ccdate_formatter.php 14748 2011-11-09 09:35:48Z alex $
* @package	In-Portal
* @copyright	Copyright (C) 1997 - 2011 Intechnic. All rights reserved.
* @license      GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/

defined('FULL_PATH') or die('restricted access!');

/**
 * Credit card expiration date formatter
 *
 */
class kCCDateFormatter extends kFormatter
{
	/**
	 * The method is supposed to alter config options or cofigure object in some way based on its usage of formatters
	 * The methods is called for every field with formatter defined when configuring item.
	 * Could be used for adding additional VirtualFields to an object required by some special Formatter
	 *
	 * @param string $field_name
	 * @param array $field_options
	 * @param kDBBase $object
	 */
	function PrepareOptions($field_name, &$field_options, &$object)
	{
		$add_fields = Array();

		$i = 1;
		$options = Array('00' => '');
		while($i <= 12)
		{
			$options[ sprintf('%02d',$i) ] = sprintf('%02d',$i);
			$i++;
		}
		$add_fields[ $field_options['month_field'] ] = Array('formatter'=>'kOptionsFormatter', 'options' => $options, 'not_null' => true, 'default' => '00');
		$add_fields[ $field_options['year_field'] ] = Array('type' => 'string', 'default' => '');

		$virtual_fields = $object->getVirtualFields();
		$add_fields = kUtil::array_merge_recursive($add_fields, $virtual_fields);
		$object->setVirtualFields($add_fields);
	}

	/**
	 * Used for split fields like timestamp -> date, time
	 * Called from DBItem to update sub fields values after loading item
	 *
	 * @param string $field
	 * @param string $value
	 * @param Array $options
	 * @param kDBItem $object
	 * @return void
	 * @access public
	 */
	public function UpdateSubFields($field, $value, &$options, &$object)
	{
		if ( !$value ) {
			return ;
		}

		$date = explode('/', $value);
		$object->SetDBField($options['month_field'], $date[0]);
		$object->SetDBField($options['year_field'], $date[1]);
	}

	/**
	 * Will work in future if we could attach 2 formatters to one field
	 *
	 * @param mixed $value
	 * @param string $field_name
	 * @param kDBItem $object
	 * @return mixed
	 * @access public
	 */
	public function Parse($value, $field_name, &$object)
	{
		$options = $object->GetFieldOptions($field_name);

		$month = $object->GetDirtyField($options['month_field']);
		$year = $object->GetDirtyField($options['year_field']);

		if ( !(int)$month && !(int)$year ) {
			return NULL;
		}

		$is_valid = ($month >= 1 && $month <= 12) && ($year >= 0 && $year <= 99);

		if ( !$is_valid ) {
			$object->SetError($field_name, 'bad_type');
		}
		
		return $month . '/' . $year;
	}

}