<?php

/**
 * KataoPeriod form.
 *
 * @package katao
 * @subpackage form
 * @author Your name here
 * @version SVN: $Id: sfPropelFormTemplate.php 10377 2008-07-21 07:10:32Z dwhittle $
 */
class KataoPeriodForm extends BaseKataoPeriodForm {
    public function configure() {
        unset($this->validatorSchema['status'], $this->validatorSchema['created_at'], $this->validatorSchema['updated_at']);
        unset($this->widgetSchema['status'], $this->widgetSchema['created_at'], $this->widgetSchema['updated_at']);

        $this->widgetSchema['begin_at'] = new wpWidgetFormRichDate();
        $this->validatorSchema['begin_at'] = new sfValidatorDateTime(array('date_format' => '@(?P<day>\d{2}).(?P<month>\d{2}).(?P<year>\d{4})@'));
        $this->widgetSchema['finish_at'] = new wpWidgetFormRichDate();
        $this->validatorSchema['finish_at'] = new sfValidatorDateTime(array('date_format' => '@(?P<day>\d{2}).(?P<month>\d{2}).(?P<year>\d{4})@'));
        $this->widgetSchema['order_ended_at'] = new wpWidgetFormRichDate();
        $this->validatorSchema['order_ended_at'] = new sfValidatorDateTime(array('date_format' => '@(?P<day>\d{2}).(?P<month>\d{2}).(?P<year>\d{4})@'));

        $this->widgetSchema->setLabels(array(
                'name' => 'Nom',
                'begin_at' => 'Date de début',
                'finish_at' => 'Date de fin',
                'order_ended_at' => 'Date de limite demandes',
                ));

        $this->validatorSchema->setPostValidator(new sfValidatorCallback(array('callback' => array($this, 'checkConflictedPeriodDates')), array('invalid' => 'Une période a des dates similaires.')));
    }

    public function checkConflictedPeriodDates($validator, $value) {
        $sf_request = sfContext::getInstance()->getRequest();
        $sf_user = sfContext::getInstance()->getUser();
        $sf_i18n = sfContext::getInstance()->getI18N();

        $id = $sf_request->getParameter('katao_period[id]');
        $finish_at = $sf_request->getParameter('katao_period[finish_at]');

        list($d, $m, $y) = $sf_i18n->getDateForCulture($sf_request->getParameter('katao_period[begin_at]'), $sf_user->getCulture());
        $begin_at = mktime(0, 0, 0, $m, $d, $y);

        list($d, $m, $y) = $sf_i18n->getDateForCulture($sf_request->getParameter('katao_period[finish_at]'), $sf_user->getCulture());
        $finish_at = mktime(0, 0, 0, $m, $d, $y);

        if (KataoPeriodPeer::hasConflictedPeriodDates($begin_at, $finish_at, $id)) {
            throw new sfValidatorError($validator, 'invalid');
        }

        return $value;
    }

    protected function doSave($con = null) {
        $return = parent::doSave($con);
        $this->getObject()->updateAvailableProducts(!empty($_POST['suppliers_with_all_products'])?$_POST['suppliers_with_all_products']:'', !empty($_POST['products'])?$_POST['products']:array(), $con = null);
        return $return;
    }
}