<?php

/**
 * GreensImporterAction actions.
 *
 * @package    admin
 * @subpackage HVAC
 * @author     Peter Alcivar
 * @version    SVN: $Id: GreensImporterAction.class.php 2692 2006-11-15 21:03:55Z fabien $
 */


class GreensImporterAction extends sfActions
{
	/**
	* Executes index action
	*
	*/

	public function execute()
	{
		// Check Auth
		$Auth				= new checkAuth();
		$Auth->_groups		= array('Admin');
		$Auth->_permissions	= array();
		$Auth->_user		= $this->getUser();
		if (!$Auth->isAuthenticated()) {
			return $this->forward('default', 'NoAccess');
		}

		$Submit				= $this->getRequestParameter("form-submit", '');
		$this->errors		= array();
		if (!empty($Submit)) {

			$ConsumerFileName	= $this->getRequest()->getFileName("consumers");
			if (!preg_match("/\.csv$/i", $ConsumerFileName)) {
				$this->errors[]	= "Consumer file must be in CSV format.";
			}
			$ContractFileName	= $this->getRequest()->getFileName("contracts");
			if (!preg_match("/\.csv$/i", $ContractFileName)) {
				$this->errors[]	= "Contract file must be in CSV format.";
			}

			if (empty($this->errors)) {
				require_once(SF_ROOT_DIR."/apps/".SF_APP."/lib/class.GreensImporter.php");
				$this->AccessControl	= new AccessControl($this);
				$timestamp		= date('Ymd_His');
				// reduce the chance of collisions by adding both the user id and timestamp
				$ConsumerFile	= SF_ROOT_DIR."/data/consumers_{$this->AccessControl->UserId}_{$timestamp}.csv";
				$ContractFile	= SF_ROOT_DIR."/data/contracts_{$this->AccessControl->UserId}_{$timestamp}.csv";
				$Historical		= $this->getRequestParameter("historical", "0");
				$Historical		= !empty($Historical);
				$this->getRequest()->moveFile("consumers", $ConsumerFile);
				$this->getRequest()->moveFile("contracts", $ContractFile);

				$CustomerId			= 15720;

				$Importer			= new GreensImporter($ConsumerFile, $ContractFile, $CustomerId, $Historical);
				$Importer->setDebug(true);
				$Importer->setTestonly(false);
				$this->results		= $Importer->run();
			}
		}

		return "Success";
	}

}
