<?php

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

		$this->widgetSchema['reference'] = new sfWidgetFormInput(array(), array('style' => 'width: 250px'));
		$this->widgetSchema['name'] = new sfWidgetFormInput(array(), array('style' => 'width: 250px'));
		$this->widgetSchema['accounting_code_purchase'] = new sfWidgetFormInput(array(), array('style' => 'width: 40px'));
		$this->widgetSchema['accounting_code_sell'] = new sfWidgetFormInput(array(), array('style' => 'width: 40px'));
		$this->widgetSchema['min_order_number'] = new sfWidgetFormInput(array(), array('style' => 'width: 20px'));
		$this->widgetSchema['delivery_delay'] = new sfWidgetFormInput(array(), array('style' => 'width: 20px'));
		$this->widgetSchema['max_sol_amount'] = new sfWidgetFormInput(array(), array('style' => 'width: 54px'));
		$this->widgetSchema['unit_price_euro'] = new sfWidgetFormInput(array(), array('style' => 'width: 54px'));
		$this->widgetSchema['margin'] = new sfWidgetFormInput(array(), array('style' => 'width: 54px'));

		$this->widgetSchema['katao_product_family_id'] = new sfWidgetFormSelect(array('choices' => KataoProductFamilyPeer::getAllGroupedByCategory()));

		$this->validatorSchema['accounting_code_purchase'] = new sfValidatorPass();
		$this->validatorSchema['accounting_code_sell'] = new sfValidatorPass();

		$sf_user = sfContext::getInstance()->getUser();
		if ($sf_user->isJustReferer()) {
			$this->widgetSchema['katao_supplier_id'] = new sfWidgetFormSelect(array('choices' => KataoSupplierPeer::getAllByRefererId($sf_user->getInstance()->getKataoMemberId())));
		} elseif ($sf_user->isJustDelegate()) {
			$this->widgetSchema['katao_supplier_id'] = new sfWidgetFormSelect(array('choices' => KataoSupplierPeer::getAllLocalToNode($sf_user->getInstance()->getKataoMember()->getKataoNodeId())));
		} else {
			$this->widgetSchema['katao_supplier_id'] = new sfWidgetFormSelect(array('choices' => KataoSupplierPeer::getAllSimple()));
		}

		if ($sf_user->isJustSupplier()) {
			unset($this->validatorSchema['accounting_code_purchase'], $this->validatorSchema['accounting_code_sell']);
			unset($this->widgetSchema['accounting_code_purchase'], $this->widgetSchema['accounting_code_sell']);
		}

		if ($this->getObject()->isNew()) {
			$this->setDefault('margin', 0.15);
		}
		$this->widgetSchema['tva_rate'] = new sfWidgetFormSelect(array('choices' => array('0' => '0%', '0.055' => '5.5%', '0.2' => '20%')));

		$this->widgetSchema['is_archived'] = new wpWidgetFormInputCheckbox();
		$this->widgetSchema['is_archived']->setOption('value_attribute_value', 1);
		if ((bool)$this->getObject()->getIsArchived()) {
			$this->widgetSchema['is_archived']->setAttribute('checked', 'checked');
		}
		$this->widgetSchema['authorize_decimal'] = new wpWidgetFormInputCheckbox();
		$this->widgetSchema['authorize_decimal']->setOption('value_attribute_value', 1);
		if ((bool)$this->getObject()->getAuthorizeDecimal()) {
			$this->widgetSchema['authorize_decimal']->setAttribute('checked', 'checked');
		}

		$this->widgetSchema['picture'] = new wpWidgetFormInputFile(array(), array('file_src' => $this->getObject()->getPicture()));
		$this->validatorSchema['picture'] = new sfValidatorFile(array('required' => false, 'mime_types' => array('image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png', 'image/gif', 'image/jpeg; charset=binary')), array('mime_types' => 'Merci de choisir une image au format jpg, png ou gif (%mime_type%)'));

		$this->widgetSchema->setLabels(array(
				'reference' => 'Référence',
				'name' => 'Nom',
				'katao_product_family_id' => 'Rayon/Famille',
				'katao_supplier_id' => 'Fournisseur',
				'max_sol_amount' => 'Montant maxi',
				'unit_price_euro' => 'Prix d\'achat HT',
				'tva_rate' => 'Taux de TVA',
				'min_order_number' => 'Colisage',
				'margin' => 'Marge',
				'picture' => 'Photo',
				'delivery_delay' => 'Délai de livraison',
				'is_archived' => 'Archivé ?',
				'accounting_code_purchase' => 'Achat',
				'accounting_code_sell' => 'Vente',
				'authorize_decimal' => 'Autoriser quantités avec décimales',
				));

		$this->validatorSchema->setPostValidator(new sfValidatorCallback(array('callback' => array($this, 'checkMaxSolAmount')), array('invalid' => 'Le montant de la monnaie complémentaire est trop important.')));
	}

	public function checkMaxSolAmount($validator, $value) {
		$max_sol_amount = (int)sfContext::getInstance()->getRequest()->getParameter('katao_product[max_sol_amount]');

		$price = (float)sfContext::getInstance()->getRequest()->getParameter('katao_product[unit_price_euro]');
		$tva_rate = (float)sfContext::getInstance()->getRequest()->getParameter('katao_product[tva_rate]');
		$margin = (float)sfContext::getInstance()->getRequest()->getParameter('katao_product[margin]') / 100;

		if (10 * round($price * (1 + $margin) * (1 + $tva_rate), 2) < $max_sol_amount) {
			throw new sfValidatorError($validator, 'invalid');
		}
		return $value;
	}

	public function doSave($con = null) {
		$file = $this->getValue('picture');
		if ($file && is_object($file)) {
			if (is_file(sfConfig::get('sf_web_dir') . $this->getObject()->getPicture())) {
				unlink(sfConfig::get('sf_web_dir') . $this->getObject()->getPicture());
			}

			$filename = sha1($file->getOriginalName()) . $file->getExtension($file->getOriginalExtension());
			$file->save(sfConfig::get('sf_upload_dir') . '/repository/produits/' . $filename);
		} elseif (!empty($_REQUEST['RemovePicture'])) {
			if (is_file(sfConfig::get('sf_web_dir') . $this->getObject()->getPicture())) {
				unlink(sfConfig::get('sf_web_dir') . $this->getObject()->getPicture());
			}
			$this->getObject()->setPicture(null);
		}

		return parent::doSave($con);
	}

	public function updateObject($values = null) {
		$picture = $this->getObject()->getPicture();
		$object =/*(KataoProduct)*/ parent::updateObject($values);

		$file = $this->getValue('picture');
		if ($file && is_object($file)) {
			$object->setPicture(str_replace(sfConfig::get('sf_web_dir'), '', $object->getPicture()));
		} else {
			$object->setPicture($picture);
		}
		$object->setMargin($this->getValue('margin') / 100);

		return $object;
	}
}
