<?php
require_once(DIR_FS_ADMIN.DIR_WS_CLASSES.'customer.php');
class customers extends databasetable
{
	function customers(){
		$this->set_tablename(TABLE_CUSTOMERS);
		$this->set_index('customers_id');
		$this->related_tables = array(
			0=>array('table'=>TABLE_CUSTOMERS_TO_COMPANIES,'key'=>$this->get_index(),'class'=>'customers_to_companies' ),
			1=>array('table'=>TABLE_ADDRESS_BOOKS,'key'=>$this->get_index(),'class'=>'address_books' )
		);
	}

	function get_customer($id){
		$values = $this->get_row_by_index($id);
		$customer_instance = new customer( (object) current($values) );
		return $customer_instance;
	}
	
	/**
	 * returns number of saved address books for a customer
	 *
	 * @param integer $id
	 * @return integer
	 */
	function count_address_books($id){
		$query = $this->query(sprintf("SELECT count(address_book_id) as anz FROM %s WHERE %s=%s",TABLE_ADDRESS_BOOKS,$this->get_index(),$id));
		if($query and is_array($query)){
			$result = current($query);
			return (int)$result['anz'];
		}
		return 0;
	}

	/**
	 * check the address-book table against the customers default address id
	 * if an error occures it updates the default-address entry
	 *
	 * @param integer $id
	 */
	function update_default_address_book_entry($id){
		$query = $this->query(sprintf("SELECT ab.address_book_id FROM %s c LEFT JOIN %s ab USING(%s) WHERE c.customers_default_address_id=ab.address_book_id and c.customers_id='%s'",$this->get_tablename(),TABLE_ADDRESS_BOOKS,$this->get_index(),$id));
		if($query and is_array($query)){
			// alles ok, es gibt einen defaulteintrag und dieser ist nicht geloescht
		}else{
			if($this->count_address_books($id) > 0){
				$query = $this->query(sprintf("SELECT address_book_id FROM %s WHERE %s='%s' ORDER BY address_date_added LIMIT 1",TABLE_ADDRESS_BOOKS,$this->get_index(),$id));
				$result = current($query);
				$this->set_default_address_book_entry($id, $result['address_book_id']);
			}else{
				// kein addressbuch mehr vorhanden -> default nullen
				$this->set_default_address_book_entry($id, 0);
			}
		}
	}
	
	function set_default_address_book_entry($id,$address_book_id){
		$this->query(sprintf("UPDATE %s SET customers_default_address_id=%s WHERE %s=%s",$this->get_tablename(),$address_book_id,$this->get_index(),$id));
	}
	
}
