<?php
/**
  * Ahead WebSoft Technologies Pvt Ltd.
  * @copyright  Copyright 2006-2026 Ahead WebSoft Technologies Pvt Ltd.
  * @license    https://www.socialengine.com/policies
*/
class Fields_Form_Element_Birthdate extends Engine_Form_Element_Birthdate
{
  protected $_metaObject;

  public function init()
  {
    parent::init();

		$translate = Zend_Registry::get('Zend_Translate');

    // Set min age
    if( !is_null($this->min_age) ) {

      // Set max year
      $date = new Zend_Date();
      $this->_yearMax = (int) $date->get(Zend_Date::YEAR) - (int) $this->min_age;

      // Add validator
      $validator = new Engine_Validate_Callback(array($this, 'validateAge'));
			$message = $translate->translate('The minimum age is %1$d.');
			$message = sprintf($message, $this->min_age);
      $validator->setMessage($message, 'invalid');
      $this->addValidator($validator);
    }
  }

  public function setMetaObject($meta)
  {
    $this->_metaObject = $meta;
    return $this;
  }

  public function validateAge($value)
  {
    $parts = @explode('-', $value);

    // Error if not filled out
    if( engine_count($parts) < 3 || engine_count(array_filter($parts)) < 3 ) {
      //$this->addError('Please fill in your birthday.');
      return false;
    }

    $value = mktime(0, 0, 0, $parts[1], $parts[2], $parts[0]);

    // Error if too low
    $date = new Zend_Date($value);
    $date->add((int) $this->min_age, Zend_Date::YEAR);

    if ($date->compare(new Zend_Date()) > 0) {
      //$this->addError('You are not old enough.');
      return false;
    }
    
    return true;
  }
}
