<?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/cs_ticket_message.class.php';
include_once './core/order.class.php';
include_once './core/standard_message.class.php';
include_once './core/customer.class.php';
include_once './core/mail.class.php';
include_once './core/site_content.class.php';

class Cs_ticket extends Main {

	protected $base_object;

	public $list_table_config = array (
		'title' => 'E-Mail Tickets',
		'db_table' => 'tickets',
		'list_fields' => array(
			array(
				'db_field' => 'number',
				'name' => 'Nummer',
				'sortable' => 1
			),
			array(
				'db_field' => 'subject',
				'name' => 'Betreff',
				'ref_db_table' => 'ticket_messages',
				'ref_db1_field' => 'id',
				'ref_db2_field' => 'ticket_id',
				'sortable' => 1
			),
			array(
				'db_field' => 'firstname',
				'name' => 'Vorname',
				'ref_db_table' => 'customers',
				'ref_db1_field' => 'customer_id',
				'ref_db2_field' => 'id',
				'sortable' => 1
			),
			array(
				'db_field' => 'surname',
				'name' => 'Nachname',
				'ref_db_table' => 'customers',
				'ref_db1_field' => 'customer_id',
				'ref_db2_field' => 'id',
				'sortable' => 1
			),
			array(
				'db_field' => 'create_time',
				'name' => 'Erstellt',
				'sortable' => 1
			),
			array(
				'db_field' => 'state_id',
				'rewrite_function' => 'state_values',
				'name' => 'Status',
				'sortable' => 1
			)
		),
		'list_actions' => array(
			array (
				'db_field' => 'state_id',
				'name' => 'Neuer Status',
				'values' => 'filter_state_values'
			)
		),
		'list_filter' => array(
			array (
				'db_field' => 'state_id',
				'relational_operator' => '=',
				'name' => 'Status',
				'values' => 'filter_state_values'
			)
		),
		'permanent_filter' => array(
			array(
				'db_field' => 'state_id',
				'relational_operator' => '!=',
				'value' => '4'
			)
		),
		'quick_filter' => 0,
		'list_css_selector' => 'state_id',
		'default_sort_item' => 'number',
		'default_sort_direction' => 'down',
		'search_fields' => array('tickets.number', 'customers.firstname', 'customers.surname', 'orders.order_number'),
		'db_id_field' => 'id',
		'list_group_by' => 'number',
		'edit_link' => 'index.php?admin_modul=admin_cs_ticket_editor&id=',
		'toolbar' => array(
			'delete' => 1,
			'new' => 'index.php?admin_modul=admin_cs_ticket_editor',
			'copy' => 0,
			'select_all' => 1,
			'edit' => 0,
			'actions' => 1,
			'filter' => 1,
			'search' => 1
		),
		'edit_fields' => array (
			array(
				'db_field' => 'state_id',
				'name' => 'Status',
				'type' => 'int'
			)
		)
	);

	private $object_fields = array(
		'number' => 'text',
		'customer_id' => 'integer',
		'state_id' => 'integer',
		'order_id' => 'integer'
	);

	function __construct($base_object) {
		$this->base_object = $base_object;
		$this->db = $base_object->db;
	}

	public function state_values() {
		return array(
			'1' => 'Neu',
			'2' => 'Offen',
			'3' => 'Geschlossen',
			'4' => 'Intern'
		);
	}

	public function filter_state_values() {
		return array(
			'1' => 'Neu',
			'2' => 'Offen',
			'3' => 'Geschlossen'
		);
	}

	public function get_all() {
		$sql = "SELECT * FROM tickets";
		$result = $this->db->query($sql);
		$data = array();
		while ($obj = $result->fetch_object()) {
			$data[] = $obj;
		}

		return $data;
	}

	public function get_all_customer_tickets($customer_id) {
		$sql = "SELECT * FROM tickets WHERE customer_id=".$this->db->real_escape_string($customer_id);
		$result = $this->db->query($sql);
		$data = array();
		while ($obj = $result->fetch_object()) {
			$data[] = $obj;
		}

		return $data;
	}

	public function get_all_order_tickets($order_id) {
		$sql = "SELECT * FROM tickets WHERE order_id=".$this->db->real_escape_string($order_id);
		$result = $this->db->query($sql);
		$data = array();
		while ($obj = $result->fetch_object()) {
			$data[] = $obj;
		}

		return $data;
	}


	public function get_data() {
		$sql = "SELECT * FROM tickets WHERE id = ".$this->id;
		$result = $this->db->query($sql);
		$obj = $result->fetch_object();

		// get ticket messages
		$ticket_message_object = new Cs_ticket_message($this->base_object);
		$ticket_messages = $ticket_message_object->get_all_ticket_messages($this->id);
		$obj->ticket_messages = $ticket_messages['messages'];
		$obj->last_message_number = $ticket_messages['last_message_number'];
		return $obj;
	} // end get_data

	public function get_id_by_number($ticket_number) {
		$sql = "SELECT * FROM tickets WHERE number = '#CS".$ticket_number."'";
		$result = $this->db->query($sql);
		if ($result) {
			$obj = $result->fetch_object();
			return $obj->id;
		}
		return false;
	}

	public function delete() {
		$sql = "DELETE FROM tickets WHERE id=".$this->id;
		$this->db->query($sql);
		return;
	}

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

	public function create($data) {
		// create new ticket
		$order = '';
		if (isset($data['order_id']) && $data['order_id']) {
			$order = "order_id=".$data['order_id'].", ";
		}
		$sql = "INSERT INTO tickets SET
			customer_id = ".$data['customer_id'].",".$order."
			state_id=".$data['state_id'].",
			create_time = current_timestamp
		";
		$this->db->query($sql);
		$this->id = $this->db->insert_id;

		// create new ticket number
		$this->ticket_number = $ticket_number = '#CS'.(100000 + $this->id);

		// set ticket number
		$sql = "
		UPDATE tickets
		SET number='".$ticket_number."'
		WHERE id=".$this->id;
		$this->db->query($sql);

		// create new message
		//$data['subject'] = '['.$ticket_number.'] '.$data['subject'];
		$data['subject'] = $data['subject'].' ['.$ticket_number.']';
		$ticket_message_object = new Cs_ticket_message($this->base_object);
		$data['ticket_id'] = $this->id;
		if (!isset($data['create_type'])) {
			$data['create_type'] = 2;
		}
		$form_data = $ticket_message_object->data_filter($data);

		$attachments = (isset($data['attachments'])) ? $data['attachments'] : false;
		$ticket_message_object->create($form_data, $attachments);

		// set state
		if (isset($data['state_id'])) {
			$this->set_state($data['state_id']);
		}

		if ($data['create_type'] == 2) {
			// send message
			$mailer = new mail_tools($this->base_object);
			$res = $mailer->send_mail($form_data['subject'], $form_data['message'], $form_data['m_to'], 'extern', false, false, false, false, $attachments);
		}

		return $ticket_message_object->id;
	}

	public function get_response($data) {
		// create new message
		$ticket_number = '#CS'.(100000 + $this->id);
		//$data['subject'] = '['.$ticket_number.'] '.$data['subject'];
		$data['subject'] = $data['subject'].' ['.$ticket_number.'] ';
		$ticket_message_object = new Cs_ticket_message($this->base_object);
		$data['ticket_id'] = $this->id;
		if (!isset($data['create_type'])) {
			$data['create_type'] = 1;
		}
		$form_data = $ticket_message_object->data_filter($data);
		$ticket_message_object->create($form_data);

		// set state
		if (isset($data['state_id'])) {
			$this->set_state($data['state_id']);
		}

		$attachments = false;
		if ($data['create_type'] == 2) {
			// send message
			$mailer = new mail_tools($this->base_object);
			$mailer->send_mail($form_data['subject'], $form_data['message'], $form_data['m_to'], 'extern', false, false, false, false, $attachments);
		}

		return $ticket_message_object->id;
	}

	private function search_order_ticket($search_options) {
		$sql = "SELECT * FROM tickets
				WHERE customer_id=".$search_options['customer_id']."
				AND order_id=".$search_options['order_id']."
				LIMIT 1
		";
		$result = $this->db->query($sql);
		if ($result) {
			$obj = $result->fetch_object();
			return $obj->id;
		} else {
			return 0;
		}
	}

	public function event($event_type, $customer_id, $order_id, $data = false) {

		$tracking_url='';
		$ticket_data = array(
			'customer_id' => $customer_id,
			'state_id' => 1,
			'order_id' => $order_id
		);
		// get ticket id - if exists
		if (!empty($ticket_data['order_id'])) {
			$this->id = $this->search_order_ticket($ticket_data);
		}
		// get customer data
		$customer_object = new Customer($this->base_object);
		$customer_object->customer_id = $customer_id;
		$customer_data = $customer_object->get_data();

		// get standard message
		$standard_message_object = new Standard_message($this->base_object);
		$standard_messages = $standard_message_object->get_messages_by_event($event_type);

		// get agbs
		$var_data = array();
		//if ($event_type == 3) {

		// customer data place holder
		$var_data['[#customer_id]'] = $customer_id;
		$var_data['[#customer_number]'] = $customer_data->number;

		if ($customer_data->honorific == 0) {
			$var_data['[#customer_salutation]'] = 'Herr';
			$var_data['[#full_salutation]'] = 'Herr '.$customer_data->firstname.' '.$customer_data->surname;
		} 
		else if ($customer_data->honorific == 1) {
			$var_data['[#customer_salutation]'] = 'Frau';
			$var_data['[#full_salutation]'] = 'Frau '.$customer_data->firstname.' '.$customer_data->surname;
		}
		else if ($customer_data->honorific == 2) {
			$var_data['[#customer_salutation]'] = 'Firma';
			$var_data['[#full_salutation]'] = 'Sehr geehrte Damen und Herren';
		}
		$var_data['[#customer_company]'] = $customer_data->company;
		$var_data['[#customer_name]'] = $customer_data->firstname.' '.$customer_data->surname;
		$var_data['[#customer_firstname]'] = $customer_data->firstname;
		$var_data['[#customer_email]'] = $customer_data->email;
		$var_data['[#customer_surename]'] = $customer_data->surname;
		$var_data['[#customer_address]'] = '';
			if ($customer_data->default_address_company) {
			$var_data['[#customer_address]'] .= $customer_data->default_address_company.'<br />';
		}
		if ($customer_data->default_address_surname) {
			$var_data['[#customer_address]'] .= $customer_data->default_address_firstname.' '.$customer_data->default_address_surname.'<br />';
		}
		$var_data['[#customer_address]'] .= $customer_data->default_address_street.' '.$customer_data->default_address_house_number.'<br />';
		$var_data['[#customer_address]'] .= $customer_data->default_address_zip_code.' '.$customer_data->default_address_city.'<br />';
		$var_data['[#customer_address]'] .= $customer_data->default_address_countryname.'<br />';
		$var_data['[#customer_skonto]'] = $customer_data->skonto;
		$var_data['[#customer_freetext1]'] = $customer_data->freetextfield1;
		$var_data['[#customer_freetext2]'] = $customer_data->freetextfield2;
		$var_data['[#customer_freetext3]'] = $customer_data->freetextfield3;
		$var_data['[#customer_freetext4]'] = $customer_data->freetextfield4;
		$var_data['[#customer_freetext5]'] = $customer_data->freetextfield5;
		$var_data['[#customer_freetext6]'] = $customer_data->freetextfield6;

		$var_data['[#customer_birthday]'] = $customer_data->burth_date;
		$var_data['[#customer_phone]'] = $customer_data->phone;
		$var_data['[#customer_fax]'] = $customer_data->fax;
		$var_data['[#customer_mobile]'] = $customer_data->mobile;
		$var_data['[#customer_website]'] = $customer_data->website;

		$var_data['[#customer_bank]'] = $customer_data->bank;
		$var_data['[#customer_bank_number]'] = $customer_data->bank_number;
		$var_data['[#customer_account_number]'] = $customer_data->account_number;
		$var_data['[#customer_iban]'] = $customer_data->iban;
		$var_data['[#customer_bic]'] = $customer_data->swift_bic;
		$var_data['[#customer_account_holder]'] = $customer_data->account_holder;

		$var_data['[#customer_tax_id]'] = $customer_data->tax_id;
		$var_data['[#customer_tax_number]'] = $customer_data->tax_number;

		$var_data['[#customer_da_zip_code]'] = $customer_data->default_address_zip_code;
		$var_data['[#customer_da_city]'] = $customer_data->default_address_city;
		$var_data['[#customer_da_street]'] = $customer_data->default_address_street;
		$var_data['[#customer_da_house_number]'] = $customer_data->default_address_house_number;
		$var_data['[#customer_da_countryname]'] = $customer_data->default_address_countryname;
		$var_data['[#customer_da_company]'] = $customer_data->default_address_company;
		$var_data['[#customer_da_firstname]'] = $customer_data->default_address_firstname;
		$var_data['[#customer_da_surname]'] = $customer_data->default_address_surname;

		// get agb's ...
		$site_content_object = new SiteContent($this->base_object);
		$var_data['[#datenschutz]'] = $site_content_object->get_textbox_data_by_id(55);
		$var_data['[#agb]'] = $site_content_object->get_textbox_data_by_id(56);
		$var_data['[#agb_b2b]'] = $site_content_object->get_textbox_data_by_id(10632);
		$var_data['[#widerruf]'] = $site_content_object->get_textbox_data_by_id(60);
		//}

		// get order data
		if ($order_id) {
			$var_data['[#order]'] = OrderHelper::get_order_items_html($order_id);
			$order_object = new Order($this->base_object);
			$order_object->id = $order_id;
			$order_data = $order_object->get_data();
			$var_data['[#order_number]'] = $order_data->order_number;
			$var_data['[#order_date]'] = $order_data->order_date;
			$var_data['[#order_customer_text]'] = $order_data->customer_info;


			// get country data
			include_once './core/country.class.php';
			$country_object = new Country($this->base_object);
			$countries = $country_object->get_all();


			// order billing address
			$var_data['[#order_address]'] = '';
			if ($order_data->billing_company) {
				$var_data['[#order_address]'] .= $order_data->billing_company.'<br />';
			}
			if ($order_data->billing_surname) {
				$var_data['[#order_address]'] .= $order_data->billing_firstname.' '.$order_data->billing_surname.'<br />';
			}
			$var_data['[#order_address]'] .= $order_data->billing_street.' '.$order_data->billing_house_number.'<br />';
			$var_data['[#order_address]'] .= $order_data->billing_zip_code.' '.$order_data->billing_city.'<br />';
			$var_data['[#order_address]'] .= $countries[$order_data->billing_country]->name.'<br />';

			// order shipping address
			$var_data['[#shipping_address]'] = '';
			if ($order_data->shipping_company) {
				$var_data['[#shipping_address]'] .= $order_data->shipping_company.'<br />';
			}
			if ($order_data->shipping_surname) {
				$var_data['[#shipping_address]'] .= $order_data->shipping_firstname.' '.$order_data->shipping_surname.'<br />';
			}
			$var_data['[#shipping_address]'] .= $order_data->shipping_street.' '.$order_data->shipping_house_number.'<br />';
			$var_data['[#shipping_address]'] .= $order_data->shipping_zip_code.' '.$order_data->shipping_city.'<br />';

			$var_data['[#shipping_address]'] .= $countries[$order_data->shipping_country]->name.'<br />';

			// get payment method
			if ($order_data->payment_method) {
				$sql = " SELECT name, order_email_text FROM payment_methods WHERE id = ".$order_data->payment_method;
				$result = $this->db->query($sql);
				$payment = $result->fetch_object();
				$var_data['[#payment_method]'] = $payment->name;
				$var_data['[#payment_text]'] = $payment->order_email_text;
			}
		}
		if ($event_type == 6 && $order_data->trackingcode && $order_data->shipping_method) { // versandt
			$sql = " SELECT tacking_url FROM deliverers WHERE id = '".$order_data->shipping_method."' ";
			$result = $this->db->query($sql);
			$deliever = $result->fetch_object();
			$tracking_url=$deliever->tacking_url;
			if ($tracking_url) {
				$tracking_url=str_replace(array('[trackingcode]'), array($order_data->trackingcode), $tracking_url);
			}
		}

		if ($data) {
			foreach ($data as $key => $value) {
				$var_data['[#'.$key.']'] = $value;
			}
		}

		if ($standard_messages) {
			foreach ($standard_messages as $standard_message) {
				if ($standard_message->active == 1 && ($standard_message->customer_group_id == 0 || $standard_message->customer_group_id == $customer_data->group_id)) {
					// create ticket
					$ticket_data['subject'] = strtr($standard_message->title,$var_data);
					$ticket_data['message'] = strtr($standard_message->message,$var_data);
					if ($tracking_url) {
						$ticket_data['message']=str_replace(array('[trackingcode]'), array($tracking_url), $ticket_data['message']);
					}
					if ($standard_message->recipient == 1) {
						$ticket_data['m_to'] = $customer_data->email;
					} else {
						$ticket_data['m_to'] = $this->base_object->config->shopConfiguration['mailRecipients'];
					}
					$ticket_data['m_from'] = $this->base_object->config->shopConfiguration['system_email'];
					// get attachments
					$standard_message_object->id = $standard_message->id;
					$ticket_data['attachments'] = $standard_message_object->get_file_list();
					if (isset($data['attachments'])) {
						$ticket_data['attachments'] = array_merge($ticket_data['attachments'], $data['attachments']);
					}

					if ($this->id) {
						//$ticket = $this->get_data();
						//$ticket_number = $ticket->number;
						$ticket_number = $this->ticket_number;
						$ticket_data['subject'] = $ticket_data['subject'].' ['.$ticket_number.']';

						$response_id = $this->send_response($ticket_data);
					} else {
						$this->id = $this->create($ticket_data);
					}
				}
			}
		}

		return $this->id;
	}

	public function send_response($data) {
		// create new message
		$ticket_message_object = new Cs_ticket_message($this->base_object);
		$data['ticket_id'] = $this->id;
		$data['create_type'] = 2;
		$form_data = $ticket_message_object->data_filter($data);

		$attachments = (isset($data['attachments'])) ? $data['attachments'] : false;
		$ticket_message_object->create($form_data, $attachments);

		// set state
		if (isset($data['state_id'])) {
			$this->set_state($data['state_id']);
		}
		 
		// todo send message
		$mailer = new mail_tools($this->base_object);
		$mailer->send_mail($form_data['subject'], $form_data['message'], $form_data['m_to'], 'extern', false, false, false, false, $attachments);

		return $ticket_message_object->id;
	}

	public function set_state($state_id) {
		$sql = "
		UPDATE tickets
		SET state_id=".$state_id."
		WHERE id=".$this->id;
		$this->db->query($sql);
		return;
	}

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

	public function fetch_email() {
		// mail connection data
		/*$mbox = imap_open("{pop3.web.de:110/pop3/novalidate-cert}", "richard_kammermayer", "azce74BU");

		if ($hdr = imap_check($mbox)) {
			$overview = imap_fetch_overview($mbox, '1:'.$hdr->Nmsgs, 0);

			if (is_array($overview)) {
				$curMsgNo = 0;

				foreach ($overview as $msgId => $message_data) {
					++$curMsgNo;

					// get body data
					$body = imap_body($mbox, $curMsgNo);

					// set ticket message data
					$ticket_data = array();
					$ticket_data['subject'] = $message_data->subject;
					$ticket_data['message'] = $body;
					$ticket_data['m_to'] = $message_data->to;
					$ticket_data['m_from'] = $message_data->from;
					$ticket_data['state_id'] = 1;

					// create new ticket
					$ticket_data['customer_id'] = 0;
					$ticket_data['create_type'] = 1;
					$this->ticket_id = false;
					if (preg_match("@\[\#CS([0-9]+)\]@si", $message_data->subject)) {
						$ticket_number = preg_replace("@(.*)?(\[\#CS)([0-9]+)(\])(.*)?@si", "$3", $message_data->subject);
						$this->id = $this->get_id_by_number($ticket_number);
					}

					if ($this->id) {
						$this->get_response($ticket_data);
					} else {
						$this->id = $this->create($ticket_data);
					}

				}
			}
		}*/

		/*imap_expunge($mbox);
		imap_delete($mbox, '1:*'); // to clear out an entire mailbox.
		imap_expunge($mbox);
		imap_close($mbox);*/

		return;
	}


	function get_part($mime_type, $structure = false, $part_number = false) {

		if (!$structure) {
			$structure = imap_fetchstructure($this->stream, $this->msgId);
		}

		if ($structure) {
			if ($mime_type == $this->get_mime_type($structure)) {
				if (!$part_number) {
					$part_number = 1;
				}

				$text = imap_fetchbody($this->stream, $this->msgId, $part_number);

				if ($structure->encoding == 3) {
					return imap_base64($text);
				} else if ($structure->encoding == 4) {
					return imap_qprint($text);
				} else {
					return $text;
				}
			}

			if ($structure->type == 1) {
				$prefix = '';

				foreach ($structure->parts as $part) {
					list($index, $sub_structure) = $part;

					if ($part_number) {
						$prefix = $part_number.'.';
					}

					$data = $this->get_part($mime_type, $sub_structure, $prefix.($index + 1));

					if ($data) {
						return $data;
					}
				}
			}
		}

		return false;
	}


	function get_mime_type(&$structure) {
		$primary_mime_type = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER");

		if ($structure->subtype) {
			return $primary_mime_type[(int) $structure->type].'/'.$structure->subtype;
		}

		return "TEXT/PLAIN";
	}

	function get_tickets_by_type() {
		$types = array('1' => 'Posteingang', '2' => 'Postausgang', '3' => 'geschlossen');
		$data = array(array(
			'id' => 0,
			'name' => 'Alle',
			'count' => $this->get_count_all(),
		));
		foreach ($types as $type_id => $type_name) {
			$data[] = array (
				'id' => $type_id,
				'name' => $type_name,
				'count' => $this->get_count_by_type($type_id),
			);
		}
		return $data;
	}

	function get_count_by_type($type_id) {
		$count = 0;
		$sql = "SELECT count(id) AS ticket_count
				FROM tickets
				WHERE state_id=".$this->db->real_escape_string($type_id);
		$result = $this->db->query($sql);
		if ($obj = $result->fetch_object()) {
			$count = $obj->ticket_count;
		}
		return $count;
	}

	function get_count_all() {
		$count = 0;
		$sql = "SELECT count(id) AS ticket_count FROM tickets";
		$result = $this->db->query($sql);
		if ($obj = $result->fetch_object()) {
			$count = $obj->ticket_count;
		}
		return $count;
	}

	function get_new_messages() {
		$sql = "SELECT * FROM tickets WHERE state_id=1 LIMIT 10";
		$result = $this->db->query($sql);
		while ($obj = $result->fetch_object()) {
			$data[] = $obj;
		}
		return $data;
	}

	function set_ticket_state($state_id, $ticket_id = false) {
		if ($ticket_id) {
			$id = $ticket_id;
		} else if ($this->id) {
			$id = $this->id;
		}

		if ($id) {
			$sql = "
			UPDATE tickets
			SET state_id='".$this->db->real_escape_string($state_id)."'
			WHERE id=".$this->db->real_escape_string($id);
			$this->db->query($sql);
			return 1;
		} else {
			return 0;
		}
	}

}

?>