<?php
/****************************************
/*  Author 	: Kvvaradha
/*  Module 	: Kvcodes CRM
/*  E-mail 	: admin@kvcodes.com
/*  Version : 1.0
/*  Http 	: www.kvcodes.com
*****************************************/
$page_security = 'CRM_LEADS';
$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");
$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();
}
 
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/date_functions.inc");

add_js_file('../modules/KvcodesCRM/js/nicEdit-latest.js');

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

$new_item = get_post('lead_id')=='' || get_post('cancel') || get_post('clone'); 
//------------------------------------------------------------------------------------
$user = $_SESSION["wa_current_user"]->name;

// display_error(json_encode($user));


if (isset($_GET['lead_id'])){
	$_POST['lead_id'] = $_GET['lead_id'];
}
$lead_id = get_post('lead_id');

if (list_updated('lead_id')) {
	$_POST['NewLeadID'] = $lead_id = get_post('lead_id');
    clear_data();
	$Ajax->activate('details');
	$Ajax->activate('controls');
}

if (get_post('cancel')) {
	$_POST['NewLeadID'] = $lead_id = $_POST['lead_id'] = '';
    clear_data();
	set_focus('lead_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');
}*/
//display_error($_POST['contacted_today']);
if(isset($_GET['Added'])){
	display_notification(_("A New Lead Inserted Successfully!"));
}if(isset($_GET['Updated'])){
	display_notification(_("The Selected Lead Details Updated Successfully!"));
}
if(get_post('contacted_today')) {
	$_POST['contacted_today'] = 1;	
}
function clear_data(){
	unset($_POST['lead_exist_id'] , $_POST['salutation'] ,$_POST['first_name'], $_POST['last_name'], $_POST['addr_line1'] , $_POST['addr_line2'], $_POST['address2'], $_POST['city'], $_POST['country'],$_POST['state'], $_POST['work_phone'],$_POST['mobile_phone'], $_POST['email'],$_POST['client'],$_POST['title'],$_POST['website'],$_POST['note'],$_POST['lead_source_id'],$_POST['industry_id'],$_POST['lead_status_id'],$_POST['added_by'],$_POST['managed_by'],$_POST['contacted_today'],$_POST['contacted_date']);
}

if (isset($_POST['addupdate'])) {

	$input_error = 0;
	if (strlen($_POST['first_name']) == 0) {
		display_error(_("The Lead name cannot be empty."));
		set_focus('first_name');
		return false;
	}	
	if (strlen($_POST['mobile_phone']) == 0) {
		display_error(_("The mobile number Can't be empty."));
		set_focus('mobile_phone');
		return false;
	} 
	if (strlen($_POST['email']) == 0) {
		display_error(_("The E-mail Can't be empty."));
		set_focus('email');
		return false;
	}

	if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
		display_error(_("The Entered E-Mail is not Valid."));
		set_focus('email');
		return false;
	}

	if ($input_error != 1){
		$date = (check_value('contacted_today') ? Today() : $_POST['contacted_date']);
		if($new_item) {			
			$id = Insert('kv_crm_leads', array('salutation' => $_POST['salutation'], 'first_name' => $_POST['first_name'], 'last_name' => $_POST['last_name'], 'addr_line1' => $_POST['addr_line1'], 
										'addr_line2' => $_POST['addr_line2'], 'city' => $_POST['city'], 'state' => $_POST['state'], 'country' => $_POST['country'], 'address2' => $_POST['address2'], 'curr_code' => $_POST['curr_code'],
										'work_phone' => $_POST['work_phone'], 'mobile_phone' => $_POST['mobile_phone'], 'email' => $_POST['email'], 'client' => $_POST['client'], 
										'title' => $_POST['title'], 'website' => $_POST['website'], 'note' => $_POST['note'], 'lead_source_id' => $_POST['lead_source_id'],
										'industry_id' => $_POST['industry_id'], 'lead_status_id' => $_POST['lead_status_id'], 'added_by' => $_POST['added_by'], 
										'managed_by' => $_POST['managed_by'], 'note' => $_POST['note'], 'date' => array($date, 'date')));

			custom_field_update('leads',$id);
			$staff = GetRow('users', array('id' => $_POST['managed_by']));
			$to =  array('name' => $staff['real_name'], 'email' => $staff['email']);

			$details = array('real_name' => $staff['real_name'], 'name2' => '',  'phone' => $_POST['mobile_phone'], 'email' => $staff['email'], 'lead_name' => $_POST['first_name'].' '.$_POST['last_name'], 'lead_email' => $_POST['email']);

			$template = array('slug' => 'new-lead-assigned',  'details' => $details );
			kv_mail($to, '', '', "html", array(), null, false, $template);
			
			meta_forward($_SERVER['PHP_SELF'], "Added=yes&lead_id=$id");
		}else {
			$lead_id =  $_POST['lead_id'];
			Update('kv_crm_leads', array('lead_id' => $_POST['lead_id']), array('salutation' => $_POST['salutation'], 'first_name' => $_POST['first_name'], 'last_name' => $_POST['last_name'], 'addr_line1' => $_POST['addr_line1'], 
										'addr_line2' => $_POST['addr_line2'], 'city' => $_POST['city'], 'state' => $_POST['state'], 'country' => $_POST['country'], 'address2' => $_POST['address2'], 'curr_code' => $_POST['curr_code'],
										'work_phone' => $_POST['work_phone'], 'mobile_phone' => $_POST['mobile_phone'], 'email' => $_POST['email'], 'client' => $_POST['client'], 
										'title' => $_POST['title'], 'website' => $_POST['website'], 'note' => $_POST['note'], 'lead_source_id' => $_POST['lead_source_id'],
										'industry_id' => $_POST['industry_id'], 'lead_status_id' => $_POST['lead_status_id'], 'added_by' => $_POST['added_by'], 
										'managed_by' => $_POST['managed_by'], 'date' => array($date, 'date')));

			custom_field_update('leads',$lead_id);
			meta_forward($_SERVER['PHP_SELF'], "Updated=yes&lead_id=$lead_id");
		}		
	}
} elseif(isset($_POST['convert'])){
	$lead_id= $_POST['lead_id'];
	meta_forward('convert_to_customer.php', "lead_id=$lead_id");
}elseif(isset($_POST['convert_opp'])){
	$lead_id= $_POST['lead_id'];
	meta_forward('convert_to_opp.php', "lead_id=$lead_id");
}
if (get_post('clone')) {
	unset($_POST['lead_id']);	
	unset($_POST['is_converted']);
	set_focus('lead_exist_id');
	$Ajax->activate('_page_body');
}
if(isset($_POST['delete'])){
	$is_converted = GetSingleValue('kv_crm_leads', 'is_converted', array('lead_id' => $_POST['lead_id']));
	if(!$is_converted){
		$dlt = true;
		if(GetSingleValue('kv_crm_tasks', 'COUNT(*)', array('type' => 1, 'type_id' => $_POST['lead_id']))){
			$dlt = false;
			display_warning(_("Unable to delete this Lead. Some Tasks referring to it"));
		}
		if($dlt && GetSingleValue('kv_crm_attachments', 'COUNT(*)', array('type' => 1, 'type_id' => $_POST['lead_id']))){
			$dlt = false;
			display_warning(_("Unable to delete this Lead. Some attachments referring to it"));
		}
		if( $dlt && GetSingleValue('kv_crm_activities', 'COUNT(*)', array('type' => 1, 'type_id' => $_POST['lead_id']))){
			$dlt = false;
			display_warning(_("Unable to delete this Lead. Some activities referring to it"));
		}
		if($dlt && GetSingleValue('kv_crm_sales_orders', 'COUNT(*)', array('type' => ST_SALESPROPOSAL, 'debtor_no' => $_POST['lead_id']))){
			$dlt = false;
			display_warning(_("Unable to delete this Lead. Some Proposals referring to it"));
		}

	}
	if($dlt){
		Delete('kv_crm_leads', array('lead_id' => $_POST['lead_id']));
		display_notification(_("Selected Lead has been deleted"));
	}	
}

function lead_settings(&$lead_id, $new_item) {

	global $SysPrefs, $path_to_root, $page_nested;
	if (!$new_item || $lead_id) {
		$myrow = GetRow('kv_crm_leads', array('lead_id' => $lead_id));
			
			$_POST['lead_exist_id'] = $myrow["lead_id"];
			$_POST['salutation'] = $myrow["salutation"];
			$_POST['first_name'] = $myrow["first_name"];
			$_POST['last_name'] = $myrow["last_name"];
			$_POST['addr_line1']  = $myrow["addr_line1"];
			$_POST['addr_line2']  = $myrow["addr_line2"];
			$_POST['address2']  = $myrow["address2"];
			$_POST['city']  = $myrow["city"];
			$_POST['country']  = $myrow["country"];
			$_POST['state']  = $myrow["state"];
			$_POST['work_phone']	= $myrow["work_phone"];
			$_POST['mobile_phone']  = $myrow["mobile_phone"];
			$_POST['email']  = $myrow["email"];
			$_POST['curr_code']  = $myrow["curr_code"];
			$_POST['client']  = $myrow["client"];
			$_POST['title']  = $myrow["title"];
			$_POST['website']  = $myrow["website"];
			$_POST['note']  = $myrow["note"];
			$_POST['lead_source_id']  = $myrow["lead_source_id"];
			$_POST['industry_id']  = $myrow["industry_id"];
			$_POST['lead_status_id']  = $myrow["lead_status_id"];
			$_POST['added_by']  = $myrow["added_by"];
			$_POST['managed_by']  = $myrow["managed_by"];
			$_POST['contacted_today'] = 0;
			$_POST['contacted_date']  = sql2date($myrow["date"]);
	} else {
		$_POST['curr_code']  = get_company_currency();
		if(!isset($_POST['country']))
			$_POST['country'] = GetSingleValue('kv_crm_option', 'option_value', array('option_name' => 'home_country'));
	}
	start_outer_table(TABLESTYLE2);

	table_section(1);
	
	/*$subject= "Lead creation Mail";
	$message = " Hello, <br>Someone requested resetting Your Password with our system. If its you please follow the below link to create new password for you to login with our system. <br><a href='?reset_password=123' style='font-size: 24px;'> Rest Password </a>";
	$message .="<br> 
			Thank you,<br>";
		//$attachment = array( 'summa.png' => ABSPATH.'/files/58b5a51e865e9.png');
	kv_mail(array('name' => 'Varadha', 'email' => 'kvvaradha@gmail.com'), $subject, $message, "html");*/ 

	table_section_title(_("Basic Details"));
	kv_crm_salutation_list_row( _("Salutation:"), 'salutation', null);
	text_row(_("First Name:*"), 'first_name', null, 35, 100);
	text_row(_("Last Name:"), 'last_name', null,  35, 100);
	table_section_title(_("Permanent Address"));
	text_row(_("Line 1:"), 'addr_line1', null, 35, 100);
	text_row(_("Line 2:"), 'addr_line2', null, 35, 100);
	text_row(_("City:"), 'city', null, 35, 100);
	text_row(_("State:"), 'state', null, 35, 100);
 	crm_country_list_row(_("Country:"), 'country', null);
 	currencies_list_row(_("Currency:"), 'curr_code', $_POST['curr_code']);
 	table_section_title(_(" Residential Address"));
	textarea_row(_("Residential Address:"), 'address2', null, 30, 5);
	
	table_section_title(_("Contact Details"));
	text_row(_("Office Phone:"), 'work_phone', null, 35, 40);
	text_row(_("Mobile Phone:*"), 'mobile_phone', null,  35, 100);
	text_row(_("Email:*"), 'email', null, 35, 100);
	//------------------------------------------------------------------------------------
	if ($new_item) {
					
	} else {

	}
	//for custom fields
	custom_field_section('leads',$lead_id,1);
	//end custom fields
	table_section(2);

	table_section_title(_("Lead Details"));
		text_row(_("Client"), 'client', null, 35, 100);
		text_row(_("Title"), 'title', null, 35, 100);
		text_row(_("Website"), 'website', null, 35, 100);
		kv_common_type_row(_('Lead Source') ,'lead_source_id',null, false, false,1); 
		kv_common_type_row(_('Industry List') ,'industry_id',null, false, false,2); 
		kv_common_type_row(_(' Lead Status'), 'lead_status_id', null,  false, false, 3);
		//kv_common_status_row(_('Lead Status'), 'lead_status_id', null,  true, false, 3);
		
	table_section_title(_("Other Details"));
		kv_user_list_row(_('Added By'),'added_by');	
		kv_user_list_row(_('Managed By'),'managed_by');	
		textarea_row(_('Notes'), 'note', null,40, 8);	
		check_row(_("Contacted Today"), 'contacted_today', null, true);
		if(!get_post('contacted_today'))
			date_row(_("Contacted Date"), 'contacted_date');

	//for custom fields
	custom_field_section('leads',$lead_id,2);
	//end custom fields
	end_outer_table(1);

	div_start('controls');
	if (@$_REQUEST['popup']) hidden('popup', 1);
	if ($new_item && !isset($_GET['Updated'])  && !isset($_GET['Added'])) 	{
		submit_center('addupdate', _("Insert New Lead"), true, '', 'default');
	} else {
		submit_center_first('addupdate', _("Update Lead"), '', 	$page_nested ? true : 'default');
		submit_return('select', get_post('lead_id'), 	_("Select this items and return to document entry."));
		submit('clone', _("Clone This Lead"), true, '', true, ICON_EDIT);
		submit('convert', _("Convert to Customer"), true, '', true, ICON_REPORT);
		submit('convert_opp', _("Convert to Opportunity"), true, '', true, ICON_ALLOC);
		submit('delete', _("Delete This Lead"), true, '', true, ICON_REMOVE);
		submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
	}

	div_end();
}

//-------------------------------------------------------------------------------------------- 

start_form(true);
if($lead_id)
	$_POST['lead_id'] = $lead_id;
if (db_has_leads()) {
	start_table(TABLESTYLE_NOBORDER);
	start_row();
    lead_list_cells(_("Select a Lead"). " :", 'lead_id', null,  _("New Lead"), true, check_value('show_inactive'), false, array());
	//$new_item = get_post('lead_id')=='';
	check_cells(_("Show Converted:"), 'show_inactive', null, true);
	end_row();
	end_table();

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

div_start('details');


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

$tabs =  array(
		'settings' => array(_('&General'), $lead_id),
		'tasks' => array(_('&Tasks'), $lead_id),
		'activity' => array(_('&Activity'), $lead_id),
		'attachments' => array(_('Attach&ments'), (user_check_access('SA_SALESPRICE') ? $lead_id : null)),		
		'proposals' => array(_('&Proposals'), (user_check_access('SA_ITEMSSTATVIEW') ? $lead_id : null))	);

tabbed_content_start('tabs', $tabs);

	switch (get_post('_tabs_sel')) {
		default:
		case 'settings':
			lead_settings($lead_id, $new_item); 
			break;
		
		case 'attachments':
			$_GET['type_id'] = $lead_id;	
			$_GET['type']= ST_LEADS;  //leads type
			$activity = new attachments('attachment', $lead_id, 'leads');
			$activity->show();			
			break;
			/*$_GET['type_id'] = $lead_id;
			$_GET['type']= 1;  //leads type
			$_GET['page_level'] = 1;
			include_once($path_to_root."/modules/KvcodesCRM/manage/attachments.php");
			break;*/
		case 'activity':			
			$_GET['type_id'] = $lead_id;	
			$_GET['type']= ST_LEADS;  //leads type
			$activity = new activity('activity', $lead_id, 'leads');
			$activity->show();			
			break;
		case 'tasks':
			$_GET['type_id'] = $lead_id;
			$_GET['type']= ST_LEADS;  //leads type
			$_GET['page_level'] = ST_LEADS;
			include_once($path_to_root."/modules/KvcodesCRM/tasks/index.php");
			break;
		case 'proposals':
			$_GET['customer_id'] = $lead_id;			
			$_GET['type'] = ST_SALESPROPOSAL;	
			include_once($path_to_root."/modules/KvcodesCRM/inquires/proposal_estimate_inquiry.php");		
			break;
	};

br();
tabbed_content_end();

div_end();

end_form();

//------------------------------------------------------------------------------------
echo "<script type='text/javascript'> kvcodes_crm_nicEditor();  </script> \n";
end_page();
?>