<?php

/* * *******************************************************************************
 * SugarCRM is a customer relationship management program developed by
 * SugarCRM, Inc. Copyright (C) 2004-2010 SugarCRM Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Affero General Public License along with
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 * 
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by SugarCRM".
 * ****************************************************************************** */

/**
 * THIS CLASS IS FOR DEVELOPERS TO MAKE CUSTOMIZATIONS IN
 */
class EcmSysInfo extends SugarBean {

	var $new_schema = true;
	var $module_dir = 'EcmSysInfos';
	var $object_name = 'EcmSysInfo';
	var $table_name = 'ecmsysinfos';
	var $importable = false;
	var $disable_row_level_security = true; // to ensure that modules created and deployed under CE will continue to function under team security if the instance is upgraded to PRO
	var $id;
	var $date_entered;
	var $date_modified;
	var $modified_user_id;
	var $modified_by_name;
	var $created_by;
	var $created_by_name;
	var $description;
	var $deleted;
	var $created_by_link;
	var $modified_user_link;
	var $assigned_user_id;
	var $assigned_user_name;
	var $assigned_user_link;
	var $phone_home;
	var $phone_mobile;
	var $phone_work;
	var $email1;
	var $email2;
	var $adress;
	var $banks;
	var $primary_mail;
	var $phone_fax;
	var $name_bank;
	var $invoice_number_format;
	var $invoice_number_format_id;
	var $short_name;
	var $short_name_id;
        var $smsApi_id;
	var $name;
	var $name_id;
	var $nip;
	var $nip_id;
	var $regon;
	var $regon_id;
	var $www;
	var $www_id;
	var $register_adress;
	var $correspondence_adress;
	var $krs;
	var $krs_id;
	var $contact_info;

	function EcmSysInfo() {
		parent::SugarBean();
              
		$this->fill_operating_values();
		$query = 'SELECT * FROM operating_values WHERE name = "firmInfo" AND module_name="EcmSysInfos"';
		$return = $this->db->query($query);
		$this->setBanks();
		$this->setAdress();
		$this->setContactInfo();
		while ($row = $this->db->fetchByAssoc($return)) {
			switch ($row['value0']) {
				case 'short_name':
					$this->short_name = $row['value9'];
					$this->short_name_id = $row['id'];
					break;
                                case 'smsApi':
					$this->smsApi_id = $row['id'];
					break;    
				case 'name':
					$this->name = $row['value9'];
					$this->name_id = $row['id'];
					break;
				case 'InvoiceNumberFormat':
					$this->invoice_number_format = $row['value9'];
					$this->invoice_number_format_id = $row['id'];
					break;
				case 'Regon':
					$this->regon = $row['value9'];
					$this->regon_id = $row['id'];
					break;
				case 'Nip':
					$this->nip = $row['value9'];
					$this->nip_id = $row['id'];
					break;
				case 'WWW':
					$this->www = $row['value9'];
					$this->www_id = $row['id'];
					break;
				case 'Krs':
					$this->krs = $row['value9'];
					$this->krs_id = $row['id'];
					break;
				case 'RegisterAdress':
					$this->register_adress = array();
					$this->register_adress['ID'] = $row['id'];
					$this->register_adress['STREET'] = $row['value1'];
					$this->register_adress['LOCAL'] = $row['value2'];
					$this->register_adress['HOME'] = $row['value3'];
					$this->register_adress['CITY'] = $row['value4'];
					$this->register_adress['POSTALCODE'] = $row['value5'];
					$this->register_adress['MAIL'] = $row['value6'];
					$this->register_adress['COMMUNITY'] = $row['value7'];
					$this->register_adress['DISTRICT'] = $row['value8'];
					$this->register_adress['STATE'] = $row['value9'];
					$this->register_adress['COUNTRY'] = $row['text0'];
					break; 
				case 'CorrespondenceAdress':
					$this->correspondence_adress = array();
					$this->correspondence_adress['ID'] = $row['id'];
					$this->correspondence_adress['STREET'] = $row['value1'];
					$this->correspondence_adress['LOCAL'] = $row['value2'];
					$this->correspondence_adress['HOME'] = $row['value3'];
					$this->correspondence_adress['CITY'] = $row['value4'];
					$this->correspondence_adress['POSTALCODE'] = $row['value5'];
					$this->correspondence_adress['MAIL'] = $row['value6'];
					$this->correspondence_adress['COMMUNITY'] = $row['value7'];
					$this->correspondence_adress['DISTRICT'] = $row['value8'];
					$this->correspondence_adress['STATE'] = $row['value9'];
					$this->correspondence_adress['COUNTRY'] = $row['text0'];
					break;
				default:
					break;
			}
		}
	}
	
	function getDatabaseName(){
		global $sugar_config,$current_user;
		$link = mysql_connect($sugar_config['dbconfig']['db_host_name'],$sugar_config['dbconfig']['db_user_name'],$sugar_config['dbconfig']['db_password']);
		mysql_select_db($sugar_config['dbconfig']['db_name'],$link);
		$d=mysql_query("select dbasename from users where id='".$current_user->id."'",$link);
		$dbase=mysql_fetch_array($d);
		return $dbase['dbasename'];
	}
	
	function fill_operating_values(){ 
		//Sprawdzamy numeracje
		$query = "SELECT value0 FROM operating_values WHERE name ='InvoiceNumberFormat'";
		$return = $this->db->query($query);
		$insertData = [
			['name' => 'InvoiceNumberFormat','value0' =>''],
			['name' => 'InvoiceNumberFormat','value0' =>'{n}/{Y}'],
			['name' => 'InvoiceNumberFormat','value0' =>'{n}/{y}'],
			['name' => 'InvoiceNumberFormat','value0' =>'{n}/{U}/{Y}'],
			['name' => 'InvoiceNumberFormat','value0' =>'{n}/{m}/{y}'],
			['name' => 'InvoiceNumberFormat','value0' =>'Nistandardowe'],
		];
		$returnData = array();
		while ($row = $this->db->fetchByAssoc($return)) {
			$returnData[$row['value0']] = true;
		}
		foreach($insertData as $key => $value){
			if($returnData[$value['value0']] != true){
				$keys = array_keys($value);
				$values = array_values($value);
				$insertQuery = "INSERT INTO operating_values (" . implode(",",$keys) . ") VALUES ('" . implode("','",$values) . "');";
				$this->db->query($insertQuery);
			}
		}
		
		//Nagłówki
		//Pobieram podstawową numerację
		$query = "SELECT id FROM operating_values WHERE name ='InvoiceNumberFormat' AND value0='{n}/{Y}'";
		$return = $this->db->query($query);
		$row = $this->db->fetchByAssoc($return);
		$numerId = $row['id'];
		//Sprawdzamy dla jezyka polskiego
		$query = "SELECT value0 FROM operating_values WHERE name ='headersDocuments' AND value4='pl_pl'";
		$return = $this->db->query($query);
		$insertData = [
			['name' => 'headersDocuments', 'value0' => 'Faktura', 'value1' =>$numerId, 'value2' => 'EcmInvoiceOuts', 'value3' => '01', 'value4' => 'pl_pl', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'Paragon', 'value1' =>$numerId, 'value2' => 'EcmReceipts', 'value3' => '02', 'value4' => 'pl_pl', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'Faktura z paragonu', 'value1' =>$numerId, 'value2' => 'EcmReceiptsToInvoiceOuts', 'value3' => '03', 'value4' => 'pl_pl', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'Oferta', 'value1' =>$numerId, 'value2' => 'EcmQuotes', 'value3' => '04', 'value4' => 'pl_pl', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'Zamówienie sprzedaży', 'value1' =>$numerId, 'value2' => 'EcmSales', 'value3' => '05', 'value4' => 'pl_pl', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'Zamówienie zakupu', 'value1' =>$numerId, 'value2' => 'EcmPurchaseOrders', 'value3' => '06', 'value4' => 'pl_pl', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'KS', 'value1' =>$numerId, 'value2' => 'EcmStockDocCorrects', 'value3' => '07', 'value4' => 'pl_pl', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'PZ', 'value1' =>$numerId, 'value2' => 'EcmStockDocIns', 'value3' => '08', 'value4' => 'pl_pl', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'WZ', 'value1' =>$numerId, 'value2' => 'EcmStockDocOuts', 'value3' => '09', 'value4' => 'pl_pl', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'PW', 'value1' =>$numerId, 'value2' => 'EcmStockDocInsideIns', 'value3' => '10', 'value4' => 'pl_pl', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'MM', 'value1' =>$numerId, 'value2' => 'EcmStockDocMoves', 'value3' => '11', 'value4' => 'pl_pl', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'RW', 'value1' =>$numerId, 'value2' => 'EcmStockDocInsideOuts', 'value3' => '12', 'value4' => 'pl_pl', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'KP', 'value1' =>$numerId, 'value2' => 'EcmNewKpkwsReceived', 'value3' => '13', 'value4' => 'pl_pl', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'KW', 'value1' =>$numerId, 'value2' => 'EcmNewKpkwsGave', 'value3' => '14', 'value4' => 'pl_pl', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'Faktury zaliczkowe', 'value1' =>$numerId, 'value2' => 'EcmPrepaymentInvoices', 'value3' => '15', 'value4' => 'pl_pl', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'Umowy', 'value1' =>$numerId, 'value2' => 'EcmAgreements', 'value3' => '16', 'value4' => 'pl_pl', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'Zlecenie serwisowe', 'value1' =>$numerId, 'value2' => 'EcmServiceNews', 'value3' => '17', 'value4' => 'pl_pl', 'module_name' => 'EcmSysInfos'],
		];
		$returnData = array();
		while ($row = $this->db->fetchByAssoc($return)) {
			$returnData[$row['value0']] = true;
		}
		foreach($insertData as $key => $value){
			if($returnData[$value['value0']] != true){
				$keys = array_keys($value);
				$values = array_values($value);
				$insertQuery = "INSERT INTO operating_values (" . implode(",",$keys) . ") VALUES ('" . implode("','",$values) . "');";
				$this->db->query($insertQuery);
			}
		}
		//Sprawdzamy dla jezyka angielskiego
		$query = "SELECT value0 FROM operating_values WHERE name ='headersDocuments' AND value4='en_us'";
		$return = $this->db->query($query);
		$insertData = [
			['name' => 'headersDocuments', 'value0' => 'Faktura', 'value1' =>$numerId, 'value2' => 'EcmInvoiceOuts', 'value3' => '01', 'value4' => 'en_us', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'Paragon', 'value1' =>$numerId, 'value2' => 'EcmReceipts', 'value3' => '02', 'value4' => 'en_us', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'Faktura z paragonu', 'value1' =>$numerId, 'value2' => 'EcmReceiptsToInvoiceOuts', 'value3' => '03', 'value4' => 'en_us', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'Oferta', 'value1' =>$numerId, 'value2' => 'EcmQuotes', 'value3' => '04', 'value4' => 'en_us', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'Zamówienie sprzedaży', 'value1' =>$numerId, 'value2' => 'EcmSales', 'value3' => '05', 'value4' => 'en_us', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'Zamówienie zakupu', 'value1' =>$numerId, 'value2' => 'EcmPurchaseOrders', 'value3' => '06', 'value4' => 'en_us', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'KS', 'value1' =>$numerId, 'value2' => 'EcmStockDocCorrects', 'value3' => '07', 'value4' => 'en_us', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'PZ', 'value1' =>$numerId, 'value2' => 'EcmStockDocIns', 'value3' => '08', 'value4' => 'en_us', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'WZ', 'value1' =>$numerId, 'value2' => 'EcmStockDocOuts', 'value3' => '09', 'value4' => 'en_us', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'PW', 'value1' =>$numerId, 'value2' => 'EcmStockDocInsideIns', 'value3' => '10', 'value4' => 'en_us', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'MM', 'value1' =>$numerId, 'value2' => 'EcmStockDocMoves', 'value3' => '11', 'value4' => 'en_us', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'RW', 'value1' =>$numerId, 'value2' => 'EcmStockDocInsideOuts', 'value3' => '12', 'value4' => 'en_us', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'KP', 'value1' =>$numerId, 'value2' => 'EcmNewKpkwsReceived', 'value3' => '13', 'value4' => 'en_us', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'KW', 'value1' =>$numerId, 'value2' => 'EcmNewKpkwsGave', 'value3' => '14', 'value4' => 'en_us', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'Faktury zaliczkowe', 'value1' =>$numerId, 'value2' => 'EcmPrepaymentInvoices', 'value3' => '15', 'value4' => 'en_us', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'Umowy', 'value1' =>$numerId, 'value2' => 'EcmAgreements', 'value3' => '16', 'value4' => 'en_us', 'module_name' => 'EcmSysInfos'],
			['name' => 'headersDocuments', 'value0' => 'Zlecenie serwisowe', 'value1' =>$numerId, 'value2' => 'EcmServiceNews', 'value3' => '17', 'value4' => 'en_us', 'module_name' => 'EcmSysInfos'],
		];
		$returnData = array();
		while ($row = $this->db->fetchByAssoc($return)) {
			$returnData[$row['value0']] = true;
		}
		foreach($insertData as $key => $value){
			if($returnData[$value['value0']] != true){
				$keys = array_keys($value);
				$values = array_values($value);
				$insertQuery = "INSERT INTO operating_values (" . implode(",",$keys) . ") VALUES ('" . implode("','",$values) . "');";
				$this->db->query($insertQuery);
			}
		}
		
		//Autonumeracja
		$query = "SELECT name FROM operating_values WHERE value2 ='Auto_increment'";
		$return = $this->db->query($query);
		$insertData = [
			['name' => 'ecmproductsCodeIncrement', 'value0' => '0','value2'=>'Auto_increment', 'module_name' => 'EcmProducts'],
			['name' => 'PartNumber', 'value0' => '0', 'value2' => 'Auto_increment', 'module_name' => 'EcmProducts'],
		];
		while ($row = $this->db->fetchByAssoc($return)) {
			$returnData[$row['name']] = true;
		}
		foreach($insertData as $key => $value){
			if($returnData[$value['name']] != true){
				$keys = array_keys($value);
				$values = array_values($value);
				$insertQuery = "INSERT INTO operating_values (" . implode(",",$keys) . ") VALUES ('" . implode("','",$values) . "');";
				$this->db->query($insertQuery);
			}
		}
	}

	function bean_implements($interface) {
		switch ($interface) {
			case 'ACL': return true;
		}
		return false;
	}
        
        function getNotificationSettings(){
            $db=$GLOBALS['db'];
            $query="select * from operating_values where value0='smsApi'";
            $res=$db->query($query);
            return $db->fetchByAssoc($res);
        }
        
        function saveNotificationSettings(){
            
                $query = '';
		if ($this->smsApi_id == null) {
			$query = 'INSERT INTO operating_values (name,value0,value1,value2,value3,value4,value5,value6,value7,value8,value9,module_name) VALUES ("firmInfo","smsApi","' . $_POST['api_login'] . '","' . $_POST['api_password'] . '","' . $_POST['api_from'] . '","' . $_POST['prevent_first'] . '","' . $_POST['prevent_second'] . '","' . $_POST['debt_first'] . '","' . $_POST['debt_other'] . '","' . $_POST['send_sms'] . '","' . $_POST['send_email'] . '","EcmSysInfos")';
		} else {
			$query = 'UPDATE operating_values SET value1="' . $_POST['api_login'] . '",value2="' . $_POST['api_password'] . '",value3="' . $_POST['api_from'] . '",value4="' . $_POST['prevent_first'] . '",value5="' . $_POST['prevent_second'] . '",value6="' . $_POST['debt_first'] . '",value7="' . $_POST['debt_other'] . '",value8="' . $_POST['send_sms'] . '",value9="' . $_POST['send_email'] . '" where id="' . $this->smsApi_id . '"';
		}
               
		$this->db->query($query);
             
             
        }
	function saveShortName($short_name) {
		$this->short_name = trim($short_name);
		$query = '';
		if ($this->short_name_id == null) {
			$query = 'INSERT INTO operating_values (name,value0,value9,module_name) VALUES ("firmInfo","short_name","' . $this->short_name . '", "EcmSysInfos")';
		} else {
			$query = 'UPDATE operating_values SET value9="' . $this->short_name . '" where id="' . $this->short_name_id . '"';
		}
		$this->db->query($query);
	}

	function saveKrs($krs) {
		$this->krs = trim($krs);
		$query = '';
		if ($this->krs_id == null) {
			$query = 'INSERT INTO operating_values (name,value0,value9,module_name) VALUES ("firmInfo","Krs","' . $this->krs . '", "EcmSysInfos")';
		} else {
			$query = 'UPDATE operating_values SET value9="' . $this->krs . '" where id="' . $this->krs_id . '"';
		}
		$this->db->query($query);
	}

	function saveName($name) {
		$this->name = trim($name);
		$query = '';
		if ($this->name_id == null) {
			$query = 'INSERT INTO operating_values (name,value0,value9,module_name) VALUES ("firmInfo","name","' . $this->name . '", "EcmSysInfos")';
		} else {
			$query = 'UPDATE operating_values SET value9="' . $this->name . '" where id="' . $this->name_id . '"';
		}
		$this->db->query($query);
	}

	function saveInvoiceNumberFormat($invoice_number_format) {
		$this->invoice_number_format = trim($invoice_number_format);
		$query = '';
		if ($this->invoice_number_format_id == null) {
			$query = 'INSERT INTO operating_values (name,value0,value9,module_name) VALUES ("firmInfo","InvoiceNumberFormat","' . $this->invoice_number_format . '", "EcmSysInfos")';
		} else {
			$query = 'UPDATE operating_values SET value9="' . $this->invoice_number_format . '" where id="' . $this->invoice_number_format_id . '"';
		}
		$this->db->query($query);
	}

	function saveNip($nip) {
		$this->nip = trim($nip);
		$query = '';
		if ($this->nip_id == null) {
			$query = 'INSERT INTO operating_values (name,value0,value9,module_name) VALUES ("firmInfo","Nip","' . $this->nip . '", "EcmSysInfos")';
		} else {
			$query = 'UPDATE operating_values SET value9="' . $this->nip . '" where id="' . $this->nip_id . '"';
		}
		$this->db->query($query);
	}

	function saveFile(){
	    try {
	    
	        // Undefined | Multiple Files | $_FILES Corruption Attack
	        // If this request falls under any of them, treat it invalid.
	        if (
	                !isset($_FILES['upfile']['error']) ||
	                is_array($_FILES['upfile']['error'])
	        ) {
	            throw new RuntimeException('Invalid parameters.');
	        }
	    
	        // Check $_FILES['upfile']['error'] value.
	        switch ($_FILES['upfile']['error']) {
	            case UPLOAD_ERR_OK:
	                break;
	            case UPLOAD_ERR_NO_FILE:
	                throw new RuntimeException('');
	            case UPLOAD_ERR_INI_SIZE:
	            case UPLOAD_ERR_FORM_SIZE:
	                throw new RuntimeException('Exceeded filesize limit.');
	            default:
	                throw new RuntimeException('Unknown errors.');
	        }
	    
	        // You should also check filesize here.
	        if ($_FILES['upfile']['size'] > 1000000) {
	            throw new RuntimeException('Exceeded filesize limit.');
	        }
	    
	        // DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
	        // Check MIME Type by yourself.
	        $finfo = new finfo(FILEINFO_MIME_TYPE);
	        if (false === $ext = array_search(
	                $finfo->file($_FILES['upfile']['tmp_name']),
	                array(
	                        'jpg' => 'image/jpeg',
	                        'png' => 'image/png',
	                        'gif' => 'image/gif',
	                ),
	                true
	        )) {
	            throw new RuntimeException('Invalid file format.');
	        }
	    
	        // You should name it uniquely.
	        // DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
	        // On this example, obtain safe unique name from its binary data.
	       $name= create_guid(); 
	      
	        if (!move_uploaded_file(
	                $_FILES['upfile']['tmp_name'],
	                sprintf('upload/%s.%s',
	                        $name,
	                        $ext
	                )
	        )) {
	            throw new RuntimeException('Failed to move uploaded file.');
	        } else {
	            $query="update operating_values set value7='".$name.'.'.$ext."' where id=19";
	            $this->db->query($query);
	        }
	    
	    
	    } catch (RuntimeException $e) {
	    
	        echo $e->getMessage();
	    
	    }
	}
	
	function getLogo(){
	    $z=$this->db->query('select value7 from operating_values where id=19');
	    $bb=$this->db->fetchByAssoc($z);
	    return $bb['value7'];
	}
	
	function saveBanks($banks) {
		$arrayin = array();
		foreach ($banks as $key => $value) {
			if (!isset($value['ID']) || $value['ID'] == '') {
				$query = 'INSERT INTO operating_values (name,value0,value3,value2,value4,value5,
				        value7,value8,value9,module_name) VALUES ("firmInfo","bankAccount","' . $value['CURRENCY'] . '","' . $value['NAMESHORT'] . '","' . $value['SWIFT'] . '","' . trim($value['IBAN']) . '","' . trim($value['POSITION']) . '","' . trim($value['NAME']) . '","' . trim($value['NUMBER']) . '", "EcmSysInfos")';
				$this->db->query($query);
				$query = 'SELECT id FROM operating_values WHERE name="firmInfo" AND value0="bankAccount" AND module_name = "EcmSysInfos" AND ';
				$query .= '" AND value9 = "' . trim($value['NUMBER']);
				$query .= '" AND value8 = "' . trim($value['NAME']);
				$query .= '" AND value3 = "' . trim($value['CURRENCY']);
				$query .= '" AND value4 = "' . trim($value['SWIFT']);
				$query .= '" AND value5 = "' . trim($value['IBAN']);
				$query .= '" AND value2 = "' . trim($value['NAMESHORT']);
				$query .= '" AND value7 = "' . $value['POSITION'] . '"';
				
				$return = $this->db->query($query);
				$row = $this->db->fetchByAssoc($return);
				$arrayin[] = $row['id'];
			} else {
				$query = 'UPDATE operating_values SET value7 = "' . $value['POSITION'] . '",value2 = "' . $value['NAMESHORT'] . '", value8 = "' . trim($value['NAME']) . '", value9 = "' . trim($value['NUMBER']) . '"
				        , value3 = "' . trim($value['CURRENCY']) . '"
				                , value4 = "' . trim($value['SWIFT']) . '"
				                        , value5 = "' . trim($value['IBAN']) . '" where id="' . $value['ID'] . '"';
				$this->db->query($query);
				$arrayin[] = $value['ID'];
			}
		}
		$stringIn = '(';
		//delete old adress
		if (count($arrayin) > 0) {
			foreach ($arrayin as $key => $value) {
				if ($key == 0) {
					$stringIn .=$value;
				} else {
					$stringIn .= ',' . $value;
				}
			}
			$stringIn .= ')';
			$query = 'DELETE FROM operating_values WHERE id NOT IN ' . $stringIn . ' AND name="firmInfo" AND value0="bankAccount" AND module_name = "EcmSysInfos"';
			$this->db->query($query);
		}
		$this->setBanks();
	}

	function saveRegon($regon) {
		$this->regon = trim($regon);
		$query = '';
		if ($this->regon_id == null) {
			$query = 'INSERT INTO operating_values (name,value0,value9,module_name) VALUES ("firmInfo","Regon","' . $this->regon . '", "EcmSysInfos")';
		} else {
			$query = 'UPDATE operating_values SET value9="' . $this->regon . '" where id="' . $this->regon_id . '"';
		}
		$this->db->query($query);
	}

	function saveAdress($adress) {
		$arrayin = array();
		foreach ($adress as $key => $value) {
			if (!isset($value['ID']) || $value['ID'] == '') {
				$query = 'INSERT INTO operating_values (name,value0,module_name,value2,value3,value4,value5,value6,value7) ';
				$query .= 'VALUES ("firmInfo","Adress", "EcmSysInfos","';
				$query .= $value['POSITION'] . '","'; // value2
				$query .= trim($value['NAME']) . '","';
				$query .= trim($value['STREET']) . '","';
				$query .= trim($value['CITY']) . '","';
				$query .= trim($value['POSTALCODE']) . '","';
				$query .= trim($value['COUNTRY']) . '"';
				$query .= ')';
				$this->db->query($query);
				$query = 'SELECT id FROM operating_values WHERE name="firmInfo" AND value0="Adress" AND module_name = "EcmSysInfos" AND ';
				$query .= '   value2 = "' . $value['POSITION'];
				$query .= '" AND value3 = "' . trim($value['NAME']);
				$query .= '" AND value4 = "' . trim($value['STREET']);
				$query .= '" AND value5 = "' . trim($value['CITY']);
				$query .= '" AND value6 = "' . trim($value['POSTALCODE']);
				$query .= '" AND value7 = "' . trim($value['COUNTRY']) . '"';
				$return = $this->db->query($query);
				$row = $this->db->fetchByAssoc($return);
				$arrayin[] = $row['id'];
			} else {
				$query = 'UPDATE operating_values SET ';
				$query .= '   value2 = "' . $value['POSITION'];
				$query .= '", value3 = "' . trim($value['NAME']);
				$query .= '", value4 = "' . trim($value['STREET']);
				$query .= '", value5 = "' . trim($value['CITY']);
				$query .= '", value6 = "' . trim($value['POSTALCODE']);
				$query .= '", value7 = "' . trim($value['COUNTRY']);
				$query .= '" WHERE id="' . $value['ID'] . '"';
				$this->db->query($query);
				$arrayin[] = $value['ID'];
			}
		}
		$stringIn = '(';
		//delete old adress
		if (count($arrayin) > 0) {
			foreach ($arrayin as $key => $value) {
				if ($key == 0) {
					$stringIn .=$value;
				} else {
					$stringIn .= ',' . $value;
				}
			}
			$stringIn .= ')';
			$query = 'DELETE FROM operating_values WHERE id NOT IN ' . $stringIn . ' AND name="firmInfo" AND value0="Adress" AND module_name = "EcmSysInfos"';
			$this->db->query($query);
		}
		$this->setAdress();
	}

	function saveWWW($www) {
		$this->www = trim($www);
		$query = '';
		if ($this->www_id == null) {
			$query = 'INSERT INTO operating_values (name,value0,value9,module_name) VALUES ("firmInfo","WWW","' . $this->www . '", "EcmSysInfos")';
		} else {
			$query = 'UPDATE operating_values SET value9="' . $this->www . '" where id="' . $this->www_id . '"';
		}
		$this->db->query($query);
	}

	function saveRegisterAdress($register_adress) {
		$this->register_adress = $register_adress;
		$query = '';
		if ($this->register_adress['ID'] == null || $this->register_adress['ID'] == '') {
			$query = 'INSERT INTO operating_values (name,module_name,value0,value1,value2,value3,value4,value5,value6,value7,value8,value9,text0) '
					. ' VALUES ("firmInfo","EcmSysInfos","RegisterAdress",'
					. '"' . trim($this->register_adress['STREET']) . '",'
					. '"' . trim($this->register_adress['LOCAL']) . '",'
					. '"' . trim($this->register_adress['HOME']) . '",'
					. '"' . trim($this->register_adress['CITY']) . '",'
					. '"' . trim($this->register_adress['POSTALCODE']) . '",'
					. '"' . trim($this->register_adress['MAIL']) . '",'
					. '"' . trim($this->register_adress['COMMUNITY']) . '",'
					. '"' . trim($this->register_adress['DISTRICT']) . '",'
					. '"' . trim($this->register_adress['STATE']) . '",'
					. '"' . trim($this->register_adress['COUNTRY']) . '"'
					. ')';
		} else {
			$query = 'UPDATE operating_values SET '
					. 'value1="' . trim($this->register_adress['STREET']) . '"'
					. ',value2="' . trim($this->register_adress['LOCAL']) . '"'
					. ',value3="' . trim($this->register_adress['HOME']) . '"'
					. ',value4="' . trim($this->register_adress['CITY']) . '"'
					. ',value5="' . trim($this->register_adress['POSTALCODE']) . '"'
					. ',value6="' . trim($this->register_adress['MAIL']) . '"'
					. ',value7="' . trim($this->register_adress['COMMUNITY']) . '"'
					. ',value8="' . trim($this->register_adress['DISTRICT']) . '"'
					. ',value9="' . trim($this->register_adress['STATE']) . '"'
					. ',text0="' . trim($this->register_adress['COUNTRY']) . '"'
					. ' WHERE id="' . $this->register_adress['ID'] . '"';
		}
		$this->db->query($query);
	}

	function saveCorrespondenceAdress($correspondence_adress) {
		$this->correspondence_adress = $correspondence_adress;
		$query = '';
		if ($this->correspondence_adress['ID'] == null || $this->correspondence_adress['ID'] == '') {
			$query = 'INSERT INTO operating_values (name,module_name,value0,value1,value2,value3,value4,value5,value6,value7,value8,value9,text0) '
					. ' VALUES ("firmInfo","EcmSysInfos","CorrespondenceAdress",'
					. '"' . trim($this->correspondence_adress['STREET']) . '",'
					. '"' . trim($this->correspondence_adress['LOCAL']) . '",'
					. '"' . trim($this->correspondence_adress['HOME']) . '",'
					. '"' . trim($this->correspondence_adress['CITY']) . '",'
					. '"' . trim($this->correspondence_adress['POSTALCODE']) . '",'
					. '"' . trim($this->correspondence_adress['MAIL']) . '",'
					. '"' . trim($this->correspondence_adress['COMMUNITY']) . '",'
					. '"' . trim($this->correspondence_adress['DISTRICT']) . '",'
					. '"' . trim($this->correspondence_adress['STATE']) . '",'
					. '"' . trim($this->correspondence_adress['COUNTRY']) . '"'
					. ')';
		} else {
			$query = 'UPDATE operating_values SET '
					. 'value1="' . trim($this->correspondence_adress['STREET']) . '"'
					. ',value2="' . trim($this->correspondence_adress['LOCAL']) . '"'
					. ',value3="' . trim($this->correspondence_adress['HOME']) . '"'
					. ',value4="' . trim($this->correspondence_adress['CITY']) . '"'
					. ',value5="' . trim($this->correspondence_adress['POSTALCODE']) . '"'
					. ',value6="' . trim($this->correspondence_adress['MAIL']) . '"'
					. ',value7="' . trim($this->correspondence_adress['COMMUNITY']) . '"'
					. ',value8="' . trim($this->correspondence_adress['DISTRICT']) . '"'
					. ',value9="' . trim($this->correspondence_adress['STATE']) . '"'
					. ',text0="' . trim($this->correspondence_adress['COUNTRY']) . '"'
					. ' WHERE id="' . $this->correspondence_adress['ID'] . '"';
		}
		$this->db->query($query);
	}
    
	function saveEmailSettings() {
	    
	    $query = 'UPDATE operating_values SET value1 = "' . $_POST['email_hostPort'] . '", value2 = "' .$_POST['email_login'] . '",
	             value3 = "' . $this->encrypt($_POST['email_password'],$_POST['email_login']) . '", value4 = "' .$_POST['email_address'] . '", value5 = "' .$_POST['autentication_type'] . '", value6="'.$_POST['email_address_replay'].'" where id="18"';
	    $this->db->query($query);
	    require_once 'include/ECM/EcmSendPdfButton/EcmSendPdfButton.inc';
	    $t = new EcmSendPdfButton('Users', '','','');
	    $t->setAdress('outtervision@gmail.com');
	  //  $t->setAdress('slawomir.chojnicki@gmail.com');
	    $t->setSubject('test');
	    $t->setBody('asdasd');
	    $success = false;
	    $success= $t->sendEmail();
	    if($success==1){
	        return 1;
	    } else {
	        $query = 'UPDATE operating_values SET value1 = "", value2 = "", value3 = "" where id="18"';
	     //   $this->db->query($query);
	        return 0;
	    }
	}
	
	function getEmailSettings(){
	    $query="select value1,value2,value3,value4,value5,value6 from operating_values where id=18";
	    $zap=$this->db->query($query);
	    $b=$this->db->fetchByAssoc($zap);
	    $b['value3']=$this->decrypt(    $b['value3'],    $b['value2']);
	    return $b;
	}
	
        
        
	public function encrypt($data, $secret)
	{
	    //Generate a key from a hash
	    $key = md5(utf8_encode($secret), true);
	
	    //Take first 8 bytes of $key and append them to the end of $key.
	    $key .= substr($key, 0, 8);
	
	    //Pad for PKCS7
	    $blockSize = mcrypt_get_block_size('tripledes', 'ecb');
	    $len = strlen($data);
	    $pad = $blockSize - ($len % $blockSize);
	    $data .= str_repeat(chr($pad), $pad);
	
	    //Encrypt data
	    $encData = mcrypt_encrypt('tripledes', $key, $data, 'ecb');
	
	    return base64_encode($encData);
	}
	
	public function decrypt($data, $secret)
	{
	    //Generate a key from a hash
	    $key = md5(utf8_encode($secret), true);
	
	    //Take first 8 bytes of $key and append them to the end of $key.
	    $key .= substr($key, 0, 8);
	
	    $data = base64_decode($data);
	
	    $data = mcrypt_decrypt('tripledes', $key, $data, 'ecb');
	
	    $block = mcrypt_get_block_size('tripledes', 'ecb');
	    $len = strlen($data);
	    $pad = ord($data[$len-1]);
	
	    return substr($data, 0, strlen($data) - $pad);
	}
	
	function saveContactInfo($contact) {
		$arrayin = array();
		foreach ($contact as $key => $value) {
			if (!isset($value['ID']) || $value['ID'] == '') {
				$query = 'INSERT INTO operating_values (name,value0,value7,value8,value9,module_name) VALUES ("firmInfo","ContactInfo","' . $value['POSITION'] . '","' . trim($value['NAME']) . '","' . trim($value['VALUE']) . '", "EcmSysInfos")';
				$this->db->query($query);
				$query = 'SELECT id FROM operating_values WHERE name="firmInfo" AND value0="ContactInfo" AND module_name = "EcmSysInfos" AND ';
				$query .= '" AND value9 = "' . trim($value['VALUE']);
				$query .= '" AND value8 = "' . trim($value['NAME']);
				$query .= '" AND value7 = "' . $value['POSITION'] . '"';
				$return = $this->db->query($query);
				$row = $this->db->fetchByAssoc($return);
				$arrayin[] = $row['id'];
			} else {
				$query = 'UPDATE operating_values SET value7 = "' . $value['POSITION'] . '", value8 = "' . trim($value['NAME']) . '", value9 = "' . trim($value['VALUE']) . '" where id="' . $value['ID'] . '"';
				$this->db->query($query);
				$arrayin[] = $value['ID'];
			}
		}
		$stringIn = '(';
		//delete old adress
		if (count($arrayin) > 0) {
			foreach ($arrayin as $key => $value) {
				if ($key == 0) {
					$stringIn .=$value;
				} else {
					$stringIn .= ',' . $value;
				}
			}
			$stringIn .= ')';
			$query = 'DELETE FROM operating_values WHERE id NOT IN ' . $stringIn . ' AND name="firmInfo" AND value0="ContactInfo" AND module_name = "EcmSysInfos"';
			$this->db->query($query);
		}
		$this->setContactInfo();
	}

	function getKRS() {
		return $this->krs;
	}
	
	function getFormatNumberForModule($modulename){
		$return = $this->db->query("SELECT value0 FROM operating_values WHERE id = (SELECT value1 from operating_values WHERE value2='". $modulename ."' AND name='headersDocuments' AND module_name='EcmSysInfos' and value4='pl_pl')");
		$row = $this->db->fetchByAssoc($return);
		return $row['value0'];
	}
	
	function getHeaderForModule($modulename, $language='pl_pl'){
		$return = $this->db->query("SELECT text0 from operating_values WHERE value2='". $modulename ."' AND value4='". $language ."'AND name='headersDocuments' AND module_name='EcmSysInfos'");
		$row = $this->db->fetchByAssoc($return);
		return html_entity_decode($row['text0']);
	}
	
	function getFooterForModule($modulename, $language='pl_pl'){
		$return = $this->db->query("SELECT text1 from operating_values WHERE value2='". $modulename ."' AND value4='". $language ."' AND name='headersDocuments' AND module_name='EcmSysInfos'");
		$row = $this->db->fetchByAssoc($return);
		return html_entity_decode($row['text1']);
	}

	function getCorrespondenceAdress() {
		return $this->correspondence_adress;
	}

	function getRegisterAdress() {
		return $this->register_adress;
	}

	function getContactInfo() {
		return $this->contact_info;
	}

	function getWWW() {
		return $this->www;
	}

	function getRegon() {
		return $this->regon;
	}

	function getNip() {
		return $this->nip;
	}

	function getBanks() {
		return $this->banks;
	}

	function getBankAccoutnsList() {
		$tmp = array();
		foreach ($this->banks as $key => $value) {
			$tmp[] = $value['NUMBER'];
		}
		return $tmp;
	}

	function getShortName() {
		return $this->short_name;
	}

	function getName() {
		return $this->name;
	}

	function getInvoiceNumberFormat() {
		return $this->invoice_number_format;
	}

	function getAdress() {
		return $this->adress;
	}

	function setBanks() {
		$query = 'SELECT id ID, value7 POSITION, value2 NAMESHORT, value8 NAME, value9 NUMBER, value3 CURRENCY, value4 SWIFT, value5 IBAN FROM operating_values WHERE name = "firmInfo" AND value0 = "bankAccount" AND module_name="EcmSysInfos" ORDER BY value7';
		$return = $this->db->query($query);
		$this->banks = array();
		while ($row = $this->db->fetchByAssoc($return)) {
			$this->banks[] = $row;
		}
	}
	
	function getCurrencies(){
	  $zap=$this->db->query("select id,name from currencies where deleted=0");
	  $list=array();
	  $tmp['id']='PLN';
	  $tmp['name']='PLN';
	  $list[]=$tmp;
	  while($dane=$this->db->fetchByAssoc($zap)){
	      $list[]=$dane;
	  }
	  return $list;
	}
	
	function setAdress() {
		$query = 'SELECT id ID, value2 POSITION, value3 NAME, value4 STREET, value5 CITY, value6 POSTALCODE, value7 COUNTRY, value8 PHONE, value9 FAX FROM operating_values WHERE name = "firmInfo" AND value0 = "Adress" AND module_name="EcmSysInfos" ORDER BY value2';
		$return = $this->db->query($query);
		$this->adress = array();
		while ($row = $this->db->fetchByAssoc($return)) {
			$this->adress[] = $row;
		}
	}

	function setContactInfo() {
		$query = 'SELECT id ID, value7 POSITION, value8 NAME, value9 VALUE FROM operating_values WHERE name = "firmInfo" AND value0 = "ContactInfo" AND module_name="EcmSysInfos" ORDER BY value7';
		$return = $this->db->query($query);
		$this->contact_info = array();
		while ($row = $this->db->fetchByAssoc($return)) {
			$this->contact_info[] = $row;
		}
	}

	function fill_in_additional_detail_fields() {
		parent::fill_in_additional_detail_fields();
	}

}
