<?php  
$path_to_root="../../..";
$page_security = 'SA_OPEN';
	include_once($path_to_root . "/includes/db_pager.inc");

include_once($path_to_root . "/includes/session.inc");
page(_($help_context = "Contacts Inquires"));
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/crm.inc" );
include_once($path_to_root . "/modules/KvcodesCRM/includes/crm_contacts_view.inc");
simple_page_mode(true, 'update_contact_type');

function user_types($name, $selected_id=null,  $submit_on_change=false, $all_option=false){
    // $status = array(ST_CUSTOMER => _("Customer"), ST_SUPPLIER => _("Supplier"),ST_CUSTOMER_BRANCH =>_('Branch') ); 

    $status = array(ST_CUSTOMER => _("Customer"), ST_SUPPLIER => _("Supplier"),'Others'=>'Others');

    return array_selector($name, $selected_id, $status, 
        array( 
            'select_submit'=> $submit_on_change,
            'async' => false,
            'spec_option'=> ($all_option ? $all_option : false ),
            'disabled' => false ) ); // FIX?
}

function user_types_cells($label, $name, $selected_id=null,  $submit_on_change=false, $all_option=false){
    if ($label != null)
        echo "<td>$label</td>\n";
    echo "<td>";
    echo user_types($name, $selected_id, $submit_on_change, $all_option);
    echo "</td>\n";
}

function can_process()
{
	if (strlen($_POST['name']) == 0) {
			display_error(_("The contact name cannot be empty."));
			set_focus('name');
			return false;
		}
		if (strlen($_POST['ref']) == 0) {
			display_error(_("Contact reference cannot be empty."));
			set_focus('ref');
			return false;
		}
		if (!$_POST['selected_id']&& isset($_POST['username']) && strlen($_POST['username']) <= 3 ) {
			display_error(_("You have to input username for the contact login."));
			set_focus('username');
			return false;
		}
		if(!$_POST['selected_id'] && $_POST['password'] ===''){
			display_error( _("The password cannot be empty!"));
			set_focus('password');
	    	return false;
		}elseif (!$_POST['selected_id'] && ($_POST['password'] != "")){
	    	if (strlen($_POST['password']) < 4)   	{
	    		display_error( _("The password entered must be at least 4 characters long."));
				set_focus('password');
	    		return false;
	    	}

	    	if (strstr($_POST['password'], $_POST['user_id']) != false) 	{
	    		display_error( _("The password cannot contain the user login."));
				set_focus('password');
	    		return false;
	    	}
		}
	return true;
}
if($Mode=='UPDATE_ITEM'  && can_process()){
	$update_contact = array("ref"=> $_POST['ref'],"name"=> $_POST['name'],"name2"=> $_POST['name2'],"address"=> $_POST['address'],"phone"=> $_POST['phone'],"phone2"=> $_POST['phone2'],"fax"=> $_POST['fax'],"email"=> $_POST['email'],"lang"=> $_POST['lang'],"notes"=> $_POST['notes']);

	if(isset($_POST['user_id']) && $_POST['user_id'] > 0 )
		$update_contact['user_id'] = $_POST['user_id'];
	elseif($_POST['username'] != '' && $_POST['password'] != '' ){
		 $_POST['CustomerRole'] = GetSingleValue('kv_crm_option', 'option_value', array('option_name' => 'customer_role'));
		$user_id = Insert('users', array('user_id' => $_POST['username'], 'real_name' => $_POST['name'], 'role_id' => $_POST['CustomerRole'], 'password' => md5($_POST['password']), 'phone' => $_POST['phone'], 'email' => $_POST['email'], 'startup_tab' => 'crm'));
		$update_contact['user_id'] = $user_id;
		if(check_value('send_welcome_email')){
			$to =  array('name' => $_POST['name'], 'email' => $_POST['email']);
			$contact = array('name' => $_POST['name'], 'name2' => '', 'phone' => $_POST['phone'], 'email' => $_POST['email'], 'user_name' => $_POST['username'], 'password' => md5('password'));
			//display_error(json_encode($contact));
			$template = array('slug' => 'new-client-created',  'details' => $contact );
			kv_mail($to, '', '', "html", array(), null, false, $template);
		}
	}

	Update('crm_persons',array('id'=>$_POST['selected_id']),$update_contact);


	 $Mode = 'RESET';

	 display_notification('Contact Updated Sucessfully');
}

if($Mode =='RESET'){
	$selected_id=-1;
	$_POST['selected_id']=-1;
}

start_form();

if(list_updated('user_type')){
	$selected_id =-1;
	$_POST['search_text']='';
	$_POST['master_id']='0';
	$Ajax->activate('user_type_list');

}
if(isset($_POST['search'])){
	$Ajax->activate('user_type_list');
}

function delete_link($row){
  	return button('Delete'.$row["id"], _("Delete"), _("Delete"), ICON_DELETE);
}
function edit_link($row){
	global $path_to_root; 
  	return ($row['type'] == 'Undefined' ? '<a target="_blank" href="'.$path_to_root.'/modules/KvcodesCRM/inquires/allocate_contact.php?entity_id='.$row["id"].'" onclick="javascript:openWindow(this.href,this.target); return false;"><img src="'.$path_to_root.'/themes/Default/images/edit.gif" style="vertical-align:middle;width:12px;height:12px;border:0;" title="Edit"></a>' : button('Edit'.$row["id"], _("Edit"), _("Edit"), ICON_EDIT));
}
function display_rows(){
if(isset($_POST['master_id']) && $_POST['master_id'] >0){
	if(isset($_POST['branch_code']) && $_POST['branch_code']>0){
		$type ='cust_branch';
		$contacts = new crm_contacts('contacts', $_POST['branch_code'], $type);
		$contacts->show();
	}
	elseif($_POST['user_type']  ==ST_CUSTOMER){
		$type ='customer';
		$contacts = new crm_contacts('contacts', $_POST['master_id'], $type);
		$contacts->show();
	}
	elseif($_POST['user_type']  ==ST_SUPPLIER){
		$type ='supplier';
		$contacts = new crm_contacts('contacts', $_POST['master_id'], $type);
		$contacts->show();
	}
}else{
	if(isset($_POST['user_type']) && $_POST['user_type'] ==='Others'){

		$sql = "SELECT pr.id As id , 'Undefined' as type, pr.ref,users.user_id AS username,concat(pr.name,'',pr.name2) AS full_name,pr.phone,pr.phone2,pr.fax,pr.email from crm_persons AS pr LEFT JOIN ".TB_PREF."users AS users ON pr.user_id = users.id WHERE pr.id NOT in(SELECT pr.id FROM `crm_contacts` AS con, crm_persons as pr  WHERE con.person_id = pr.id GROUP BY con.person_id)";
	}else{
		//display_error('chekc');
		$sql = "SELECT crm_persons.id As id ,crm_contacts.type as type, crm_persons.ref,users.user_id AS username,concat(crm_persons.name,'',crm_persons.name2) AS full_name,crm_persons.phone,crm_persons.phone2,crm_persons.fax,crm_persons.email FROM ".TB_PREF."crm_persons AS crm_persons LEFT JOIN ".TB_PREF."crm_contacts AS crm_contacts ON crm_persons.id = crm_contacts.person_id LEFT JOIN ".TB_PREF."users AS users ON crm_persons.user_id = users.id ";

		if(!isset($_POST['master_id']) ||  $_POST['master_id'] ==0){
			if($_POST['user_type']  ==ST_CUSTOMER)
				$sql .=" WHERE (crm_contacts.type ='customer' OR crm_contacts.type ='cust_branch')  ";
			elseif($_POST['user_type']  ==ST_SUPPLIER)	
				$sql .=" WHERE crm_contacts.type ='supplier' ";
			else
				$sql .=' WHERE 1 ';
		}else{
			$sql .=' WHERE 1 ';
		}
	}
	if(isset($_POST['search_text']) && strlen($_POST['search_text']) >0){
		$sql.=" AND (crm_persons.name LIKE '%".trim($_POST['search_text'])."%' OR crm_persons.name2 LIKE '%".trim($_POST['search_text'])."%'  OR crm_persons.email LIKE '%".trim($_POST['search_text'])."%'  OR crm_persons.phone LIKE '%".trim($_POST['search_text'])."%'  OR crm_persons.phone2 LIKE '%".trim($_POST['search_text'])."%')";
	}
	//display_error($sql);
	$cols = array(
			_("Id") => 'skip',
			_("Contact Type") => array('name'=>'type'),
			_("Reference") => array('name'=>'ref'),
			_("Username") => array('username'=>'username'),	    	    
			_("Full Name") => array('name'=>'full_name'),	   
			_("Phone") => array('name'=>'phone'), 	 
			_("Sec Phone") => array('name'=>'phone2'), 	 
			_("Fax") => array('name'=>'fax'),   
			_("email") => array('name'=>'email'),  
		    	array('insert'=>true, 'fun'=>'edit_link'),
		    	array('insert'=>true, 'fun'=>'delete_link')
		    );	
	

	if (isset($_POST['user_type']) && $_POST['user_type'] !=0)
		$cols[_("Contact Type")] = 'skip';	

		$table =& new_db_pager('crm_persons', $sql, $cols);
		$table->width = "80%";
		display_db_pager($table);
	}
}
div_start('FilteringList');
start_outer_table(TABLESTYLE2, "");
table_section(1);
start_row();

user_types_cells(_('Type : '),'user_type',null,true,_("Select User Type"));	
end_row();
if($_POST['user_type'] ==ST_CUSTOMER){
	table_section(2);
	
	start_row();
	$contact_type ='customer';
	$sql ="SELECT deb.debtor_no AS id, deb.name AS name  FROM ".TB_PREF."debtors_master as deb ";
	echo "<td>".combo_input('master_id',null, $sql, 'id', 'name',array('order'=>false,'select_submit' =>true,'spec_option'=>_('Select Customer')))."<td>";
	div_start('branch_list');
	if($_POST['user_type']==ST_CUSTOMER  && isset($_POST['master_id']) &&$_POST['master_id'] !=0){
		 $sql = "SELECT branch_code As id, br_name AS name FROM ".TB_PREF."cust_branch
			WHERE debtor_no=" . db_escape($_POST['master_id'])." ";
		echo "<td>".combo_input('branch_code', null, $sql, 'id', 'name',array('order'=>false,'select_submit' =>true,'spec_option'=>_('Select Branch'))) ."<td>";
	}
	div_end();
	end_row();
}elseif($_POST['user_type'] ==ST_SUPPLIER){
	table_section(2);
	start_row();
	$contact_type ='supplier';
	$sql ="SELECT supp.supplier_id AS id, supp.supp_name AS name  FROM ".TB_PREF."suppliers as supp ";
	echo "<td>".combo_input('master_id', null, $sql, 'id', 'name',array('order'=>false,'select_submit' =>true,'spec_option'=>_('Select Supplier')))."<td>";
	 end_row();
}

if(!isset($_POST['master_id']) || $_POST['master_id'] ==0){
	table_section(3);
	start_row();
	text_cells('Search','search_text');
	submit_cells('search', _("Search"),'',_('Select documents'), 'default');
	end_row();
}

if(list_updated('master_id')){	
	$selected_id =-1;
	$Ajax->activate('FilteringList');
	$Ajax->activate('user_type_list');
 }
 if(list_updated('branch_code')){	
	$selected_id =-1;
	$Ajax->activate('user_type_list');
 }
if(list_updated('type')){
	display_error($_POST['type']);
	$Ajax->activate('update_contact');
}

if($Mode == 'Edit') 
	$Ajax->activate('update_contact_type');
end_outer_table(1);
div_end();	

div_start('user_type_list');

display_rows();

div_start('update_contact_type');
if((!isset($_POST['master_id']) || $_POST['master_id'] ==0)  && $selected_id !=-1){
	br();
	
	if($_POST['user_type'] =='Others' && $Mode == 'Edit'){
		
		start_outer_table(TABLESTYLE);
		table_section(1);
		 $list = array(ST_CUSTOMER => _("Customer"), ST_SUPPLIER => _("Supplier"));
		 start_row();
	    echo "<td>Type</td>\n";
		echo "<td>"; 
    	echo array_selector('type',null, $list, 
        array( 
            'select_submit'=> true,
            'async' => false,
            'spec_option'=> _('Select a type'),
            'disabled' => false ) ); // FIX?
    	echo "</td>";
    	end_row();
    	if($_POST['type'] ==ST_CUSTOMER){
			table_section(2);
			
			start_row();
			$contact_type ='customer';
			$sql ="SELECT deb.debtor_no AS id, deb.name AS name  FROM ".TB_PREF."debtors_master as deb ";
			echo "<td>".combo_input('entity_id',null, $sql, 'id', 'name',array('order'=>false,'select_submit' =>true,'spec_option'=>_('Select Customer')))."<td>";
			div_start('branch_list');
			if($_POST['type']==ST_CUSTOMER  && isset($_POST['entity_id']) &&$_POST['entity_id'] !=0){
				 $sql = "SELECT branch_code As id, br_name AS name FROM ".TB_PREF."cust_branch
					WHERE debtor_no=" . db_escape($_POST['entity_id'])." ";
				echo "<td>".combo_input('branch_code', null, $sql, 'id', 'name',array('order'=>false,'select_submit' =>true,'spec_option'=>_('Select Branch'))) ."<td>";
			}
			div_end();
			end_row();
		}elseif($_POST['type'] ==ST_SUPPLIER){

			table_section(2);
			start_row();
			$contact_type ='supplier';
			$sql ="SELECT supp.supplier_id AS id, supp.supp_name AS name  FROM ".TB_PREF."suppliers as supp ";
			echo "<td>".combo_input('entity_id', null, $sql, 'id', 'name',array('order'=>false,'select_submit' =>true,'spec_option'=>_('Select Supplier')))."<td>";
			 end_row();
		}
		table_section(3);
		start_row();
		submit_cells('update_contact',_('Update'));
		end_row();
		end_outer_table(1);
		
	}else{
		
		start_outer_table(TABLESTYLE);
		table_section(1);
		table_section_title(_("Contact data"));
		$persons =GetRow('crm_persons',array('id'=>$selected_id));

		text_row(_("First Name:"), 'name', $persons['name'], 35, 40);
		text_row(_("Last Name:"), 'name2', $persons['name2'], 35, 40);
		text_row(_("Reference:"), 'ref', $persons['ref'], 35, 40);

		if(isset($persons['user_id']) && $persons['user_id'] == 0){
			kv_unassigned_users_for_contact_row(_("Select User Access:"), 'user_id',null,"No user selected");
		// }elseif (isset($persons['user_id']) && $persons['user_id'] > 0) {

		// }
		// else {
			text_row(_("Username:"), 'username', null, 32, 30);
			password_row(_("Password:"), 'password', null);
			check_row(_("Send Login Credentials through email"), 'send_welcome_email', null);
		}

		text_row(_("Phone:"), 'phone', $persons['phone'], 32, 30);
		text_row(_("Secondary Phone Number:"), 'phone2', $persons['phone2'], 32, 30);
		text_row(_("Fax Number:"), 'fax', $persons['fax'], 32, 30);
		email_row(_("E-mail:"), 'email', $persons['email'], 35, 55);

		table_section(2);
		table_section_title("&nbsp;");
		textarea_row(_("Address:"), 'address', $persons['address'], 30, 4);
		languages_list_row( _("Document Language:"), 'lang', $persons['lang'], _("Customer default"));

		textarea_row(_("Notes:"), 'notes', $persons['notes'], 30, 4);
		end_outer_table(1);
		hidden('selected_id',$selected_id);
		submit_add_or_update_center($selected_id == -1, '', 'both');
	}
}
div_end();
div_end();	
end_form();
end_page();
?>
