<?php
/**********************************************************
* @project:	HolidaysByWyndham - Webform Promo Code Check
* @file:		webform_promocode.module
* @version:	0.1
* @author:	Alexander Noakes - Milan Shahroodi
* 
* Further reference: http://drupal.org/node/908600
**********************************************************/


/**
 * Implementation of hook_webform_validation_validators().
 * Will display in list of validation methods for webforms
 */
function webform_promocode_webform_validation_validators() {
  return array(
  //When list of Validation methods requested return this new one.
    'validate_id' => array(
	//What is it called and type of field it can validate
      'name' => "Promo Code",
      'component_types' => array(
        'textfield',
      ),
	  //Add custom validation error message text box on edit rule screen for validation
	  'custom_error' => TRUE,
	  //Add the description so user knows what it can apply to.
	  'description' => t('Current Promo Code Validator. Checks for Content Type Promo Code and adds to webform submission for tracking later'),
    )
  );
}

/**
 * Implementation of hook_webform_validation_validate().
 * Once the validation type is called it will check using a Query for valid Promo Code Nodes
 * which are content type: Promo Code. To be valid they must be within active date range
 */
function webform_promocode_webform_validation_validate($validator_name, $items, $components, $rule) {
  if ($items) {
    switch ($validator_name) {
      case 'validate_id':
	  
		$errors = array();
		
		if (!$valid_ids = db_query("SELECT n.title, d.field_date_start_value, d.field_date_start_value2
				FROM node n
				join field_data_field_date_start d
					on n.nid = d.entity_id
				WHERE type = 'promo_code'")->fetchAll())
		{
			$errors[reset(array_keys($items))] = t('No Promo Codes Available');
			return false;
         }
		
		// Loop All User Inputs of this type
		foreach ($items as $k=>$input)
		{
			$valid = false;

			// Loop Valid Codes Available
			foreach($valid_ids as $code)
				// Check if Current Valid Code = User Input, 
				if(		$code->title == $input
					and	strtotime($code->field_date_start_value) < time()
					and	time() < strtotime($code->field_date_start_value2)
				)
					// Flag Success
					$valid = true;
			
			if(!$valid)
				$errors[$k] = t('Invalid Promo Code Supplied');
		}

        return $errors;
	#	return false;
        break;
    }
  }
}
