<?php

require_once(SF_ROOT_DIR . "/classes/ParseDataFile.class.php");
require_once(SF_ROOT_DIR . "/classes/class.customer_profile.php");
require_once(SF_ROOT_DIR . "/classes/class.alert_email.php");
require_once(SF_ROOT_DIR . "/web/webservices/includes/class.variables.php");

/**
 * ProofAction actions.
 *
 * @package    admin
 * @subpackage AUTO
 * @author     Peter Alcivar
 * @version    SVN: $Id: ProofAction.class.php peter $
 */


class ProofAction extends sfActions
{
	const CLIENT_ID		= 844;
	private $classmap	= array(
		'C1'				=> 'Class 1 Balance',
		'C2'				=> 'Class 2 Balance',
		'CASH'				=> 'Class 7 Paid'
		);

	private function getProfileOptions()
	{
		$this->setLayout(false);
		$this->setTemplate(false);

		$DmsConn			= Propel::getConnection('dms_main');

		$AmmsId				= $this->getRequestParameter('CustomerId', '0');

		$query				= "SELECT customer_profile.customer_profile_id AS profile_id, customer_profile.profile_name, customer_profile_data.field_value AS brand FROM customer_profile LEFT JOIN customer_profile_data ON customer_profile.customer_profile_id = customer_profile_data.customer_profile_id WHERE customer_profile.customer_id = {$AmmsId} AND customer_profile_data.field_name = 'brand'";

		$Rs					= $DmsConn->executeQuery($query);

		$Profiles			= array();
		while ($Rs->next()) {
			$Profiles[$Rs->get('profile_id').'|'.$Rs->get('profile_name').'|'.$Rs->get('brand')]			= $Rs->get('profile_name') . " (" . $Rs->get('brand') . ")";
		}

		$Options = '';
		foreach ($Profiles as $key => $value) {
			$Options			.= "<option value=\"{$key}\">$value</option>\n";
		}

		return $Options;
	}

	private function getProfileData($ProfileId)
	{
		$DmsConn			= Propel::getConnection('dms_main');

		$query				= "SELECT customer_profile_data.field_name, customer_profile_data.field_value FROM customer_profile_data WHERE customer_profile_id = {$ProfileId}";

		$Rs					= $DmsConn->executeQuery($query);

		$ProfileData		= array();
		while ($Rs->next()) {
			$ProfileData[$Rs->get('field_name')]			= $Rs->get('field_value');
		}

		return $ProfileData;
	}

	private function getDealerCodeByAmmsId($AmmsId)
	{
		$DmsConn			= Propel::getConnection('dms_main');

		$query				= "SELECT customer_profile_data.field_value AS dealer_code FROM customer_profile LEFT JOIN customer_profile_data ON customer_profile.customer_profile_id = customer_profile_data.customer_profile_id WHERE customer_profile.customer_id = {$AmmsId} AND customer_profile.profile_name = 'DEFAULT' AND customer_profile_data.field_name = 'external_customer_code'";

		$Rs					= $DmsConn->executeQuery($query);

		$DealerCode			= false;
		while ($Rs->next()) {
			$DealerCode			= $Rs->get('dealer_code');
		}

		return $DealerCode;
	}


	/**
	* 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');
		}

		$GetProfileOptions	= $this->getRequestParameter("Profiles","0");

		if (!empty($GetProfileOptions)) {
			return $this->renderText($this->GetProfileOptions());
		}


		$Submit				= $this->getRequestParameter("form-submit", '');


		$this->Result		= '';

		if (!empty($Submit)) {
			$CustomerId		= $this->getRequestParameter("CustomerId", '0');
			$ProductCode	= $this->getRequestParameter("ProductId", '0');
			$temp			= explode('|', $ProductCode);
			$ProductId		= $temp[0];
			$ProductNumber	= $temp[1];
			$ProfileCode	= $this->getRequestParameter("ProfileId", '0');
			$temp			= explode('|', $ProfileCode);
			$ProfileId		= $temp[0];
			$ProfileName	= $temp[1];
			$Brand			= $temp[2];

			$ClassId		= $this->getRequestParameter("ClassId", '');

			$DealerCode		= $this->getDealerCodeByAmmsId($CustomerId);

			$filename		= date('Y-m-d-H-i-s-')."proof-cgid{$ProductNumber}-letter_{$DealerCode}.csv";
			$Path			= SF_ROOT_DIR."/data/Dominion/orders/".$filename;

			if (preg_match('/DEFAULT/i', $ProfileName)) {
				$TemplateId		= strtoupper($DealerCode.$ClassId);
			} else {
				$TemplateId		= strtoupper($DealerCode.substr($Brand, 0, 3).$ClassId);
			}

			$ProfileData	= $this->getProfileData($ProfileId);

			$csv_data		= array(
				"letter_id"						=> "25",
				"dealer_id"						=> "{$ProfileData['external_customer_code']}",
				"template_id"					=> $TemplateId,
				"letter_body"					=> "default",
				"service_item_name"				=> "{$ProfileData['sales_dealer_name']}",
				"recommended_service_mileage"	=> "",
				"multi_point_tire"				=> "",
				"multi_point_brake"				=> "",
				"multi_point_battery"			=> "",
				"multi_point_misc"				=> "",
				"multi_point_tire_text"			=> "",
				"multi_point_brake_text"		=> "",
				"multi_point_battery_text"		=> "",
				"multi_point_misc_text"			=> "",
				"1_coupon_name"					=> "",
				"1_coupon_code"					=> "",
				"1_coupon_offer"				=> "",
				"1_coupon_disclaimer"			=> "",
				"1_coupon_expire"				=> "",
				"2_coupon_name"					=> "",
				"2_coupon_code"					=> "",
				"2_coupon_offer"				=> "",
				"2_coupon_disclaimer"			=> "",
				"2_coupon_expire"				=> "",
				"3_coupon_name"					=> "",
				"3_coupon_code"					=> "",
				"3_coupon_offer"				=> "",
				"3_coupon_disclaimer"			=> "",
				"3_coupon_expire"				=> "",
				"coupon_set_graphic"			=> "",
				"evip"							=> "default",
				"dealer_name"					=> "{$ProfileData['sales_dealer_name']}",
				"dealer_addr1"					=> "{$ProfileData['sales_address']}",
				"dealer_addr2"					=> "",
				"dealer_city"					=> "{$ProfileData['sales_city']}",
				"dealer_state"					=> "{$ProfileData['sales_state']}",
				"dealer_zip"					=> "{$ProfileData['sales_zip']}",
				"dealer_phone"					=> "{$ProfileData['sales_phone']}",
				"dealer_hours"					=> "{$ProfileData['trigger_sales_ophrs']}",
				"dealer_web_addr"				=> "{$ProfileData['sales_website_address']}",
				"first_name"					=> "James",
				"last_name"						=> "Kirk",
				"address_1"						=> "{$ProfileData['sales_address']}",
				"address_2"						=> "",
				"city"							=> "{$ProfileData['sales_city']}",
				"state"							=> "{$ProfileData['sales_state']}",
				"zip"							=> "{$ProfileData['sales_zip']}",
				"year"							=> "2000",
				"make"							=> "Subaru",
				"model"							=> "Outback",
				"signator_graphic_id"			=> "223",
				"signator_name"					=> "{$ProfileData['sales_contact_name']}",
				"signator_title"				=> "{$ProfileData['sales_contact_title']}",
				"signator_phone"				=> "{$ProfileData['sales_contact_phone']}",
				"signator_email"				=> "{$ProfileData['sales_contact_email']}",
				"alternate_contact_name"		=> "",
				"alternate_contact_title"		=> "",
				"alternate_contact_phone"		=> "",
				"alternate_contact_email"		=> "",
				"customer_id"					=> "",
				"vin"							=> "JHMGD38628S013599",
				"estimated_mileage"				=> "12345",
				"send_date"						=> "",
				"estimated_service_date"		=> "",
				"queuenode"						=> "",
				"purchase_date"					=> "",
				"class"							=> $this->classmap[strtoupper($ClassId)],
				"current_payment"				=> "",
				"payoff"						=> "",
				"number_of_vehicles"			=> "",
				"number_of_retail_vehicles"		=> "",
				"number_of_lease_vehicles"		=> "",
				"lowest_payment"				=> "",
				"lowest_retail_payment"			=> "",
				"lowest_lease_payment"			=> "",
				"lowest_retail_vin"				=> "",
				"lowest_retail_make"			=> "",
				"lowest_retail_model"			=> "",
				"lowest_retail_year"			=> "",
				"lowest_lease_vin"				=> "",
				"lowest_lease_make"				=> "",
				"lowest_lease_model"			=> "",
				"lowest_lease_year"				=> "",
				"LHEADER"						=> "",
				"LOTHER1"						=> "",
				"LOTHER2"						=> "",
				"LOTHER3"						=> "",
				"LOTHER4"						=> "",
				"LBULLETS1"						=> "",
				"LBULLETS2"						=> "",
				"LBULLETS3"						=> "",
				"LBULLETS4"						=> "",
				"LPS"							=> "",
				"IMAGE_1"						=> "",
				"IMAGE_2"						=> "",
				"IMAGE_3"						=> "",
				"IMAGE_4"						=> "",
				"IMAGE_5"						=> "",
				"IMAGE_6"						=> "",
				"IMAGE_7"						=> "",
				"IMAGE_8"						=> "",
				"IMAGE_9"						=> "",
				"IMAGE_10"						=> "",
				"evip_url"						=> "http://images.mmserver.com/rdir.php?url=http%3A%2F%2Fwww.autoevip.com%3Ffield_custnum%3D-5077580-7B1580&cid=72302633&qnid=3321245215",
				"custom_url"					=> "",
				"book_value"					=> "4800"
				);

			// echo "<pre>".print_r($csv_data, true)."</pre>";


			$file = fopen($Path, "w");
			fputcsv($file, array_keys($csv_data));
			fputcsv($file, array_values($csv_data));
			fclose($file);

			$result = exec(SF_ROOT_DIR."/scripts/proc_dominion_trigger.sh");
			// $result = exec("php ".SF_ROOT_DIR."/batch/proc_dominion_trigger.php");
			$this->Result = "<pre>{$CustomerId}, {$ProductCode}, {$ProductId}, {$ProfileCode}, {$ProfileId}, {$ProfileName}, {$Brand}, {$ClassId}, {$DealerCode}, {$TemplateId}, {$Path}, " . ($result ? "good":"bad")."</pre>\n";
		}


		$Conn				= Propel::getConnection();

		$query				= "SELECT customer_id, name FROM customer WHERE client_id = '".self::CLIENT_ID."' AND active_yn = 'Y' ORDER BY name";

		$Rs					= $Conn->executeQuery($query);

		$customers			= array('0' => 'Select Customer');

		while ($Rs->next()) {
			$customers[$Rs->get('customer_id')]		= $Rs->get('name');
		}

		$this->Customers	= $customers;


		$this->Products		= array(
				'0'				=> 'Select Product',
				'3516|601'		=> '6x11 Postcard',
				'3522|520'		=> '8.5x11 Letter'
			);


		$this->Classes		= array(
				'0'				=> 'Select Class',
				'C1'			=> 'C1',
				'C2'			=> 'C2',
				'Cash'			=> 'Cash'
			);

		return "Success";

	}

}
