<?php

$page_security = 'CRM_CUSTOMERS';
$path_to_root = "../../..";

include_once($path_to_root . "/includes/db_pager.inc");
include_once($path_to_root . "/includes/session.inc");
add_access_extensions();
$js = "";
if ($SysPrefs->use_popup_windows)
	$js .= get_js_open_window(900, 500);
if (user_use_date_picker())
	$js .= get_js_date_picker();
	
page(_($help_context = "Lead To Opportunity & Customers"), false, false, "", $js); 

include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/banking.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/ui/contacts_view.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/crm.inc" );

$selected_id = get_post('customer_id','');
//--------------------------------------------------------------------------------------------
function Has_Customer_Shortname($cust_ref) {
	return GetSingleValue('debtors_master', 'COUNT(debtor_no)', ['debtor_ref' => $cust_ref]);
}
function gst_validate($gstNo, $statecode,$debtor)
{

    if($debtor=="Registered") {
        if (strlen($gstNo) == 15) {
            if ($statecode == substr($gstNo, 0, 2)) {

                if (!preg_match("/^([0-9]){2}([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}([a-zA-Z0-9]){1}([a-zA-Z]){1}([a-zA-Z0-9]){1}?$/", $gstNo)) {
                    return false;
                } else {
                    return true;
                }
            } else {
                return false;
            }
        } else
            return false;
    }
    else
        return true;

}
function can_process()
{
	if (strlen($_POST['CustName']) == 0) 
	{
		display_error(_("The customer name cannot be empty."));
		set_focus('CustName');
		return false;
	} 

	if (strlen($_POST['cust_ref']) == 0) 
	{
		display_error(_("The customer short name cannot be empty."));
		set_focus('cust_ref');
		return false;
	} 
	
	if (!check_num('credit_limit', 0))
	{
		display_error(_("The credit limit must be numeric and not less than zero."));
		set_focus('credit_limit');
		return false;		
	} 
	if(isset($_POST['password']) && strlen($_POST['password'])<=3){
		display_error(_("The password entered must be at least 4 characters long."));
		set_focus('password');
		return false;		
	}

	if(key_in_foreign_table($_POST['cust_ref'], 'users', 'user_id') || key_in_foreign_table($_POST['cust_ref'], 'debtors_master', 'debtor_ref')){
		display_error(_("Shor Name is already used."));
		set_focus('cust_ref');
		return false;
	}
	if (!check_num('pymt_discount', 0, 100)) 
	{
		display_error(_("The payment discount must be numeric and is expected to be less than 100% and greater than or equal to 0."));
		set_focus('pymt_discount');
		return false;		
	} 
	
	if (!check_num('discount', 0, 100)) 
	{
		display_error(_("The discount percentage must be numeric and is expected to be less than 100% and greater than or equal to 0."));
		set_focus('discount');
		return false;		
	} 
	if (Has_Customer_Shortname($_POST['cust_ref'])) 
	{
		display_error(_("The customer short name already exists."));
		set_focus('cust_ref');
		return false;
	} 
	if (gst_validate($_POST['tax_id'], $_POST['state_code'], $_POST['debtors_category']) == false)
    {
        display_error("Invalid GST No");
        set_focus('tax_id');
        return false;
    }

    if (gst_validate($_POST['ship_gst'], $_POST['ship_state_code'], $_POST['debtors_category']) == false)
    {
        display_error("Invalid ship GST No ");
        set_focus('ship_gst');
        return false;
    }

    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 (strlen($_POST['probability']) == 0) 
	{
		display_error(_("The probability cannot be empty."));
		set_focus('probability');
		return false;
	} 
	return true;
}

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

function handle_submit(&$selected_id)
{
	global $path_to_root, $Ajax, $SysPrefs;

	if (!can_process())
		return;
		
	
		begin_transaction();
		// add_customer($_POST['CustName'], $_POST['cust_ref'], $_POST['address'],
		// 	$_POST['tax_id'], $_POST['curr_code'], $_POST['dimension_id'], $_POST['dimension2_id'],
		// 	$_POST['credit_status'], $_POST['payment_terms'], input_num('discount') / 100, input_num('pymt_discount') / 100,
		// 	input_num('credit_limit'), $_POST['sales_type'], $_POST['notes']);

		$selected_id = $_POST['customer_id'] = Insert('debtors_master',array('name'=>$_POST['CustName'],'debtor_ref'=>$_POST['cust_ref'],'address'=>$_POST['address'],'tax_id'=>$_POST['tax_id'],'curr_code'=>$_POST['curr_code'],'dimension_id'=>$_POST['dimension_id'],'dimension2_id'=>$_POST['dimension2_id'],'credit_status'=>$_POST['credit_status'],'payment_terms'=>$_POST['payment_terms'],'discount'=>input_num('discount') / 100,'pymt_discount'=>input_num('pymt_discount') / 100,'credit_limit'=>$_POST['credit_limit'],'sales_type'=>$_POST['sales_type'],'notes'=>$_POST['notes'], "debtorscategory"=>$_POST['debtors_category'],"state_code"=>$_POST['state_code'],"ship_state_code"=>$_POST['ship_state_code'],"ship_address"=>$_POST['ship_address'],"ship_gst"=>$_POST['ship_gst'],"ecom"=>check_value('ecom_enabled'),"reverse_charge"=>check_value('reverse_charge_enabled')));


		// $selected_id = $_POST['customer_id'] = db_insert_id();
        
		if (isset($SysPrefs->auto_create_branch) && $SysPrefs->auto_create_branch == 1)
		{
			 $user_id = Insert('users', array('user_id' => $_POST['cust_ref'], 'real_name' => $_POST['CustName'], 'role_id' => $_POST['CustomerRole'], 'password' => md5($_POST['password']), 'phone' => $_POST['phone'], 'email' => $_POST['email'], 'startup_tab' => 'crm'));
        	add_branch($selected_id, $_POST['CustName'], $_POST['cust_ref'],
                $_POST['address'], $_POST['salesman'], $_POST['area'], $_POST['tax_group_id'], '',
                get_company_pref('default_sales_discount_act'), get_company_pref('debtors_act'), get_company_pref('default_prompt_payment_act'),
                $_POST['location'], $_POST['address'], 0, $_POST['ship_via'], $_POST['notes'], $_POST['bank_account']);
                
        	$selected_branch = db_insert_id();
        
			add_crm_person($_POST['cust_ref'], $_POST['CustName'], '', $_POST['address'], $_POST['phone'], $_POST['phone2'], $_POST['fax'], $_POST['email'], '', '',null,null,$user_id);

			$pers_id = db_insert_id();
			add_crm_contact('cust_branch', 'general', $selected_branch, $pers_id);

			add_crm_contact('customer', 'general', $selected_id, $pers_id);
		}		

		
		if ($_POST['email'] != '' && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
			$to =  array('name' => $_POST['CustName'], 'email' => $_POST['email']);
			$contact = array('name' => $_POST['CustName'], 'name2' => '', 'phone' => $_POST['phone'], 'email' => $_POST['email'], 'login_password' => 'password');
			$template = array('slug' => 'new-client-created',  'details' => $contact );
			kv_mail($to, '', '', "html", array(), null, false, $template);
		}

		Update('kv_crm_leads', array('lead_id' => $_POST['lead_id']), array('is_converted' => 1));
		if(isset($_POST['convert_attachments'])){
			Update('kv_crm_attachments', array('type' => 1, 'type_id' => $_POST['lead_id']), array('type' => 5, 'type_id' => $selected_id));
		}
		if(isset($_POST['convert_tasks'])){
			Update('kv_crm_tasks', array('type' => 1, 'type_id' => $_POST['lead_id']), array('type' => 3, 'type_id' => $selected_id));
		}
		if(GetSingleValue('kv_crm_sales_orders','COUNT(*)',array('formType' => 1, 'debtor_no' => $_POST['lead_id']))>0)
			Update('kv_crm_sales_orders', array('formType' => 1, 'debtor_no' => $_POST['lead_id']), array('formType' => 2, 'debtor_no' => $selected_id));

		 Insert('kv_crm_opportunities', array('opportunity_name' => $_POST['opportunity_name'], 'organization_name' => $_POST['organization_name'], 'amount_curr_abrev' => (isset($_POST['amount_curr_abrev']) ? $_POST['amount_curr_abrev'] :  $_POST['curr_code']), 'amount' => input_num('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['customer_id'], 'probability' => $_POST['probability'], 'contact_id' => $pers_id, 	'custome_info' => '', 'description' => $_POST['notes'], 'expected_close_date' => array($_POST['expected_close_date'], 'date'))); 
		/*if(isset($_POST['convert_activities'])){
			Update('kv_crm_activities', array('type' => 1, 'type_id' => $_POST['lead_id']), array('type' => 5, $selected_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 );			
					kv_mail($to, '', '', "html", array(), null, false, $template); 
				}
		commit_transaction();

		display_notification(_("The Selected Lead Has been converted to customer."));

		if (isset($SysPrefs->auto_create_branch) && $SysPrefs->auto_create_branch == 1)
			display_notification(_("A default Branch has been automatically created, please check default Branch values by using link below."));
		
	//	meta_forward('customers.php', "debtor_no=$selected_id");
	
}
//--------------------------------------------------------------------------------------------

if (isset($_POST['submit'])) 
{
	handle_submit($selected_id);
}
if(isset($_GET['lead_id']))
	$_POST['lead_id'] = $_GET['lead_id'];

start_form();
	global $SysPrefs, $path_to_root, $page_nested;
	hidden('CustomerRole', GetSingleValue('kv_crm_option', 'option_value', array('option_name' => 'customer_role')));
	$myrow = GetRow('kv_crm_leads', array('lead_id' => $_POST['lead_id'], 'is_converted' => 0));
	
	if(!$myrow)	{
		$myrow2 = GetRow('kv_crm_leads', array('lead_id' => $_POST['lead_id'], 'is_converted' => 1));
		if(!empty($myrow2)){
			display_warning(_("The Selected Lead was already converted to customer"));
			display_footer_exit();
		}
	}
	$_POST['notes']  = $myrow["note"];			
	$_POST['phone2']	= $myrow["work_phone"];
	$_POST['phone']  = $myrow["mobile_phone"];
	$_POST['email']  = $myrow["email"];		
	$_POST['CustName'] = $myrow["first_name"]. ' '.$myrow["last_name"];
	$_POST['cust_ref'] = $myrow["first_name"];
	$_POST['address'] = $myrow["addr_line1"].' '.$myrow["addr_line2"]. ' '.$myrow["city"].' '. GetSingleValue('kv_crm_country','local_name',array('id'=> $myrow["country"]));
	$_POST['tax_id']  = '';
	$_POST['dimension_id'] = 0;
	$_POST['dimension2_id'] = 0;
	$_POST['sales_type'] = -1;
	$_POST['type'] = $myrow["lead_status_id"];	
	$_POST['lead_source'] = $myrow["lead_source_id"];	
	$_POST['assign_to'] = $myrow["managed_by"];	
	$_POST['curr_code']  = $myrow["curr_code"];
	$_POST['credit_status']  = -1;
	$_POST['payment_terms']  = '';
	$_POST['discount']  = $_POST['pymt_discount'] = percent_format(0);
	$_POST['credit_limit']	= price_format($SysPrefs->default_credit_limit());
	$_POST['lead_source'] = $myrow['lead_source_id'];
	hidden('lead_id', $_POST['lead_id']);
	start_outer_table(TABLESTYLE2);
	table_section(1);
	table_section_title(_("Name and Address"));
	show_debtor_category(_("Category:"), 'debtors_category',null, false);
    show_country(_("Country:"), 'countryid', 99, false);
    show_state(_("State:"), 'state_code', null, false);
    show_state(_("Ship State:"), 'ship_state_code', null, false); 
	text_row(_("Customer Name:"), 'CustName', $_POST['CustName'], 40, 80);
	text_row(_("Customer Short Name:"), 'cust_ref', null, 30, 30);
	textarea_row(_("Address:"), 'address', $_POST['address'], 35, 5);
	textarea_row(_("Ship Address:"), 'ship_address', null, 35, 5);

    check_row(_("Ecommerce Enabled:"), 'ecom_enabled');
    check_row(_("Reverse Charge Enabled:"), 'reverse_charge_enabled');
	text_row(_("Bill GSTN:"), 'tax_id', $_POST['tax_id'], 40, 40);
    text_row(_("Ship GSTN:"), 'ship_gst', null, 40, 40);

	if (!$selected_id || is_new_customer($selected_id) || (!key_in_foreign_table($selected_id, 'debtor_trans', 'debtor_no') &&
		!key_in_foreign_table($selected_id, 'sales_orders', 'debtor_no'))) {
		currencies_list_row(_("Customer's Currency:"), 'curr_code', $_POST['curr_code']);
	} 
	else {
		label_row(_("Customer's Currency:"), $_POST['curr_code']);
		hidden('curr_code', $_POST['curr_code']);				
		hidden('amount_curr_abrev', $_POST['curr_code']);				
	}
	sales_types_list_row(_("Sales Type/Price List:"), 'sales_type', $_POST['sales_type']);

	if($selected_id)
		record_status_list_row(_("Customer status:"), 'inactive');
	elseif (isset($SysPrefs->auto_create_branch) && $SysPrefs->auto_create_branch == 1)	{
		table_section_title(_("Branch & Account"));
		text_row(_("Phone:"), 'phone', null, 32, 30);
		text_row(_("Secondary Phone Number:"), 'phone2', null, 32, 30);
		text_row(_("Fax Number:"), 'fax', null, 32, 30);
		email_row(_("E-mail:"), 'email', null, 35, 55);
		password_row(_('Password'),'password',null);
		text_row(_("Bank Account Number:"), 'bank_account', null, 30, 60);
		sales_persons_list_row( _("Sales Person:"), 'salesman', null);
	}
	table_section(2);

	table_section_title(_("Sales"));

	percent_row(_("Discount Percent:"), 'discount', $_POST['discount'], true);
	percent_row(_("Prompt Payment Discount Percent:"), 'pymt_discount', $_POST['pymt_discount'], true);
	amount_row(_("Credit Limit:"), 'credit_limit', $_POST['credit_limit']);

	payment_terms_list_row(_("Payment Terms:"), 'payment_terms', $_POST['payment_terms']);
	credit_status_list_row(_("Credit Status:"), 'credit_status', $_POST['credit_status']); 
	$dim = get_company_pref('use_dimension');
	if ($dim >= 1)
		dimensions_list_row(_("Dimension")." 1:", 'dimension_id', $_POST['dimension_id'], true, " ", false, 1);
	if ($dim > 1)
		dimensions_list_row(_("Dimension")." 2:", 'dimension2_id', $_POST['dimension2_id'], true, " ", false, 2);
	if ($dim < 1)
		hidden('dimension_id', 0);
	if ($dim < 2)
		hidden('dimension2_id', 0);

	if ($selected_id)  {
		start_row();
		echo '<td class="label">'._('Customer branches').':</td>';
	  	hyperlink_params_td($path_to_root . "/sales/manage/customer_branches.php",
			'<b>'. ($page_nested ?  _("Select or &Add") : _("&Add or Edit ")).'</b>', 
			"debtor_no=".$selected_id.($page_nested ? '&popup=1':''));
		end_row();
	}

	textarea_row(_("General Notes:"), 'notes', null, 35, 5);
	if (!$selected_id && isset($SysPrefs->auto_create_branch) && $SysPrefs->auto_create_branch == 1){
		table_section_title(_("Branch"));
		locations_list_row(_("Default Inventory Location:"), 'location');
		shippers_list_row(_("Default Shipping Company:"), 'ship_via');
		sales_areas_list_row( _("Sales Area:"), 'area', null);
		tax_groups_list_row(_("Tax Group:"), 'tax_group_id', null);
	}
	table_section_title(_("Get Leads Data"));
	check_row(_("Attachments to Customer"), 'convert_attachments', 1);
	check_row(_("Tasks to Customer"), 'convert_tasks', null);	
	//check_row(_("Activity to Customer"), 'convert_activities', null);
	table_section(3);
	table_section_title(_("Opportunity Details"));

		text_row('Opportunities Name','opportunity_name', null, 35,30);						
		text_row('Organization Name','organization_name', null, 35,30);	
		  
		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);		
		text_row('Probability','probability', null, '', '');
	end_outer_table(1);

	div_start('controls');
	if (@$_REQUEST['popup']) hidden('popup', 1);
	if (!$selected_id)
	{
		submit_center('submit', _("Convert to Customer"), true, '', 'default');
	} 	
	div_end();


end_form();
end_page();

