<?php
/*
 * @version			$Id: index.php 10381 2008-06-01 03:35:53Z $
 * @package			Carteasy
 * @copyright		Copyright (C) 2005 - 2011 Wlanium
 * @license			proprietary
 * @author			Thomas Bartelt
 * Carteasy is a web shop system
 */

include_once './core/database.class.php';
include_once './core/honorific.class.php';
include_once './core/country.class.php';
include_once './core/money.class.php';
include_once './core/cs_ticket.class.php';
include_once './core/customergroups.class.php';
include_once './core/main.class.php';

class Customer extends Main {

	protected $base_object;

	public $list_table_config = array (
		'title' => 'Kunden',
		'db_table' => 'customers',
		'list_fields' => array(
			array(
				'db_field' => 'number',
				'name' => 'K-Nummer',
				'sortable' => 1
			),
			array(
				'db_field' => 'honorific',
				'name' => 'Anrede',
				'rewrite_function' => 'salutation_values',
				'sortable' => 1
			),
			array(
				'db_field' => 'firstname',
				'name' => 'Vorname',
				'sortable' => 1
			),
 			array(
				'db_field' => 'surname',
				'name' => 'Nachname',
				'sortable' => 1
			),
			array(
				'db_field' => 'company',
				'name' => 'Firma',
				'sortable' => 1
			),
			array(
				'db_field' => 'email',
				'name' => 'E-Mail',
				'sortable' => 1
			),
			array(
				'db_field' => 'country',
				'ref_db_table' => 'customer_addresses',
				'ref_db1_field' => 'default_address',
				'ref_db2_field' => 'id',
				'name' => 'Land',
				'rewrite_function' => 'country_values',
				'sortable' => 1
			),
			array(
				'db_field' => 'group_id',
				'name' => 'Kundengruppe',
				'rewrite_function' => 'customer_group_name',
				'sortable' => 1
			),
			array(
				'db_field' => 'locked',
				'name' => 'Status',
				'rewrite_function' => 'customer_state_text',
				'sortable' => 1
			)
		),
		'default_sort_item' => 'number',
		'default_sort_direction' => 'up',
		'search_fields' => array('customers.number','customers.firstname', 'customers.surname', 'customers.company', 'customers.email'),
		'db_id_field' => 'id',
		'edit_link' => 'index.php?admin_modul=admin_customer_editor&id=',
		'toolbar' => array(
			'delete' => 1,
			'new' => 'index.php?admin_modul=admin_customer_editor',
			'copy' => 0,
			'select_all' => 1,
			'edit' => 0,
			'actions' => 0,
			'csv_export' => 1,
			'filter' => 1,
			'search' => 1
		),
		'list_filter' => array(
			array (
				'db_field' => 'group_id',
				'relational_operator' => '=',
				'name' => 'Kundengruppe',
				'values' => 'customer_group_name'
			),
			array (
				'db_field' => 'customers.honorific',
				'relational_operator' => '=',
				'name' => 'Anrede',
				'values' => 'salutation_values'
			),
			array (
				'db_field' => 'customer_addresses.country',
				'relational_operator' => '=',
				'name' => 'Land',
				'values' => 'country_values'
			),
			array (
				'db_field' => 'locked',
				'relational_operator' => '=',
				'name' => 'Status',
				'values' => 'customer_state_text'
			),
			array (
				'db_field' => 'registration_date',
				'relational_operator' => '>=',
				'name' => 'Letzte Registrierungen bis vor',
				'values' => 'registration_date_filter_values'
			)
		),
		'edit_title' => 'Kunden',
		'edit_fields' => array (
			array(
				'name' => 'Stammdaten',
				'type' => 'form_title'
			),
			array(
				'db_field' => 'number',
				'name' => 'Kundennummer',
				'type' => 'text'
			),
			array(
				'db_field' => 'locked',
				'name' => 'Freigabe',
				'values' => 'active_values',
				'type' => 'int'
			),
			array(
				'db_field' => 'group_id',
				'name' => 'Kundengruppe',
				'values' => 'customer_group_values',
				'type' => 'int'
			),
			array(
				'db_field' => 'admin_role_id',
				'name' => 'Rolle (Admin-Berechtigung)',
				'values' => 'admin_role_values',
				'type' => 'int'
			),
			array(
				'name' => 'Kontaktdaten',
				'type' => 'form_title'
			),
			array(
				'db_field' => 'honorific',
				'name' => 'Anrede',
				'values' => 'salutation_values',
				'type' => 'int'
			),
			array(
				'db_field' => 'company',
				'name' => 'Firma',
				'type' => 'text'
			),
			array(
				'db_field' => 'firstname',
				'name' => 'Vorname',
				'type' => 'text'
			),
			array(
				'db_field' => 'surname',
				'name' => 'Nachname',
				'type' => 'text'
			),
			array(
				'db_field' => 'phone',
				'name' => 'Telefon',
				'type' => 'text'
			),
			array(
				'db_field' => 'mobile',
				'name' => 'Handy',
				'type' => 'text'
			),
			array(
				'db_field' => 'fax',
				'name' => 'Fax',
				'type' => 'text'
			),
			array(
				'db_field' => 'email',
				'name' => 'E-Mail',
				'type' => 'text'
			),
			array(
				'db_field' => 'website',
				'name' => 'Homepage',
				'type' => 'text'
			),
			array(
				'name' => 'Adressen',
				'type' => 'form_title'
			),
			array(
				'name' => 'Angaben für die Steuer',
				'type' => 'form_title'
			),
			array(
				'db_field' => 'tax_number',
				'name' => 'Steuernummer',
				'type' => 'text'
			),
			array(
				'db_field' => 'tax_id',
				'name' => 'Ust-ID',
				'type' => 'text'
			),
			array(
				'db_field' => 'eu_business',
				'name' => 'EU-Geschäfte',
				'values' => 'on_off_values',
				'type' => 'int'
			),
			array(
				'name' => 'Bankverbindung',
				'type' => 'form_title'
			),
			array(
				'db_field' => 'account_holder',
				'name' => 'Kontoinhaber',
				'type' => 'text'
			),
			array(
				'db_field' => 'account_number',
				'name' => 'Kontonummer',
				'type' => 'text'
			),
			array(
				'db_field' => 'bank',
				'name' => 'Geldinstitut',
				'type' => 'text'
			),
			array(
				'db_field' => 'bank_number',
				'name' => 'BLZ',
				'type' => 'text'
			),
			array(
				'db_field' => 'iban',
				'name' => 'IBAN',
				'type' => 'text'
			),
			array(
				'db_field' => 'swift_bic',
				'name' => 'SWIFT/BIC',
				'type' => 'text'
			),
			array(
				'name' => 'Zahlungsmethoden',
				'type' => 'form_title'
			),
			array(
				'db_field' => 'direct_debit_active',
				'name' => 'Bankeinzug',
				'values' => 'on_off_values',
				'type' => 'int'
			),
			array(
				'db_field' => 'rechnung_active',
				'name' => 'Rechnung',
				'values' => 'on_off_values',
				'type' => 'int'
			),
			array(
				'db_field' => 'skonto',
				'name' => 'Skonto %',
				'values' => 'skonto_values',
				'type' => 'int'
			),
			array(
				'name' => 'Weitere Kundendaten',
				'type' => 'form_title'
			),
			array(
				'db_field' => 'burth_date',
				'name' => 'Geburtsdatum',
				'type' => 'date'
			),
			array(
				'db_field' => 'freetextfield1',
				'name' => 'Freitextfeld 1',
				'type' => 'text'
			),
			array(
				'db_field' => 'freetextfield2',
				'name' => 'Freitextfeld 2',
				'type' => 'text'
			),
			array(
				'db_field' => 'freetextfield3',
				'name' => 'Freitextfeld 3',
				'type' => 'text'
			),
			array(
				'db_field' => 'freetextfield4',
				'name' => 'Freitextfeld 4',
				'type' => 'text'
			),
			array(
				'db_field' => 'freetextfield4',
				'name' => 'Freitextfeld 5',
				'type' => 'text'
			),
			array(
				'db_field' => 'freetextfield6',
				'name' => 'Freitextfeld 6',
				'type' => 'text'
			),
			array(
				'db_field' => 'newsletter_sub',
				'name' => 'Newsletter',
				'values' => 'on_off_values',
				'type' => 'int'
			),
			array(
				'db_field' => 'has_item_export',
				'name' => 'Artikel Export',
				'values' => 'on_off_values',
				'type' => 'int'
			),
			array(
				'db_field' => 'info',
				'name' => 'Notiz',
				'type' => 'multitext'
			),
			array(
				'name' => 'Passwort',
				'type' => 'form_title'
			),
			array(
				'db_field' => 'pass1',
				'name' => 'Neues Passwort',
				'type' => 'password'
			),
			array(
				'db_field' => 'pass2',
				'name' => 'Passwort wiederholen',
				'type' => 'password'
			),

		),
		'edit_pre_action' => array('manage_form_data'),
		'edit_post_action' => array('customer_edit_action'),
		'edit_mandatory_fields' => array('name'),
		'edit_js_file' => 'admin_customer_edit.js',
		'edit_toolbar' => array(
			'close' => 'index.php?admin_modul=admin_object_edit&object=Customer',
			'copy' => 0,
			'undo' => 0,
			'redo' => 0,
			'save' => 1,
			'new_password' => 1,
			'first_activation' => 1,
			'delete' => 1
		)
	);




	private $customer_fields = array(
		'number' => 'text',
		'group_id' => 'integer',
		'registration_date' => 'date',
		'admin_settings' => 'text',
		'honorific' => 'integer',
		'company' => 'text',
		'firstname' => 'text',
		'surname' => 'text',
		'burth_date' => 'date',
		'default_address' => 'integer',
		'phone' => 'text',
		'fax' => 'text',
		'mobile' => 'text',
		'email' => 'text',
		'website' => 'text',
		'account_holder' => 'text',
		'account_number' => 'text',
		'bank' => 'text',
		'bank_number' => 'text',
		'iban' => 'text',
		'swift_bic' => 'text',
		'pass' => 'password',
		'locked' => 'integer',
		'tax_id' => 'text',
		'tax_number' => 'text',
		'admin_role_id' => 'integer',
		'freetextfield1' => 'text',
		'freetextfield2' => 'text',
		'freetextfield3' => 'text',
		'freetextfield4' => 'text',
		'freetextfield5' => 'text',
		'freetextfield6' => 'text',
		'street' => 'text', // not in customer database
		'house_number' => 'text', // not in customer database
		'zip_code' => 'text', // not in customer database
		'city' => 'text', // not in customer database
		'country' => 'text', // not in customer database
		'eu_business' => 'integer',
		'skonto' => 'integer',
		'newsletter_sub' => 'integer'
	);

	private $verification_types = array(
		'regular_verification',
		'regular_no_email_verification',
		'company_verification',
		'company_no_email_verification'
	);

	var $customer_id = 0;
	var $language = 'de';// evt konfigurierbare standard sprache!!
	// default rabattgruppe
	var $rabattgruppe = 1;
	// standard price group
	var $preisgruppe = 1;
	var $haendler = 0;
	private $discount = array();


	private $config;
	private $_error;
	private $validation_errors;
	private $customergroups_object;

	public function __construct($base_object) {
		$this->config_object = $base_object->config;
		$this->db = $base_object->db;
		$this->base_object = $base_object;
		$this->customergroups_object = new CustomerGroups($base_object);
		$this->_error = '';
		$this->validation_errors = array();

		$begin = 32;
		for ($i=1;$i<7;$i++) {
			$this->list_table_config['edit_fields'][($begin + $i)]['name'] = '';
			if (isset($this->base_object->config->shopConfiguration['customer_freetextfield'.$i.'_name'])) {
				$this->list_table_config['edit_fields'][($begin + $i)]['name'] = $this->base_object->config->shopConfiguration['customer_freetextfield'.$i.'_name'];
			}
		}
	} 

	public function registration_date_filter_values() {
		$data = array();
		for ($i=1;$i<32;$i++) {
			$today = getdate((time() - (86400 * $i)));
			$day = ($i == 1)?' Tag':' Tage';
			$data[$today['year'].'-'.$today['mon'].'-'.$today['mday']] = $i.$day;

		}
		return $data;
	}


	public function on_off_values() {
		return array (
			'0' => 'Nein',
			'1' => 'Ja'
		);
	}

	public function salutation_values() {
		return array (
			'0' => 'Herr',
			'1' => 'Frau',
			'2' => 'Firma'
		);
	}

	public function active_values() {
		return array (
			'0' => 'Ja',
			'1' => 'Nein',
			'-1' => 'Erstfreigabe mit Benachrichtigung'
		);
	}

	public function skonto_values() {
		$data =  array ('0' => '-');
		for ($i=1;$i<11;$i++) {
			$data[$i] = $i;
		}
		return $data;
	}

	public function customer_state_text() {
		return array (
			'0' => 'aktiv',
			'1' => 'gesperrt'
		);
	}

	public function customer_group_name() {
		$data =  $this->customergroups_object->get_all_names();
		$data['0'] = '#not defined#';
		return $data;
	}

	public function customer_group_values() {
		$data =  $this->customergroups_object->get_all_names();
		$data['0'] = '-';
		return $data;
	}

	public function admin_role_values() {
		include_once './core/admin_role.class.php';
		$admin_role_object = new Admin_role($this->base_object);
		$data = $admin_role_object->get_all_names();
		$data['0'] = '-';
		return $data;
	}

	public function country_values() {
		include_once './core/main.class.php';
		$country_object = new Country($this->base_object);
		$data = $country_object->get_all_names();
		return $data;
	}

	public function get_error() {
		return $this->_error;
	}

	public function get_id() {
		return $this->customer_id;
	}

	public function set_id($id) {
		$this->customer_id = $id;
	}

	public function save($data, $object_id = false) {
		if (isset($data['id'])) {
			$id = $data['id'];
			unset($data['id']);

			$this->set_id($id);

			return $this->update($data);
		} else {
			return $this->create($data);
		}
	}

	public function login($loginname, $password, $login_save_session = false) {
		if ($loginname && $password) {
			$sql = "SELECT
						id, pass AS password, email, locked, group_id, merchant, firstname, surname, admin_role_id
					FROM
						customers
					WHERE
						(email = '".$this->db->real_escape_string($loginname)."'";

			$number = (int) $loginname;
			if ($number) {
				$sql .= " OR number='".$this->db->real_escape_string($number)."'";
			} if ($this->base_object->config->shopConfiguration['guest_order_customer_group']) {
				$sql .= ") AND group_id != ".$this->db->real_escape_string($this->base_object->config->shopConfiguration['guest_order_customer_group']);
			} else {
				$sql .= ")";
			}
			$result = $this->db->query($sql);

			if ($result->num_rows == 1) {
				$obj = $result->fetch_object();
				if ($obj->password == md5($password)) {
					if ($obj->locked == 1) {
						$_SESSION['zugriff']['admin'] = false;
						$_SESSION['uid'] = false;
						$_SESSION['ewcms'] = false;
						$_SESSION['new_login'] = false;
						// account disabled
						return 4;
					} else {
						$this->customer_id = $_SESSION['easyshop']['login']['id'] = $obj->id;
						$_SESSION['easyshop']['login']['haendler'] = $obj->merchant;
						$_SESSION['easyshop']['login']['name'] = $obj->name.' '.$obj->surname;

						// if admin
						if ($obj->admin_role_id > 0) {
							$_SESSION['zugriff']['admin'] = 1;
							$_SESSION['uid'] = $obj->id;
							$_SESSION['ewcms'] = true;
							$_SESSION['new_login'] = 'loggedandgood';
						} else {
							$_SESSION['zugriff']['admin'] = false;
							$_SESSION['uid'] = false;
							$_SESSION['ewcms'] = false;
							$_SESSION['new_login'] = false;
						}

						// save session?
						if ($login_save_session) {
							setcookie("userid",$obj->id,time()+(3600*24*100));
						}

						// login ok
						return 1;
					}
				} else {
					$_SESSION['zugriff']['admin'] = false;
					$_SESSION['uid'] = false;
					$_SESSION['ewcms'] = false;
					$_SESSION['new_login'] = false;
					// wrong password
					return 3;
				}
			} else {
					$_SESSION['zugriff']['admin'] = false;
					$_SESSION['uid'] = false;
					$_SESSION['ewcms'] = false;
					$_SESSION['new_login'] = false;
					// no customer found
					return 2;
			}
		}
		return 0;
	} // end login

	public function logout() {
		$_SESSION['zugriff']['admin'] = false;
		$_SESSION['uid'] = false;
		$_SESSION['ewcms'] = false;
		$_SESSION['new_login'] = false;

		unset($_COOKIE['userid']);
		setcookie("userid", '',time() - 3600);
		setcookie("userid", '',time() - 3600, '/');
		unset($_SESSION['easyshop']['login']['id']);
		return;
	} // end logout

	public function auth() {
		if (!isset($_SESSION['easyshop']['login']['id']) && isset($_COOKIE['userid'])) {
			$_SESSION['easyshop']['login']['id'] = $_COOKIE['userid'];
		}

		if (isset($_SESSION['easyshop']['login']['id'])) {
			$result = $this->db->query("
				SELECT
					c.*,
					ca.company AS default_address_company, ca.honorific AS default_address_honorific, ca.firstname AS default_address_firstname,
					ca.surname AS default_address_surname, ca.street AS default_address_street, ca.house_number AS default_address_house_number,
					ca.zip_code AS default_address_zip_code, ca.city AS default_address_city, ca.country AS default_address_country_id
				FROM
					customers c
				LEFT JOIN
					customer_addresses ca
				ON
					c.default_address = ca.id
				WHERE
					c.id = '".$_SESSION['easyshop']['login']['id']."'
			");

			if ($result->num_rows == 1) {
				$object_data = $result->fetch_object();
				// customer found
				if ($object_data->locked == 1) {
					// account disabled
					unset($_SESSION['easyshop']['login']['id']);
					return 4;
				} else {
					// account ok
					$this->customer_id = $_SESSION['easyshop']['login']['id'] = $object_data->id;
					$this->country_id = $object_data->default_address_country_id;
					foreach ($object_data as $key => $value) {
						$this->{$key} = $value;
					}
					if ($this->admin_role_id > 0) {
						return 2;
					}
					else {
						return 1;
					}
				}
			} else {
				unset($_SESSION['easyshop']['login']['id']);
			}
		}
		return 0;
	} // end auth

	public function lost_password($email) {
		if ($email) {
			$sql = "SELECT id, email FROM customers WHERE email LIKE '".$this->db->real_escape_string(trim($email))."' AND group_id !=".$this->db->real_escape_string(trim($this->base_object->config->shopConfiguration['guest_order_customer_group']));
			if ($this->base_object->config->shopConfiguration['guest_order_customer_group']) {
				$sql .= " AND group_id != ".$this->db->real_escape_string($this->base_object->config->shopConfiguration['guest_order_customer_group']);
			}

			$result = $this->db->query($sql);
			$obj = $result->fetch_object();
			if ($obj->id) {
				$new_password = $this->password_generator(4);
				$this->db->query("UPDATE customers SET pass = '".md5($new_password)."' WHERE id = ".$obj->id);
				$ticket_object = new Cs_ticket($this->base_object);
				$data = array('password' => $new_password);
				$ticket_object->event(10, $obj->id, false, $data);
				return 1;
			}
			return -1;
		}
		return 0;
	} // end lost_password

	public function new_password($customer_id) {
		if ($customer_id) {
			// set new password
			$new_password = $this->password_generator(4);
			$sql = "UPDATE customers SET pass = '".md5($new_password)."' WHERE id = ".$customer_id;
			$this->db->query($sql);
			$ticket_object = new Cs_ticket($this->base_object);
			$data = array(
				'password' => $new_password
			);
			$ticket_object->event(16, $customer_id, false, $data);
			return 1;
		}
		return false;
	} // end lost_password

	public function first_activation($customer_id) {
		if ($customer_id) {
			// send message to customer
			$ticket_object = new Cs_ticket($this->base_object);
			$ticket_object->event(12, $customer_id, false);
			return 1;
		}
		return false;
	}

	public function check_data_diff($customer_id, $data) {
		// get old customer data
		$customer_data_old = $this->get_data($customer_id);

		// get field data
		$field_data = array();
		foreach ($this->list_table_config['edit_fields'] as $field) {
			$values = false;
			if (isset($field['values'])) {
				$values = $this->{$field['values']}();
			}
			$field_data[$field['db_field']] = array(
				'name' => $field['name'],
				'values' => $values
			);
		}

		// check new data
		$diff_data = array();
		foreach ($data as $key => $value) {
			$value_old = $customer_data_old->{$key};
			if ($key != 'honorific' && $key != 'newsletter_sub' && $key != 'burth_date' &&  $key != 'pass' && $value != $value_old) {
				if ($field_data[$key]['values']) {
					$diff_data[$field_data[$key]['name']] = array(
						'old' => $field_data[$key]['values'][$value_old],
						'new' => $field_data[$key]['values'][$value]
					);
				}
				else {
					$diff_data[$field_data[$key]['name']] = array(
						'old' => $value_old,
						'new' => $value
					);
				}
				/*$log_object = Logger::get_instance();
				$log_object->info($key, $value.'---'.$value_old);*/
			}
		}

		return $diff_data;
	}

	function make_diff_table($data) {
		$html = '<table border="0" cellpadding="2" cellspacing="2">';
		$html .= '<tr><th colspan="3">Persönliche Daten geändert</hd></tr><th>Feld</th><th>Alter Wert</th><th>Neuer Wert</th></tr>';
		foreach ($data as $key => $val) {
			$html .= '<tr><td>'.$key.'</td><td>'.$val['old'].'</td><td>'.$val['new'].'</td></tr>';
		}
		$html .= '</table>';
		return $html;
	}

	public function get_data($id = false) {
		$customer_id = false;

		$customer_id = (is_numeric($id)) ? $id : $this->customer_id;

		$sql = "
			SELECT
				c.*,
				ca.company AS default_address_company, ca.honorific AS default_address_honorific, ca.firstname AS default_address_firstname,
				ca.surname AS default_address_surname, ca.street AS default_address_street, ca.house_number AS default_address_house_number,
				ca.zip_code AS default_address_zip_code, ca.city AS default_address_city, ca.country AS default_address_country_id,
				cr.name AS default_address_countryname,
				g.name AS group_name,
				g.show_tax
			FROM
				customers c
			LEFT JOIN
				customer_addresses ca
			ON
				c.default_address = ca.id
			LEFT JOIN
				countries cr
			ON
				cr.id = ca.country
			LEFT JOIN
				customer_groups g
			ON
				c.group_id = g.id
			WHERE
				c.id = $customer_id
		";

		$result = $this->db->query($sql);

		if ($result->num_rows > 0) {
			$obj = $result->fetch_object();
			$obj->files = $this->get_file_list();

			return $obj;
		}

		return false;
	} // end get_data

	public function add_uploaded_file($file_data) {
		$tmpname = $file_data['Filedata']['tmp_name'];
		$name = $file_data['Filedata']['name'];
		$type = $file_data['Filedata']['type'];
		$hndFile = fopen($tmpname, "r");
		$data = addslashes(fread($hndFile, filesize($tmpname)));

		if ($data) {
			$sql = "INSERT INTO customer_files (customer_id, file_name, file_data, file_type) VALUES
				(".$this->customer_id.", '".$name."', '".$data."','".$type."')";
			$this->db->query($sql);
		}
		return;
	}

	public function get_file_list() {
		$sql = "SELECT * FROM customer_files WHERE
				customer_id=".$this->db->real_escape_string($this->customer_id);

		$result = $this->db->query($sql);
		$data = array();

		if ($result->num_rows > 0) {
			while ($obj = $result->fetch_object()) {
				$data[] = $obj;
			}
		}

		return $data;
	} // end get_file_list

	public function get_file($file_id) {
		$sql = "SELECT * FROM cusomer_files WHERE customer_id=".$this->customer_id." AND id=".$file_id;
		$result = $this->db->query($sql);
		while ($obj = $result->fetch_object()) {
			$data[] = $obj;
		}
		return $data;
	}

	# password generator
	public function password_generator($count=4) {
		$conso=array("b","c","d","f","g","h","j","k","l","m","n","p","r","s","t","v","w","x","y","z");
		$vocal=array("a","e","i","o","u");
		$pw="";
		srand ((double)microtime()*1000000);
		for ($f=1; $f<=$count; $f++) {
			$pw.=$conso[rand(0,19)];
			$pw.=$vocal[rand(0,4)];
		}
		return($pw);
	} // end password_generator

	function get_payments() {
		$payments = array();
		$sql = "SELECT name FROM payment WHERE aktiv = '1' ORDER BY rang";
		$res=mysql_query($sql);
		while ($obj=mysql_fetch_object($res)) {
			$payments[] = $obj;
		}

		return $payments;
	} // end get_payments

	public function get_config_item($item_key) {
		if (isset($this->admin_settings)) {
			$config = array();
			eval($this->admin_settings);
			if (isset($config[$item_key])) {
				return $config[$item_key];
			}
			return;
		} else {
			return;
		}
	}

	public function set_config_item($item_key, $item_value) {
		$config = array();
		eval($this->admin_settings);
		$config[$item_key] = $item_value;
		$config_string = '$config = '.$this->php_2_string($config).';';
		$this->admin_settings = $config_string;
		$sql = 'UPDATE customers SET admin_settings = "'.$config_string.'" WHERE id = '.$this->customer_id;
		$this->db->query($sql);
		return;
	}

	private function php_2_string($data) {
		$string = '';
		if (is_array($data)) {
			$string .= 'array(';
			foreach ($data as $key => $value) {
				if (is_array($value)) {
					$string .= "'$key' => ".$this->php_2_string($value).", ";
				} else {
					$string .= "'$key' => '$value', ";
				}
			}
			$string .= ")";
		} else {
			$string .= "'".$data."'";
		}
		return $string;
	}

	public function get_new($limit = false) {
		$sql = "SELECT surname, firstname, email, number, id
				FROM customers
				WHERE DATE_SUB(CURDATE(), INTERVAL 1 DAY) <= registration_date";

		if ($limit) {
			$sql .= " LIMIT ".$limit;
		}

		$result = $this->db->query($sql);

		if ($result->num_rows > 0) {
			while ($row = $result->fetch_object()) {
				$data[] = $row;
			}

			return $data;
		}

		return false;
	} // end get_new

	public function new_customer_count() {
		$sql = "SELECT *FROM customers
				WHERE DATE_SUB(CURDATE(), INTERVAL 1 DAY) <= registration_date";

		$result = $this->db->query($sql);

		return $result->num_rows;
	} // end new_customer_count

	public function get_all() {
		$result = $this->db->query("SELECT *
							FROM customers");

		while ($row = $result->fetch_object()) {
			$data[] = $row;
		}

		return $data;
	} // end get_all


	public function data_filter($request) {
		$data = array();
		foreach ($this->customer_fields as $field_name => $var_type) {
			if (isset($request[$field_name])) {
				if ($var_type == 'text') {
					$data[$field_name] = $request[$field_name];
				} else if ($var_type == 'password') {
					if ($request[$field_name]) {
						$data[$field_name] = md5($request[$field_name]);
					}
				} else {
					$data[$field_name] = (int)$request[$field_name];
				}
			}
		}
		return $data;
	}

	public function search($data) {
		$sql = 'SELECT *
				FROM customers';

		$where = '';

		if (isset($data['firstname'])) {
			$where = Database::where($where, " firstname LIKE '%".$data['firstname']."%'");
		}

		if (isset($data['surname'])) {
			$where = Database::where($where, " surname LIKE '%".$data['surname']."%'");
		}

		if (isset($data['company'])) {
			$where = Database::where($where, " company LIKE '%".$data['company']."%'");
		}

		if (isset($data['street'])) {
			$where = Database::where($where, " street LIKE '%".$data['street']."%'");
		}

		if (isset($data['city'])) {
			$where = Database::where($where, " city LIKE '%".$data['city']."%'");
		}

		if (isset($data['email'])) {
			$where = Database::where($where, " email LIKE '%".$data['email']."%'");
		}

		$result = $this->db->query($sql.$where);

		while ($obj = $result->fetch_object()) {
			$end[] = $obj;
		}

		return $end;
	}

	public function delete_by_id($id) {
		$rs = $this->db->query("DELETE FROM customers WHERE id=$id;");
	}

	public function get_default_address($id) {
		$sql = "SELECT default_address FROM customers WHERE id=".$id;

		$result = $this->db->query($sql);

		if ($result->num_rows > 0) {
			$result->fetch_object()->default_address;
		}

		return false;
	}

	// TODO: who uses this and when can i get rid of it?
	public function get_address_by_customer_id($id, $customer_group_id = false) {
		$sql = "
			SELECT 
				a.*,
				c.name, c.shipping_area_id
			FROM 
				customer_addresses a
			LEFT JOIN
				countries c
			ON
				a.country = c.id
			WHERE 
				a.customer_id = ".$this->db->real_escape_string($id)."
		";

		$result = $this->db->query($sql);

		if ($result) {
			while ($obj = $result->fetch_object()) {
				if ($obj != NULL) {
				if ($customer_group_id) {
					$sql = "SELECT * FROM country_customergroup_shippingarea
						WHERE country_id = ".$obj->country." AND customer_group_id = $customer_group_id";
					$result2 = $this->db->query($sql);
					if ($result2->num_rows > 0) {
						$obj->shipping_area_id = $result2->fetch_object()->shipping_area_id;
					}
				}
					$return[$obj->id] = $obj;
				}
			}
		}

		if ($return) {
			return $return;
		}

		return false;
	} // end get_address_by_customer_id

	public static function get_address_by_id($id) {
		$db = Registry::get('base')->db;

		$sql = "SELECT default_address FROM customers WHERE id=".$id;

		$result = $db->query($sql);

		if ($result->num_rows > 0) {
			$default_address = $result->fetch_object()->default_address;
		} else {
			$default_address = false;
		}

		$sql = "SELECT * FROM customer_addresses WHERE customer_id = $id";

		$result = $db->query($sql);

		if ($result->num_rows > 0) {
			$i = 0;

			while ($obj = $result->fetch_object()) {
				$obj->honorific_text = Honorific::get_honorific($obj->honorific);
				$obj->country = Country::get_name_by_id($obj->country);

				if ($default_address) {
					if ($obj->id == $default_address) {
						$obj->isDefault = 1;
					} else {
						$obj->isDefault = 0;
					}
				} else {
					if ($i == 0) {
						$obj->isDefault = 1;
					} else {
						$obj->isDefault = 0;
					}
				}

				$return[] = $obj;
			}

			$i++;
		}

		if (is_array($return)) {
			uasort($return, function($a, $b) {
				if ($a->isDefault > $b->isDefault) {
					return -1;
				} else {
					return 1;
				}
			});
		}

		if ($return) {
			return $return;
		}

		return false;
	} // end get_address_by_customer_id

	// TODO: rewrite get_customer_addresses_by_id in admin_customer_actions to not use this class, needs lots o work in order edior
	public static function get_address_by_id_hacked($id) {
		$db = Registry::get('base')->db;

		$sql = "SELECT default_address FROM customers WHERE id=".$id;

		$result = $db->query($sql);

		if ($result->num_rows > 0) {
			$default_address = $result->fetch_object()->default_address;
		} else {
			$default_address = false;
		}

		$sql = "SELECT * FROM customer_addresses WHERE customer_id = $id";

		$result = $db->query($sql);

		if ($result->num_rows > 0) {
			$i = 0;

			while ($obj = $result->fetch_object()) {
				$obj->honorific_text = Honorific::get_honorific($obj->honorific);
				$obj->country_text = Country::get_name_by_id($obj->country);

				if ($default_address) {
					if ($obj->id == $default_address) {
						$obj->isDefault = 1;
					} else {
						$obj->isDefault = 0;
					}
				} else {
					if ($i == 0) {
						$obj->isDefault = 1;
					} else {
						$obj->isDefault = 0;
					}
				}

				$return[] = $obj;
			}

			$i++;
		}

		if ($return) {
			return $return;
		}

		return false;
	} // end get_address_by_customer_id

	public function find_customer_like($data) {
		$sql = "SELECT id, firstname, surname, company, number
				FROM customers
				WHERE CONCAT(firstname, surname, company, number) LIKE '%$data%'";

		$result = $this->db->query($sql);

		if ($result->num_rows > 0) {
			while ($obj = $result->fetch_object()) {
				$return[] = $obj;
			}

			return $return;
		}

		return false;
	} // end find_customer_like

	public function find_customer_by_id($id) {
		$sql = "SELECT * FROM customers WHERE id = $id";

		$result = $this->db->query($sql);

		if ($result->num_rows > 0) {
			return $result->fetch_object();
		}

		return false;
	} // end find_customer_by_id


	/**
	 * Get an Object with the customerdata (default address)
	 * 
	 * @param int	$id	the customer id
	 * 
	 * @return object with the customerdata
	 */
	public function get_by_id($id) {
		$sql = "
			SELECT
				c.*,
				ca.company AS default_address_company, ca.honorific AS default_address_honorific, ca.firstname AS default_address_firstname,
				ca.surname AS default_address_surname, ca.street AS default_address_street, ca.house_number AS default_address_house_number,
				ca.zip_code AS default_address_zip_code, ca.city AS default_address_city, ca.country AS default_address_country_id,
				cr.name AS default_address_countryname
			FROM
				customers c
			LEFT JOIN
				customer_addresses ca
			ON
				c.default_address = ca.id
			LEFT JOIN
				countries cr
			ON
				cr.id = ca.country
			WHERE
				c.id = $id
		";

		$result = $this->db->query($sql);

		if ($result->num_rows > 0) {
			return $result->fetch_object();
		}

		return false;
	}

	public static function get_name_by_id($id, $with_honorific = true) {
		$db = Registry::get('base')->db;

		$sql = "SELECT honorific, firstname, surname
				FROM customers
				WHERE id = $id";

		$result = $db->query($sql);


		if ($result->num_rows > 0) {
			$obj = $result->fetch_object();

			if ($with_honorific) {
				if ($obj->honorific == 0) {
					$honorific = "Herr ";
				} else if ($obj->honorific == 1) {
					$honorific = "Frau ";
				} else {
					$honorific = "";
				}
			} else {
				$honorific = "";
			}

			return $honorific.$obj->firstname.' '.$obj->surname;
		}

		return false;
	}

	// if insertet returns true, else false
	public function add_address($data) {
		$data = Database::clean($data);

		$sql = Database::insert('customer_addresses', $data);

		if ($this->db->query($sql)) {
			return $this->db->insert_id;
		}

		return false;
	} // end add_address

	public static function set_standard_address($customer_id, $address_id) {
		$db = Registry::get('base')->db;

		$sql = "UPDATE customers
				SET default_address=$address_id
				WHERE id=$customer_id";

		return $db->query($sql);
	} // end set_standard_address

	public static function delete_address($customer_id, $address_id) {
		$db = Registry::get('base')->db;

		$sql = "DELETE FROM customer_addresses
				WHERE id=$address_id
				AND customer_id=$customer_id";

		return $db->query($sql);
	}

	public static function has_id($id) {
		$db = Registry::get('base')->db;

		$sql = "SELECT *
				FROM customers
				WHERE id = $id";

		$result = $db->query($sql);

		if ($result->num_rows > 0) {
			return true;
		}

		return false;
	}

	public function set_last_interesting_item_groups ($group_id) {
		setcookie('last_interesting_item_groups', $group_id, time() + 60 * 60 * 24 * 365);
		return;
	}

	public function get_last_interesting_item_groups () {
		if (isset($_COOKIE['last_interesting_item_groups'])) {
			return $_COOKIE['last_interesting_item_groups'];
		}
		return;
	}

	public function create($data) {
		if ($data) {
			$customer_groups = $this->customergroups_object->get_all();

			//$data['locked'] = !$customer_groups[$data['group_id']]->state_after_registration;

			// is customer a guest
			$customer_is_guest = 0;
			if ($this->base_object->config->shopConfiguration['guest_order_customer_group'] == $customer_groups[$data['group_id']]->id) {
				$customer_is_guest = 1;
			}

			// E-Mail test
			if ($customer_is_guest) {
				$data['number'] = '';
			} else {
				if (trim($data['email']) != '') {
					$email_exists = $this->check_email($data['email']);
					if ($email_exists) {
							$this->_error = 'email exisitiert bereits';

							return false;
					}
				}

				// customer number
				$data['number'] = $this->get_next_number();
			}

			// registration date
			$today = getdate();
			$data['registration_date'] = $today['year'].'-'.$today['mon'].'-'.$today['mday'];

			// password
			if ($data['pass'] != '') {
				$data['pass'] = md5($data['pass']);
			}

			// birth date
			if ($data['burth_date'] == '') {
				$data['burth_date'] = '0000-00-00';
			}

			$sql = Database::insert('customers', $data);
			$return = $this->db->query($sql);
			if ($this->db->error) {
				$log_object = Logger::get_instance();
				$log_object->info('Error in /core/customer_class.php->create()', $this->db->error.', sql:'.$sql);
				$count = 0;
			}

			if ($return) {
				return $this->db->insert_id;
			}
			$this->_error = 'datenbank fehler';

			return false;
		}
		$this->_error = 'keine daten';

		return false;
	} // end create

	public function update($data) {
		if ($data) {

			if (isset($data['pass'])) {
				$data['pass'] = md5($data['pass']);
			}

			$sql = "UPDATE customers SET ";

			$size = count($data);

			$i = 1;
			foreach ($data as $key => $value) {
				$sql .= $key;
				$sql .= "=";

				$sql .= "'".$this->db->real_escape_string($value)."'";

				if ($i < $size) {
					$sql .= ", ";
					$i++;
				}
			}

			$sql .= " WHERE id=".$this->db->real_escape_string($this->customer_id);

			$result = $this->db->query($sql);

			if ($this->db->error) {
				$log_object = Logger::get_instance();
				$log_object->info('Error in /core/customer_class.php->update()', $this->db->error.', sql:'.$sql);
				$count = 0;
			}

			if ($result) {
				return $this->customer_id;
			}
		}

		return false;
	} // end update

	public function get_next_number() {
		$sql = "SELECT number FROM customers ORDER BY number DESC LIMIT 1";

		$result = $this->db->query($sql);

		if ($result->num_rows > 0) {
			return $result->fetch_object()->number + 1;
		}

		return 100001;
	} // end get_next_number

	public function verify($data, $is_update = false) {
		$this->validation_errors = array();

		if (isset($data['group_id'])) {
			$group_id = $data['group_id'];
		} else {
			$group_id = false;
		}

		if ($group_id) {
			$group_data = $this->customergroups_object->get_data($group_id);

			if ($group_data) {
				$verification_type = $group_data->verification_type;

				if ($verification_type == '') {
					$verification_type == 'regular_verification';
				}

				if ($verification_type == 'regular_verification') {
					return $this->regular_verification($data, $is_update);
				} else if ($verification_type == 'regular_no_email_verification') {
					return $this->regular_no_email_verification($data, $is_update);
				} else if ($verification_type == '') {
					return $this->company_verification($data, $is_update);
				} else if ($verification_type == '') {
					return $this->company_no_email_verification($data, $is_update);
				} else {
					$this->_error = "unknow verification type";

					return false;
				}
			} else {
				$this->_error = "No group data";

				return false;
			}
		}

		$this->_error = "No group id";

		return false;
	} // end verify

	public function regular_verification($data, $is_update) {
		$is_valid = true;

		// check first name
		if (!isset($data['firstname']) && $data['firstname'] != '') {
			$is_valid = false;
			$this->validation_errors['firstname'] = array('set' => false);
		}

		// check surname
		if (!isset($data['surname']) && $data['surname'] != '') {
			$is_valid = false;
			$this->validation_errors['surname'] = array('set' => false);
		}

		if (!$is_update) {
			if (isset($data['email']) && $data['email'] != '') {
				$email_in_use = $this->check_email($data['email']);

				if ($email_in_use) {
					$is_valid = false;
					$this->validation_errors['email'] = array('used' => true);
				}
			} else {
				$is_valid = false;
				$this->validation_errors['email'] = array('set' => false);
			}

			// check pass1
			if (!isset($data['pass']) && $data['pass']) {
				$is_valid = false;
				$this->validation_errors['pass'] = array('set' => false);
			}

			// check address
			//$this->address_verification();
		}

		if ($is_valid) {
			return $data;
		}

		return $is_valid;
	} // end regular_verification

	public function regular_no_email_verification($data, $is_update) {
		$is_valid = true;

		echo "<pre>";
		print_r($data);
		exit();

		echo "in regular_no_email_verification";
		exit();
	} // end regular_no_email_verification

	public function company_verification($data, $is_update) {
		$is_valid = true;

		echo "in company_verification";
		exit();
	} // end company_verification

	public function company_no_email_verification($data, $is_update) {
		$is_valid = true;

		echo "in company_no_email_verification";
		exit();
	} // end company_no_email_verification

	// TODO: hand this to customer address class in future
	public function address_verification($address) {
		echo "in address_verification";
	} // end address_verification

	public function check_email($email) {
		$sql = "SELECT * FROM customers WHERE email='".$this->db->real_escape_string($email)."'";
		if ($this->base_object->config->shopConfiguration['guest_order_customer_group']) {
			$sql .= " AND group_id != ".$this->base_object->config->shopConfiguration['guest_order_customer_group'];
		}
		$result = $this->db->query($sql);

		if ($result->num_rows > 0) {
			$obj = $result->fetch_object();

			return $obj->id;
		}

		return false;
	} // end check_email

	public function get_all_newsletter_subscriber($customer_group) {
		$sql = "SELECT
		id, firstname, surname, company, email
		FROM customers
		WHERE group_id=".$this->db->real_escape_string($customer_group)." AND newsletter_sub=1";

		$result = $this->db->query($sql);

		if ($result->num_rows > 0) {
			while ($obj = $result->fetch_object()) {
				$return[] = $obj;
			}

			return $return;
		}

		return false;
	} // end find_customer_like
}

?>