<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

require_once('include/MVC/Controller/SugarController.php');

class LeadsController extends SugarController{
	function LeadsController(){
		parent::SugarController();
	}
	function pre_editview(){
		//IF we have a prospect id leads convert it to a lead
		if (empty($this->bean->id) && !empty($_REQUEST['return_module']) &&$_REQUEST['return_module'] == 'Prospects' ) {
				
			$prospect=new Prospect();
			$prospect->retrieve($_REQUEST['return_id']);
			foreach($prospect->field_defs as $key=>$value)
			{
				if ($key == 'id' or $key=='deleted' )continue;
				if (isset($this->bean->field_defs[$key])) {
					$this->bean->$key = $prospect->$key;
				}
			}
			$_POST['is_converted']=true;
		}
		return true;
	}
	function action_editview(){
		$this->view = 'edit';
		return true;
	}
	
	protected function callLegacyCode(){
		if(strtolower($this->do_action) == 'convertlead'){
			if(file_exists('modules/Leads/ConvertLead.php') && !file_exists('custom/modules/Leads/metadata/convertdefs.php')){
				if(!empty($_REQUEST['emailAddressWidget'])) {
					foreach($_REQUEST as $key=>$value) {
						if(preg_match('/^Leads.*?emailAddress[\d]+$/', $key)) {
							$_REQUEST['Leads_email_widget_id'] = 0;
							break;
						}
					}
				}
				$this->action_default();
				$this->_processed = true;
			}else{
				$this->view = 'convertlead';
				$this->_processed = true;
			}
		}else{
			parent::callLegacyCode();
		}
	}
	
	function action_config()
	{
		global $current_user;
		if(!is_admin($current_user)){
			sugar_die($GLOBALS['app_strings']['ERR_NOT_ADMIN']);
		}
		$this->view = 'config';
	}
	
	function action_saveconfig()
	{
		global $current_user;
		if(!is_admin($current_user)){
			sugar_die($GLOBALS['app_strings']['ERR_NOT_ADMIN']);
		}
		$configurator = new Configurator();
		if ($configurator->saveConfig() === false)
		{
			$this->errors = array(
					'company_logo' => $configurator->getError(),
			);
			$this->view = 'edit';
			return;
		}
	
		SugarApplication::redirect('index.php?module=Administration&action=index');
	}
	
	function action_checkDuplicate()
	{
		global $sugar_config;
		echo getDuplicateLead($_GET['record_id']);
		$this->view = 'ajax';
	}
}