<?php

include_once($path_to_root. '/includes/ui/simple_crud_class.inc');
include_once($path_to_root . "/includes/db/crm_contacts_db.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/kvcodes.inc");

/*
	View/Edit class for contacts
*/
class crm_contacts extends simple_crud {
	var $id;
	var $entity;
	var $sub_class;
	var $class;
	
	function __construct($name, $id, $class, $subclass=null) {
		$fields = array('ref','name','name2','address', 'phone', 'phone2','fax', 'user_id', 'email','lang','notes', 'assgn' =>array('fld'=>'contacts'));
		parent::__construct($name, $fields);
		$this->class = $class;
		$this->subclass = $subclass;
		$this->entity = $id;
	}

	function list_view() {
		br();
			$contacts = get_crm_persons($this->class, $this->subclass, $this->entity);
			start_table(TABLESTYLE, "width='80%'");

			$th = array(_('Assignment'), _("Reference"), _("Username"), _("Full Name"), _("Phone"), _("Sec Phone"), _("Fax"),	_("email"),  '',	"&nbsp;");
			 if(isset($_SESSION['wa_current_user']->type)){ 
			 	unset($th[8]);
			 	unset($th[9]);
			 }
			table_header($th);
			$k = 0; 
			if(db_num_rows($contacts) > 0 ){
				$last = $myrow = db_fetch($contacts);
				while ($last)	{					
					if (@$myrow['id'] != $last['id']) {
						alt_table_row_color($k);
						label_cell(implode('<br>',$description));
						label_cell($last["ref"]);
						label_cell(GetSingleValue('users', 'user_id', ['id' => $last["user_id"]]));
						label_cell($last["name"].' '.$last["name2"]);
						label_cell($last["phone"]);
						label_cell($last["phone2"]);
						label_cell($last["fax"]);
						email_cell($last["email"]);

						if(!isset($_SESSION['wa_current_user']->type)){ 
							edit_button_cell("{$this->name}Edit[{$last['id']}]", _("Edit"));

							// delete button removes only category unless this is the last contact for this person
							delete_button_cell("{$this->name}Delete[{$last['id']}]", _("Delete"));
						}
						end_row();
						$description = array();
						$last = $myrow;
					}

					if ($myrow) {
						$description[] = $myrow['description'];
						$myrow = db_fetch($contacts);
					}
				}
			}

			//inactive_control_row($th);
			end_table(1);
	}
	
	function editor_view()	{
		br();
		global $Ajax;

		if(list_updated('user_id')){
			$_POST['user_id'] =get_post('user_id');			
			$Ajax->activate('EditContact');
		}

		div_start('EditContact');
			start_outer_table(TABLESTYLE);
			table_section(1);
			table_section_title(_("Contact data"));

			text_row(_("First Name:"), 'name', @$this->data['name'], 35, 40);
			text_row(_("Last Name:"), 'name2', @$this->data['name2'], 35, 40);
			text_row(_("Reference:"), 'ref', @$this->data['ref'], 35, 40);

			crm_category_types_list_row(_("Contact active for:"), 'assgn', @$this->data['contacts'],
				array('subclass' => @$this->subclass,
					'class' => @$this->class, 
					'multi' =>true)
					);
					
			kv_unassigned_users_for_contact_row(_("Select User Access:"), 'user_id',null,"No user selected", false);
			
			if($_POST['user_id'] == 0 && false) {
				text_row(_("Username:"), 'username', null, 32, 30);
				password_row(_("Password:"), 'password', null);
			}

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

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

			textarea_row(_("Notes:"), 'notes', @$this->data['notes'], 30, 4);
			end_outer_table(1);
		div_end();
	}

	function db_insert() {
			$dat = $this->data;
			if(isset($_POST['username']) && $_POST['username'] != ''){
				if($this->class == 'customer' || $this->class == 'cust_branch'){
					$role_id =GetSingleValue('kv_crm_option','option_value',array('option_name'=>'customer_role'));
				}elseif($this->class == 'supplier'){
					$role_id =GetSingleValue('kv_crm_option','option_value',array('option_name'=>'supplier_role'));
				}

				$user_id =Insert('users',array('user_id'=>$_POST['username'],'password'=>md5($_POST['password']),'real_name'=>$dat['name'],'phone'=>$dat['phone'],'email'=>$dat['email'],'language'=>$dat['lang'],'role_id'=>$role_id));
			}
			
			$person_id = add_crm_person($dat['ref'], $dat['name'], $dat['name2'], $dat['address'],
				$dat['phone'], $dat['phone2'], $dat['fax'], $dat['email'], $dat['lang'],
				$dat['notes'], $dat['contacts'], $this->entity);
			Update('crm_persons', ['id' => $person_id], ['user_id' => $user_id]);
			return $person_id;
	}

	function db_update() {
			if($_POST['user_id'] > 0 )
				Update('crm_persons', ['id' => $this->selected_id], ['user_id' => $_POST['user_id']]);
			return update_crm_person($this->selected_id, $_POST['ref'], $_POST['name'], $_POST['name2'], 
				$_POST['address'], $_POST['phone'], $_POST['phone2'], $_POST['fax'], $_POST['email'], 
				$_POST['lang'], $_POST['notes'], $_POST['assgn'], $this->entity, $this->class);
	}

	function insert_check() {
		global $new;
		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 (count_array(@$_POST['assgn']) ==0) {
			display_error(_("You have to select at least one category."));
			set_focus('assgn');
			return false;
		}
		if (!$this->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($this->selected_id && isset($_POST['user_id']) && $_POST['user_id'] <1){
		// 	display_error(_("NO user access selected"));
		// 	set_focus('password');
	 //    	return false;
		// }
		if(!$this->selected_id && $_POST['password'] ===''){
			display_error( _("The password cannot be empty!"));
			set_focus('password');
	    	return false;
		}elseif (!$this->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; 
	}

	function db_read() {
		return get_crm_person($this->selected_id);
	}

	function delete_check() {
		return true;
	}
	//
	//	Delete all contacts for person in current class/entity
	//
	function db_delete() {
		if (delete_crm_contacts($this->selected_id, $this->class, $this->entity)) {
			// if this is the last relation - delete contact data
			$rels = get_person_contacts($this->selected_id);
			if (count($rels)==0) {
				return delete_crm_person($this->selected_id);
			}
		}
		return false;
	}
}

?>
<?php  if(isset($_SESSION['wa_current_user']->type)){ ?>
<style type="text/css">
	button#contactsNEW {display:none !important;}
</style>
<?php } ?>