<?php
/****************************************
/*  Author  : Kvvaradha
/*  Module  : Kvcodes CRM
/*  E-mail  : admin@kvcodes.com
/*  Version : 1.0
/*  Http    : www.kvcodes.com
*****************************************/
$page_security = 'CRM_SUPPLIERS';
$path_to_root = "../../..";
include($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" );
$js = "";
if ($SysPrefs->use_popup_windows)
	$js .= get_js_open_window(900, 500);
if (user_use_date_picker())
	$js .= get_js_date_picker();

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

include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/crm_contacts_view.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/attachment.inc");
include_once($path_to_root . "/admin/db/users_db.inc");

check_db_has_tax_groups(_("There are no tax groups defined in the system. At least one tax group is required before proceeding."));

if(isset($_SESSION['wa_current_user']->type) && $_SESSION['wa_current_user']->type != ST_SUPPLIER) {
	$_POST['supplier_id'] = $_SESSION['wa_current_user']->person;
	echo '<style> #delete { display : none; } </style>';	
	$help_context = "Profile";
} elseif (isset($_GET['supplier_id'])) 
{
	$_POST['supplier_id'] = $_GET['supplier_id'];
	$help_context = "Suppliers"; 
}else
	$help_context = "Suppliers" ;

page(_($help_context), false, false, "", $js);
$supplier_id = get_post('supplier_id'); 
//--------------------------------------------------------------------------------------------
function Has_Supplier_Shortname($supp_ref) {
	return GetSingleValue('suppliers', 'COUNT(supplier_id)', ['supp_ref' => $supp_ref]);
}
function supplier_settings(&$supplier_id)
{
	global $page_nested;
	
	start_outer_table(TABLESTYLE2);

	table_section(1);

	if ($supplier_id) 
	{
		//SupplierID exists - either passed when calling the form or from the form itself
		$myrow = get_supplier($_POST['supplier_id']);
		$_POST['NewSuppID']=$myrow["suppno"];
		$_POST['supp_name'] = $myrow["supp_name"];
		$_POST['supp_ref'] = $myrow["supp_ref"];
		$_POST['address']  = $myrow["address"];
		$_POST['supp_address']  = $myrow["supp_address"];

		$_POST['gst_no']  = $myrow["gst_no"];
		$_POST['website']  = $myrow["website"];
		$_POST['supp_account_no']  = $myrow["supp_account_no"];
		$_POST['bank_account']  = $myrow["bank_account"];
		$_POST['dimension_id']  = $myrow["dimension_id"];
		$_POST['dimension2_id']  = $myrow["dimension2_id"];
		$_POST['curr_code']  = $myrow["curr_code"];
		$_POST['payment_terms']  = $myrow["payment_terms"];
		$_POST['credit_limit']  = price_format($myrow["credit_limit"]);
		$_POST['tax_group_id'] = $myrow["tax_group_id"];
		$_POST['tax_included'] = $myrow["tax_included"];
		$_POST['payable_account']  = $myrow["payable_account"];
		$_POST['purchase_account']  = $myrow["purchase_account"];
		$_POST['payment_discount_account'] = $myrow["payment_discount_account"];
		$_POST['notes']  = $myrow["notes"];
	 	$_POST['inactive'] = $myrow["inactive"];
	 	$_POST['register_type']  = $myrow["idregister"];
	} 
	else 
	{
		$_POST['supp_name'] = $_POST['supp_ref'] = $_POST['address'] = $_POST['supp_address'] = 
			$_POST['tax_group_id'] = $_POST['website'] = $_POST['supp_account_no'] = $_POST['notes'] = '';
		$_POST['dimension_id'] = 0;
		$_POST['dimension2_id'] = 0;
		$_POST['tax_included'] = 0;
		$_POST['sales_type'] = -1;
		$_POST['gst_no'] = $_POST['bank_account'] = '';
		$_POST['payment_terms']  = '';
		$_POST['credit_limit'] = price_format(0);

		$company_record = get_company_prefs();
		$_POST['curr_code']  = $company_record["curr_default"];
		$_POST['payable_account'] = $company_record["creditors_act"];
		$_POST['purchase_account'] = ''; // default/item's cogs account
		$_POST['payment_discount_account'] = $company_record['pyt_discount_act'];
		$_POST['register_type']  = null;
	}

	table_section_title(_("Basic Data"));
	 show_register(_("Registration Type:"), 'register_type',null, false);
    if(isset($_POST['NewSuppID']))
    	text_row_readonly(_("Supplier ID:"), 'NewSuppID',$_POST['NewSuppID'], 21, 20,null,"readonly","");
	else
		text_row_readonly(_("Supplier ID:"), 'NewSuppID', get_supp_idauto(), 21, 20,null,"readonly","");
	text_row(_("Supplier Name:"), 'supp_name', null, 42, 40);
	text_row(_("Supplier Short Name:"), 'supp_ref', null, 30, 30);

	if(isset($_SESSION['wa_current_user']->type) && $_SESSION['wa_current_user']->type == ST_SUPPLIER){
		$_POST['password'] = "";
		password_row(_("New Password:"), 'password', $_POST['password']);		
	}


	text_row(_("GSTNo:"), 'gst_no', null, 42, 40);
	link_row(_("Website:"), 'website', null, 35, 55);
	if ($supplier_id && !is_new_supplier($supplier_id) && (key_in_foreign_table($_POST['supplier_id'], 'supp_trans', 'supplier_id') ||
		key_in_foreign_table($_POST['supplier_id'], 'purch_orders', 'supplier_id'))) 
	{
		label_row(_("Supplier's Currency:"), $_POST['curr_code']);
		hidden('curr_code', $_POST['curr_code']);
	} 
	else 
	{
		currencies_list_row(_("Supplier's Currency:"), 'curr_code', null);
	}
	tax_groups_list_row(_("Tax Group:"), 'tax_group_id', null);
	text_row(_("Our Customer No:"), 'supp_account_no', null, 42, 40);

	table_section_title(_("Purchasing"));
	text_row(_("Bank Name/Account:"), 'bank_account', null, 42, 40);
	amount_row(_("Credit Limit:"), 'credit_limit', null);
	payment_terms_list_row(_("Payment Terms:"), 'payment_terms', null);
	//
	// tax_included option from supplier record is used directly in update_average_cost() function,
	// therefore we can't edit the option after any transaction was done for the supplier.
	//
	if (is_new_supplier($supplier_id))
		check_row(_("Prices contain tax included:"), 'tax_included');
	else {
		hidden('tax_included');
		label_row(_("Prices contain tax included:"), $_POST['tax_included'] ? _('Yes') : _('No'));
		if($myrow['user_id'] == 0)
			kv_unassigned_staffs_row(_("Select User Access:"), 'user_id',null,"No user selected");
	}

	//for custom fields
	custom_field_section('supplier',$supplier_id,1);
	//end custom fields

	if (!$supplier_id) table_section(2);

	table_section_title(_("Accounts"));
	gl_all_accounts_list_row(_("Accounts Payable Account:"), 'payable_account', $_POST['payable_account']);
	gl_all_accounts_list_row(_("Purchase Account:"), 'purchase_account', $_POST['purchase_account'],
		false, false, _("Use Item Inventory/COGS Account"));
	gl_all_accounts_list_row(_("Purchase Discount Account:"), 'payment_discount_account', $_POST['payment_discount_account']);
	if (!$supplier_id) {
		table_section_title(_("Contact Data"));
		text_row(_("Contact Person:"), 'contact', null, 42, 40);
		text_row(_("Phone Number:"), 'phone', null, 32, 30);
		text_row(_("Secondary Phone Number:"), 'phone2', null, 32, 30);
		table_section_title(_("Contact Data"));
		text_row(_("Fax Number:"), 'fax', null, 32, 30);
		email_row(_("E-mail:"), 'email', null, 35, 55);
		password_row(_('Password'),'password',null);	
		languages_list_row(_("Document Language:"), 'rep_lang', null, _('System default'));
		hidden('SupplierRole', GetSingleValue('kv_crm_option', 'option_value', array('option_name' => 'supplier_role')));
	}
	else
		table_section(2);
	$dim = get_company_pref('use_dimension');
	if ($dim >= 1)
	{
		table_section_title(_("Dimension"));
		dimensions_list_row(_("Dimension")." 1:", 'dimension_id', null, true, " ", false, 1);
		if ($dim > 1)
			dimensions_list_row(_("Dimension")." 2:", 'dimension2_id', null, true, " ", false, 2);
	}
	if ($dim < 1)
		hidden('dimension_id', 0);
	if ($dim < 2)
		hidden('dimension2_id', 0);
	if (!$supplier_id)	
		table_section(2);

	table_section_title(_("Addresses"));
	textarea_row(_("Mailing Address:"), 'address', null, 35, 5);
	textarea_row(_("Physical Address:"), 'supp_address', null, 35, 5);

	table_section_title(_("General"));
	textarea_row(_("General Notes:"), 'notes', null, 35, 5);
	if ($supplier_id)
		record_status_list_row(_("Supplier status:"), 'inactive');
	//for custom fields
	custom_field_section('supplier',$supplier_id,2);
	//end custom fields
	end_outer_table(1);

	div_start('controls');
	if (@$_REQUEST['popup']) hidden('popup', 1);
	if ($supplier_id) 
	{
		submit_center_first('submit', _("Update Supplier"), 
		  _('Update supplier data'), $page_nested ? true : 'default');
		submit_return('select', get_post('supplier_id'), _("Select this supplier and return to document entry."));
		submit_center_last('delete', _("Delete Supplier"), 
		  _('Delete supplier data if have been never used'), true);
	}
	else 
	{
		submit_center('submit', _("Add New Supplier Details"), true, '', 'default');
	}
	div_end();
}

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

	//initialise no input errors assumed initially before we test
	$input_error = 0;

	/* actions to take once the user has clicked the submit button
	ie the page has called itself with some user input */

	//first off validate inputs sensible
	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['supp_ref'], 'users', 'user_id') || key_in_foreign_table($_POST['supp_ref'], 'suppliers', 'supp_ref')){
		display_error(_("Shor Name is already used."));
		set_focus('cust_ref');
		return false;
	}

	if (strlen($_POST['supp_name']) == 0 || $_POST['supp_name'] == "") {
		$input_error = 1;
		display_error(_("The supplier name must be entered."));
		set_focus('supp_name');
	}

	if (strlen($_POST['supp_ref']) == 0 || $_POST['supp_ref'] == "") {
		$input_error = 1;
		display_error(_("The supplier short name must be entered."));
		set_focus('supp_ref');
	}
	if (isset($selected_id) && !$selected_id && Has_Supplier_Shortname($_POST['supp_ref'])) 
	{
		$input_error = 1;
		display_error(_("The customer short name already exists."));
		set_focus('supp_ref');
	} 

	if ($input_error !=1 ){

		begin_transaction();
		if ($supplier_id) 	{

			Update('suppliers',array('supplier_id'=>$_POST['supplier_id']),array("supp_name"=>$_POST['supp_name'],"supp_ref"=>$_POST['supp_ref'],"address"=>$_POST['address'],"supp_address"=>$_POST['supp_address'],"gst_no"=>$_POST['gst_no'],"dimension_id"=>$_POST['dimension_id'],"dimension2_id"=>$_POST['dimension2_id'],"website"=>$_POST['website'],"payment_terms"=>$_POST['payment_terms'],"supp_account_no"=>$_POST['supp_account_no'],"bank_account"=>$_POST['bank_account'],"credit_limit"=>input_num('credit_limit'),"payable_account"=>$_POST['payable_account'],"notes"=>$_POST['notes'],"purchase_account"=>$_POST['purchase_account'],"tax_group_id"=>$_POST['tax_group_id'],'curr_code' => $_POST['curr_code'], "tax_included"=>check_value('tax_included'),"idregister"=>$_POST['register_type']));

			// update_supplier($_POST['supplier_id'], $_POST['supp_name'], $_POST['supp_ref'], $_POST['address'],
			// 	$_POST['supp_address'], $_POST['gst_no'],
			// 	$_POST['website'], $_POST['supp_account_no'], $_POST['bank_account'], 
			// 	input_num('credit_limit', 0), $_POST['dimension_id'], $_POST['dimension2_id'], $_POST['curr_code'],
			// 	$_POST['payment_terms'], $_POST['payable_account'], $_POST['purchase_account'], $_POST['payment_discount_account'],
			// 	$_POST['notes'], $_POST['tax_group_id'], get_post('tax_included', 0));
			
			custom_field_update('supplier',$_POST['supplier_id']);
			update_record_status($_POST['supplier_id'], $_POST['inactive'],
				'suppliers', 'supplier_id');

			if(isset($_POST['user_id']))
				Update('suppliers', array('supplier_id' => $_POST['supplier_id']), array('user_id' => $_POST['user_id']));

			if(isset($_POST['password']) && strlen($_POST['password']) > 0 ){
				update_user_password($_SESSION["wa_current_user"]->user, 	$_SESSION["wa_current_user"]->username,	md5($_POST['password']));
				display_notification(_("Your password has been updated."));
			}
		
			$Ajax->activate('supplier_id'); // in case of status change
			display_notification(_("Supplier has been updated."));
		} 	else 	{
			$supplier_id = $_POST['supplier_id'] = Insert('suppliers',array("supp_name"=>$_POST['supp_name'],"supp_ref"=>$_POST['supp_ref'],"address"=>$_POST['address'],"supp_address"=>$_POST['supp_address'],"gst_no"=>$_POST['gst_no'],"dimension_id"=>$_POST['dimension_id'],"dimension2_id"=>$_POST['dimension2_id'],"website"=>$_POST['website'],"payment_terms"=>$_POST['payment_terms'],"supp_account_no"=>$_POST['supp_account_no'],"bank_account"=>$_POST['bank_account'],"credit_limit"=>input_num('credit_limit'),"payable_account"=>$_POST['payable_account'],"notes"=>$_POST['notes'],"purchase_account"=>$_POST['purchase_account'],"tax_group_id"=>$_POST['tax_group_id'], 'curr_code' => $_POST['curr_code'],"tax_included"=>check_value('tax_included'),"idregister"=>$_POST['register_type']));
			// add_supplier($_POST['supp_name'], $_POST['supp_ref'], $_POST['address'], $_POST['supp_address'],
			// 	$_POST['gst_no'], $_POST['website'], $_POST['supp_account_no'], $_POST['bank_account'], 
			// 	input_num('credit_limit',0), $_POST['dimension_id'], $_POST['dimension2_id'],
			// 	$_POST['curr_code'], $_POST['payment_terms'], $_POST['payable_account'], $_POST['purchase_account'],
			// 	$_POST['payment_discount_account'], $_POST['notes'], $_POST['tax_group_id'], check_value('tax_included'));

			// $supplier_id = $_POST['supplier_id'] = db_insert_id();
			custom_field_update('supplier',$_POST['supplier_id']);

			$user_id = Insert('users', array('user_id' => $_POST['supp_ref'], 'real_name' => $_POST['supp_name'], 'role_id' => $_POST['SupplierRole'], 'password' => md5($_POST['password']), 'phone' => $_POST['phone'], 'email' => $_POST['email'], 'startup_tab' => 'crm'));

			add_crm_person($_POST['supp_ref'], $_POST['contact'], '', $_POST['address'], 
				$_POST['phone'], $_POST['phone2'], $_POST['fax'], $_POST['email'], 
				$_POST['rep_lang'], '',null,null,$user_id);

			add_crm_contact('supplier', 'general', $supplier_id, db_insert_id());


			$to =  array('name' => $_POST['contact'], 'email' => $_POST['email']);
			$contact = array('name' => $_POST['contact'], 'name2' => '', 'phone' => $_POST['phone'], 'email' => $_POST['email'], 'user_name' => $_POST['supp_ref'], 'password' => md5('password'));
			$template = array('slug' => 'welcome-aboard',  'details' => $contact );
			kv_mail($to, '', '', "html", array(), null, false, $template);

			display_notification(_("A new supplier has been added."));
			$Ajax->activate('_page_body');
		}
		commit_transaction();
	}

} 
elseif (isset($_POST['delete']) && $_POST['delete'] != "") {
	//the link to delete a selected record was clicked instead of the submit button

	$cancel_delete = 0;

	// PREVENT DELETES IF DEPENDENT RECORDS IN 'supp_trans' , purch_orders

	if (key_in_foreign_table($_POST['supplier_id'], 'supp_trans', 'supplier_id'))	{
		$cancel_delete = 1;
		display_error(_("Cannot delete this supplier because there are transactions that refer to this supplier."));

	} 	else {
		if (key_in_foreign_table($_POST['supplier_id'], 'purch_orders', 'supplier_id'))	{
			$cancel_delete = 1;
			display_error(_("Cannot delete the supplier record because purchase orders have been created against this supplier."));
		}

	}
	if ($cancel_delete == 0) {
		delete_supplier($_POST['supplier_id']);

		unset($_SESSION['supplier_id']);
		$supplier_id = '';
		$Ajax->activate('_page_body');
		display_notification("#" . $_POST['supplier_id'] . " " . _("Supplier has been deleted."));
	} //end if Delete supplier
}

start_form();

if(isset($_SESSION['wa_current_user']->type) && $_SESSION['wa_current_user']->type == ST_SUPPLIER) {
	$_POST['supplier_id'] = $supplier_id = $_SESSION['wa_current_user']->person;
} elseif (db_has_suppliers()) {
	start_table(false, "", 3);
	start_row();
	supplier_list_cells(_("Select a supplier: "), 'supplier_id', null,  _('New supplier'), true, check_value('show_inactive'));
	check_cells(_("Show inactive:"), 'show_inactive', null, true);
	end_row();
	end_table();
	if (get_post('_show_inactive_update')) {
		$Ajax->activate('supplier_id');
		set_focus('supplier_id');
	}
} else {
	hidden('supplier_id', get_post('supplier_id'));
}
$result = db_query("SHOW COLUMNS FROM `".TB_PREF."suppliers` LIKE 'user_id'", "Can't get column");
$exists = (db_num_rows($result))?TRUE:FALSE;

if(!$exists){
	$result = db_query("ALTER TABLE `".TB_PREF."suppliers` ADD `user_id` INT(11) NOT NULL DEFAULT '0' AFTER `supplier_id`", "Can't insert column");
}


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

tabbed_content_start('tabs', array(
		'settings' => array(_('&General settings'), $supplier_id),
		'contacts' => array(_('&Contacts'), $supplier_id),
		'tasks' => array(_('Tas&ks'), $supplier_id),
		'attachments' => array(_('&Attachments'), $supplier_id),
		'transactions' => array(_('&Transactions'),  $supplier_id ),
		'orders' => array(_('Purchase &Orders'), $supplier_id ),
	));
	
	switch (get_post('_tabs_sel')) {
		default:
		case 'settings':
			supplier_settings($supplier_id); 
			break;
		case 'contacts':
			$contacts = new crm_contacts('contacts', $supplier_id, 'supplier');
			$contacts->show();
			break;
		case 'transactions':
			$_GET['supplier_id'] = $supplier_id;
			include_once($path_to_root."/modules/KvcodesCRM/inquires/supplier_inquiry.php");
			break;
		case 'orders':
			$_GET['supplier_id'] = $supplier_id;
			include_once($path_to_root."/modules/KvcodesCRM/inquires/po_search_completed.php");
			break;
		case 'tasks' :
			$_GET['type_id'] = $supplier_id;
			$_GET['type']= ST_SUPPLIER;  //Supplier type
			$_GET['page_level'] = 1;
			include_once($path_to_root."/modules/KvcodesCRM/tasks/index.php");
			break;
		case 'attachments':
			/*$_GET['type_id'] = $supplier_id;
			$_GET['type']= 5;  //Customers type
			$_GET['page_level'] = 1;
			include_once($path_to_root."/modules/KvcodesCRM/manage/attachments.php"); */
			$_GET['type_id'] = $supplier_id;	
			$_GET['type']= ST_SUPPLIER;  //Supplier type
			$attachments = new attachments('attachment', $supplier_id, 'Supplier');
			$attachments->show();
			break;
	};
br();
tabbed_content_end();
end_form();

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