<?php
/**
* @version	$Id: ccdate_formatter.php 14241 2011-03-16 20:24:35Z alex $
* @package	In-Portal
* @copyright	Copyright (C) 1997 - 2009 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.
*/

/**
 * Credit card expiration date formatter
 *
 */
class kCCDateFormatter extends kFormatter
{
	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' => '');

		$add_fields = array_merge_recursive2($add_fields, $object->VirtualFields);
		$object->setVirtualFields($add_fields);
	}

	function UpdateSubFields($field, $value, &$options, &$object)
	{
		if(!$value) return false;
		$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 string $value
	 * @param string $field_name
	 * @param kDBItem $object
	 * @return string
	 */
	function Parse($value, $field_name, &$object)
	{
//		if ( is_null($value) ) return '';

		$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;
	}

}