<?php
/****************************************
/*  Author 	: Kvvaradha
/*  Module  : Kvcodes CRM
/*  E-mail 	: admin@kvcodes.com
/*  Version : 1.0
/*  Http 	: www.kvcodes.com
*****************************************/
$page_security = 'CRM_OPPORTUNITIES';
$path_to_root="../../..";
include_once($path_to_root . "/includes/db_pager.inc");
include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/db/custom_fields_db.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/ui/custom_fields_ui.inc");
add_access_extensions();
include_once($path_to_root . "/modules/KvcodesCRM/includes/crm.inc" );
include_once($path_to_root . "/modules/KvcodesCRM/includes/activity.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/attachment.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/date_functions.inc");

$version_id = get_company_prefs('version_id');

$js = '';
if($version_id['version_id'] == '2.4.1'){
	if ($SysPrefs->use_popup_windows) 
		$js .= get_js_open_window(900, 500);	

	if (user_use_date_picker()) 
		$js .= get_js_date_picker();
	
}else{
	if ($use_popup_windows)
		$js .= get_js_open_window(900, 500);
	if ($use_date_picker)
		$js .= get_js_date_picker();
}

page(_("Opportunities"), @$_REQUEST['popup'], false, "", $js); 

$new_item = get_post('opportunity_id')=='' || get_post('cancel') || get_post('clone'); 
//------------------------------------------------------------------------------------
if(isset($_GET['Added'])){
	display_notification(_("A New Opportunity Inserted Successfully!"));
}if(isset($_GET['Updated'])){
	display_notification(_("The Selected Opportunity Details Updated Successfully!"));
}
if (isset($_GET['opportunity_id'])){
	$_POST['opportunity_id'] = $_GET['opportunity_id'];
}
$opportunity_id = get_post('opportunity_id');
if (list_updated('opportunity_id')) {
	$_POST['NewOppoID'] = $opportunity_id = get_post('opportunity_id');
    clear_data();
	$Ajax->activate('details');
	$Ajax->activate('controls');
}

if (get_post('cancel')) {
	$_POST['NewOppoID'] = $opportunity_id = $_POST['opportunity_id'] = '';
    clear_data();
	set_focus('opportunity_id');
	$Ajax->activate('_page_body');
}
if (list_updated('category_id') || list_updated('mb_flag') || list_updated('fa_class_id') || list_updated('depreciation_method')) {
	$Ajax->activate('details');
}
function clear_data(){}
//------------------------------------------------------------------------------------
if (isset($_POST['addupdate'])) {

	$input_error = 0;
	if (strlen($_POST['organization_name']) == 0) {
		display_error(_("The ornganization name cannot be empty."));
		set_focus('organization_name');
		return false;
	}	
	if (strlen($_POST['opportunity_name']) == 0) {
		display_error(_("The opportunity name Can't be empty."));
		set_focus('opportunity_name');
		return false;
	}
	if ($_POST['cust_id'] == 0) {
		display_error(_("Select a Customer to continue."));
		set_focus('cust_id');
		return false;
	}
	if ($_POST['contact_id'] == 0) {
		display_error(_("Select a Customer contact to continue."));
		set_focus('contact_id');
		return false;
	}
	if ($input_error != 1){
		
		if($new_item) {			
			$id = Insert('kv_crm_opportunities', array('opportunity_name' => $_POST['opportunity_name'], 'organization_name' => $_POST['organization_name'], 'amount_curr_abrev' => $_POST['amount_curr_abrev'], 'amount' => $_POST['amount'], 
										'type' => $_POST['type'], 'lead_source' => $_POST['lead_source'], 'assign_to' => $_POST['assign_to'], 'sale_stage' => $_POST['sale_stage'],
										'status_id' => $_POST['status_id'], 'cust_id' => $_POST['cust_id'], 'probability' => $_POST['probability'], 'contact_id' => $_POST['contact_id'], 
										'custome_info' => $_POST['custome_info'], 'description' => $_POST['description'], 'expected_close_date' => array($_POST['expected_close_date'], 'date')));
			custom_field_update('opportunities',$id);

			$details = array( 'opportunity_name' => $_POST['opportunity_name'], 'name2' => '','expected_close_date' => $_POST['expected_close_date'],'probability' => $_POST['probability'], 'opportunity_status' => GetSingleValue('kv_crm_picklist_values', 'description', array('id2' => $_POST['status_id'], 'picklist_id' => 6)));				

				if($_SESSION['wa_current_user']->user != $_POST['assign_to']) { // Sent to Staff 
					$staff = GetRow('users', array('id' => $_POST['assign_to']));
					$details['real_name'] = $staff['real_name'];
					$details['probability'] = $_POST['probability'];
					$details['phone'] = $staff['phone'];
					$details['email'] = $staff['email'];
					$to =  array('name' => $staff['real_name'], 'email' => $staff['email']);

					$template = array('slug' => 'opportunities-assigned',  'details' => $details );	
					// display_error(json_encode($template));		
					kv_mail($to, '', '', "html", array(), null, false, $template);
				}
				
			meta_forward($_SERVER['PHP_SELF'], "Added=yes&opportunity_id=$id");
		}else {
			$opportunity_id =  $_POST['opportunity_id'];
			Update('kv_crm_opportunities', array('opportunity_id' => $_POST['opportunity_id']), array('opportunity_name' => $_POST['opportunity_name'], 'organization_name' => $_POST['organization_name'], 'amount_curr_abrev' => $_POST['amount_curr_abrev'], 'amount' => $_POST['amount'], 
										'type' => $_POST['type'], 'lead_source' => $_POST['lead_source'], 'assign_to' => $_POST['assign_to'], 'sale_stage' => $_POST['sale_stage'], 
										'status_id' => $_POST['status_id'], 'cust_id' => $_POST['cust_id'], 'probability' => $_POST['probability'], 'contact_id' => $_POST['contact_id'], 
										'custome_info' => $_POST['custome_info'], 'description' => $_POST['description'], 'expected_close_date' => array($_POST['expected_close_date'], 'date')));
			custom_field_update('opportunities',$_POST['opportunity_id']);
			meta_forward($_SERVER['PHP_SELF'], "Updated=yes&opportunity_id=$opportunity_id");
		}		
	}
}
if(isset($_POST['delete'])){
	$dlt = true;
	if(GetSingleValue('kv_crm_activities', 'COUNT(*)', array('type' => 2, 'type_id' => $_POST['opportunity_id']))){
		$dlt = false;
		display_warning(_("Unable to delete this Opportunity. Some activities referring to it"));
	}
	if($dlt && GetSingleValue('kv_crm_attachments', 'COUNT(*)', array('type' => 2, 'type_id' => $_POST['opportunity_id']))){
		$dlt = false;
		display_warning(_("Unable to delete this Opportunity. Some attachments referring to it"));
	}
		
	if($dlt){
		Delete('kv_crm_opportunities', array('opportunity_id' => $_POST['opportunity_id']));
		display_notification(_("Selected Opportunity has been deleted"));
	}
		
}elseif (isset($_POST['clone'])) {
	unset($_POST['opportunity_id']);	
	set_focus('opportunity_exist_id');
	$Ajax->activate('_page_body');
}
//------------------------------------------------------------------------------------
function opportunity_settings(&$opportunity_id, $new_item) {

	global $SysPrefs, $path_to_root, $page_nested, $depreciation_methods;
	if (!$new_item) {
		$myrow = GetRow('kv_crm_opportunities', array('opportunity_id' => $_POST['opportunity_id']));
			
			$_POST['opportunity_exist_id'] = $myrow["opportunity_id"];
			$_POST['opportunity_name'] = $myrow["opportunity_name"];
			$_POST['organization_name'] = $myrow["organization_name"];
			$_POST['amount_curr_abrev'] = $myrow["amount_curr_abrev"];
			$_POST['amount'] = $myrow["amount"];
			$_POST['type'] = $myrow["type"];
			$_POST['expected_close_date'] = sql2date($myrow["expected_close_date"]);
			$_POST['lead_source'] = $myrow["lead_source"];
			$_POST['assign_to'] = $myrow["assign_to"];
			$_POST['sale_stage'] = $myrow["sale_stage"];
			$_POST['status_id'] = $myrow["status_id"];
			$_POST['cust_id'] = $myrow["cust_id"];
			$_POST['probability'] = $myrow["probability"];
			$_POST['contact_id'] = $myrow["contact_id"];
			$_POST['custome_info'] = $myrow["custome_info"];
			$_POST['description'] = $myrow["description"];
	} elseif(!list_updated('cust_id')) 
		$_POST['description'] = $_POST['custome_info'] = $_POST['contact_id'] = $_POST['probability'] = $_POST['status_id'] = $_POST['sale_stage'] = $_POST['assign_to'] = $_POST['opportunity_name'] = $_POST['organization_name'] = $_POST['amount_curr_abrev'] = $_POST['amount'] = $_POST['type'] = $_POST['lead_source'] = '';
	start_outer_table(TABLESTYLE2);
	table_section(1);
	table_section_title(_("Opportunity Details"));
		text_row('Opportunities Name','opportunity_name', null, 35,30);						
		text_row('Organization Name','organization_name', null, 35,30);	
		currencies_list_row(_("Currency"), 'amount_curr_abrev',null,false);   
		amount_row(_("Amount"), 'amount', null);
		kv_common_type_row(_('Business Type') ,'type',null, false, false,3);		
		date_row('Expected Close Date', 'expected_close_date', _('Date of Expected Close Date'));							
		kv_common_type_row(_('Lead Source') ,'lead_source', null, true, false, 1);
		kv_user_list_row('Assigned To','assign_to', null, _("Select an User"), '');	
		//sales_stage_row('Sales Stage','sale_stage');
		kv_common_type_row(_('Sales Stage') ,'sale_stage',null, true, false,5); 	
		kv_common_status_row(_('Status'), 'status_id', null,  true, false,5);
		
	//for custom fields
	custom_field_section('opportunities',(isset($_POST['opportunity_id']) ? $_POST['opportunity_id'] : 0 ),1);
	//end custom fields

	//------------------------------------------------------------------------------------
	table_section(2);
	table_section_title(_("Opportunity Details"));
		text_row('Probability','probability', null, '', '');
		if(list_updated('cust_id')){			
			$_POST['cust_id'] = get_post('cust_id');
		}
		customer_list_row('Customer','cust_id', null, false, true);
		kv_contact_list_row('Contact Name','contact_id', null, null);
		text_row('Custom Information','custome_info', null, 50, 50);
		textarea_row('Description Details','description', null, 45, 10);
	//for custom fields
	custom_field_section('opportunities',(isset($_POST['opportunity_id']) ? $_POST['opportunity_id'] : 0 ),2);
	//end custom fields
	end_outer_table(1);

	div_start('controls');
	if (@$_REQUEST['popup']) hidden('popup', 1);
	if ( $new_item) 	{
		submit_center('addupdate', _("Insert New Opportunity"), true, '', 'default');
	} else {
		submit_center_first('addupdate', _("Update Opportunity"), '', 	$page_nested ? true : 'default');
		submit_return('select', get_post('opportunity_id'), 	_("Select this items and return to document entry."));
		submit('clone', _("Clone This Opportunity"), true, '', true);
		submit('delete', _("Delete This Opportunity"), true, '', true);
		submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
	}
	div_end();
}

//-------------------------------------------------------------------------------------------- 
start_form(true);
if (db_has_opportunities()) {
	start_table(TABLESTYLE_NOBORDER);
	start_row();
    opportunity_list_cells(_("Select an Opportunity"). " :", 'opportunity_id', null,  _("New Opportunity"), true, check_value('show_inactive'));
	$new_item = get_post('opportunity_id')=='';
	check_cells(_("Show inactive:"), 'show_inactive', null, true);
	end_row();
	end_table();

	if (get_post('_show_inactive_update')) {
		$Ajax->activate('opportunity_id');
		set_focus('opportunity_id');
	}
} else{
	hidden('opportunity_id', get_post('opportunity_id'));
}

div_start('details');

$opportunity_id = get_post('opportunity_id');
if (!$opportunity_id)
	unset($_POST['_tabs_sel']); // force settings tab for new customer

$tabs =  array(
		'settings' => array(_('&General'), $opportunity_id),
		'activity' => array(_('&Activity'), $opportunity_id),
		'attachments' => array(_('Attachments'), (user_check_access('SA_SALESPRICE') ? $opportunity_id : null)),	
		//'status' => array(_('&Status'), (user_check_access('SA_ITEMSSTATVIEW') ? $opportunity_id : null))	
	);

tabbed_content_start('tabs', $tabs);

	switch (get_post('_tabs_sel')) {
		default:
		case 'settings':
			opportunity_settings($opportunity_id, $new_item); 
			break;
		
		case 'attachments':
			/*$_GET['type_id'] = $opportunity_id;
			$_GET['type']= 2;  // type
			$_GET['page_level'] = 1;
			include_once($path_to_root."/modules/KvcodesCRM/manage/attachments.php");*/
			$_GET['type_id'] = $opportunity_id;	
			$_GET['type']= ST_OPPORTUNITIES;  //Opportunity type
			$attachments = new attachments('attachment', $opportunity_id, 'Opportunity');
			$attachments->show();
			break;
		case 'activity':
			$_GET['type_id'] = $opportunity_id;	
			$_GET['type']= ST_OPPORTUNITIES;  //Opportunity type
			$activity = new activity('activity', $opportunity_id, 'opportunity');
			$activity->show();
			break;
		case 'updates':
			$_GET['opportunity_id'] = $opportunity_id;
			//include_once($path_to_root."/inventory/inquiry/stock_movements.php");
			break;
		case 'status':
			$_GET['opportunity_id'] = $opportunity_id;
			//include_once($path_to_root."/inventory/inquiry/stock_status.php");
			break;
	};

br();
tabbed_content_end();
div_end();
end_form();

end_page();
?>