<?php
/****************************************
/*  Author  : Kvvaradha
/*  Module  : Kvcodes CRM
/*  E-mail  : admin@kvcodes.com
/*  Version : 1.0
/*  Http    : www.kvcodes.com
*****************************************/
define ('SS_KVCRM', 254<<8);
class KvcodesCRM_app extends application{
    var $apps;
    function __construct()  {
		global $path_to_root;
        parent::__construct("crm", _($this->help_context = "&CRM"));
		$projects = $tasks = false;
		if(file_exists($path_to_root."/modules/KvcodesCRM/projects"))
			$projects = true;
		if(file_exists($path_to_root."/modules/KvcodesCRM/tasks"))
			$tasks = true;

		Update_current_user_session();
		if(isset($_SESSION['wa_current_user']->type) && $_SESSION['wa_current_user']->type == ST_CUSTOMER) { // Customers
			$this->add_module(_("Transactions"));
			$this->add_lapp_function(0, _("Attachments"), 'modules/KvcodesCRM/manage/attachments.php', 'CRM_ATTACHMENTS', MENU_ENTRY);			

			if($projects)
				$this->add_rapp_function(0, _('Projects'), '/modules/KvcodesCRM/projects/', 'CRM_PROJECTS', MENU_ENTRY);
			if($tasks)
				$this->add_lapp_function(0, _("Tasks"), 'modules/KvcodesCRM/tasks/', 'CRM_TASKS', MENU_ENTRY);
			$this->add_lapp_function(0, _("Create Ticket"), 'modules/KvcodesCRM/tickets/new_ticket.php?', 'CRM_TICKETS', MENU_ENTRY);	
			$this->add_module(_("Inquires"));	
			$this->add_lapp_function(1, _("Ticket Inquiry"), 'modules/KvcodesCRM/tickets/', 'CRM_TICKETS', MENU_INQUIRY);	
			$this->add_lapp_function(1, _("Customers Inquiry"), 'modules/KvcodesCRM/inquires/customer_inquiry.php', 'CRM_CUSTOMERS', MENU_INQUIRY);	
							
			$this->add_lapp_function(1, _("Estimates Inquiry"), 'modules/KvcodesCRM/inquires/proposal_estimate_inquiry.php?type=33', 'CRM_CUSTOMERS', MENU_INQUIRY);				
			$this->add_lapp_function(1, _("Proposals Inquiry"), 'modules/KvcodesCRM/inquires/proposal_estimate_inquiry.php?type=34', 'CRM_CUSTOMERS', MENU_INQUIRY);				
										
			if($projects)
				$this->add_rapp_function(1, _("Projects Inquiry"), 'modules/KvcodesCRM/projects/inquiry.php', 'CRM_PROJECTS', MENU_INQUIRY);
			if($tasks)
				$this->add_rapp_function(1, _("Tasks Inquiry"), 'modules/KvcodesCRM/tasks/inquiry.php', 'CRM_TASKS', MENU_INQUIRY);
					
			$this->add_module(_("Maintainance"));
			$this->add_lapp_function(2, _("Profile"), 'modules/KvcodesCRM/manage/customers.php', 'CRM_CUSTOMERS', MENU_ENTRY);        
			$this->add_lapp_function(2, _("Branches"), 'modules/KvcodesCRM/manage/customer_branches.php', 'CRM_CUSTOMERS', MENU_ENTRY);        
					
		} elseif( isset($_SESSION['wa_current_user']->type) && $_SESSION['wa_current_user']->type == ST_SUPPLIER) { 	// Suppliers 
			$this->add_module(_("Transactions"));
			$this->add_lapp_function(0, _("Attachments"), 'modules/KvcodesCRM/manage/attachments.php', 'CRM_ATTACHMENTS', MENU_ENTRY);			

			if($tasks)
				$this->add_lapp_function(0, _("Tasks"), 'modules/KvcodesCRM/tasks/', 'CRM_TASKS', MENU_ENTRY);
			$this->add_module(_("Inquires"));	
			$this->add_lapp_function(1, _("Suppliers Inquiry"), 'modules/KvcodesCRM/inquires/supplier_inquiry.php', 'CRM_SUPPLIERS', MENU_INQUIRY);	
			$this->add_lapp_function(1, _("Ticket Inquiry"), 'modules/KvcodesCRM/tickets/', 'CRM_TICKETS', MENU_INQUIRY);	
			if($tasks)
				$this->add_rapp_function(1, _("Tasks Inquiry"), 'modules/KvcodesCRM/tasks/inquiry.php', 'CRM_TASKS', MENU_INQUIRY);
			$this->add_module(_("Maintainance"));
			$this->add_rapp_function(2, _("Profile"), 'modules/KvcodesCRM/manage/suppliers.php', 'CRM_SUPPLIERS', MENU_ENTRY);

			$this->add_lapp_function(0, _("Create Ticket"), 'modules/KvcodesCRM/tickets/new_ticket.php?', 'CRM_TICKETS', MENU_ENTRY);	

		} else {  // Staff and Adminstrator 
			$this->add_module(_("Transactions"));

			$this->add_lapp_function(0, _("Estimates"), 'modules/KvcodesCRM/estimates.php?NewEstimate=Yes', 'CRM_ESTIMATES', MENU_ENTRY);
			$this->add_rapp_function(0, _("Proposals"), 'modules/KvcodesCRM/estimates.php?NewProposal=Yes', 'CRM_PROPOSAL', MENU_ENTRY);
			$this->add_rapp_function(0, _("Project Invoice"), 'modules/KvcodesCRM/invoice.php?NewInvoice=Yes', 'CRM_PROPOSAL', MENU_ENTRY);
			$this->add_lapp_function(0, _("Add And Manage Leads"), 'modules/KvcodesCRM/manage/leads.php', 'CRM_LEADS', MENU_ENTRY);	
			$this->add_rapp_function(0, _("Add Manage Opportunites"), 'modules/KvcodesCRM/manage/opportunities.php', 'CRM_OPPORTUNITIES', MENU_ENTRY);
			$this->add_lapp_function(0, _("Attachments"), 'modules/KvcodesCRM/manage/attachments.php', 'CRM_ATTACHMENTS', MENU_ENTRY);			

			if($projects)
				$this->add_rapp_function(0, _('Projects'), '/modules/KvcodesCRM/projects/', 'CRM_PROJECTS', MENU_ENTRY);
			if($tasks)
				$this->add_lapp_function(0, _("Tasks"), 'modules/KvcodesCRM/tasks/', 'CRM_TASKS', MENU_ENTRY);
			$this->add_lapp_function(0, _("Create Ticket"), 'modules/KvcodesCRM/tickets/new_ticket.php?', 'CRM_TICKETS', MENU_ENTRY);	
			$this->add_module(_("Inquires"));				
				
			$this->add_lapp_function(1, _("Reminders"), 'modules/KvcodesCRM/inquires/reminders.php', 'CRM_ACTIVITIES', MENU_INQUIRY);				
			$this->add_lapp_function(1, _("Calls"), 'modules/KvcodesCRM/inquires/reminders.php?medium=1', 'CRM_ACTIVITIES', MENU_INQUIRY);				
			$this->add_rapp_function(1, _("Meetings"), 'modules/KvcodesCRM/inquires/reminders.php?medium=2', 'CRM_ACTIVITIES', MENU_INQUIRY);	
			$this->add_lapp_function(1, _("Ticket Inquiry"), 'modules/KvcodesCRM/tickets/', 'CRM_TICKETS', MENU_INQUIRY);			
			$this->add_lapp_function(1, _("Contacts Inquiry"), 'modules/KvcodesCRM/inquires/contacts_inquiry.php', 'CRM_CUSTOMERS', MENU_INQUIRY);				
			$this->add_lapp_function(1, _("Customers Inquiry"), 'modules/KvcodesCRM/inquires/customer_inquiry.php', 'CRM_CUSTOMERS', MENU_INQUIRY);				
			$this->add_lapp_function(1, _("Suppliers Inquiry"), 'modules/KvcodesCRM/inquires/supplier_inquiry.php', 'CRM_SUPPLIERS', MENU_INQUIRY);	
			$this->add_lapp_function(1, _("Estimates Inquiry"), 'modules/KvcodesCRM/inquires/proposal_estimate_inquiry.php?type=33', 'CRM_CUSTOMERS', MENU_INQUIRY);				
			$this->add_lapp_function(1, _("Proposals Inquiry"), 'modules/KvcodesCRM/inquires/proposal_estimate_inquiry.php?type=34', 'CRM_CUSTOMERS', MENU_INQUIRY);			
			$this->add_rapp_function(1, _("Opportunities Inquiry"), 'modules/KvcodesCRM/inquires/opportunities_inquiry.php', 'CRM_OPPORTUNITIES', MENU_INQUIRY);
			$this->add_rapp_function(1, _("Leads Inquiry"), 'modules/KvcodesCRM/inquires/leads_inquiry.php', 'CRM_LEADS', MENU_INQUIRY);				
									
			if($projects)
				$this->add_rapp_function(1, _("Projects Inquiry"), 'modules/KvcodesCRM/projects/inquiry.php', 'CRM_PROJECTS', MENU_INQUIRY);
			if($tasks)
				$this->add_rapp_function(1, _("Tasks Inquiry"), 'modules/KvcodesCRM/tasks/inquiry.php', 'CRM_TASKS', MENU_INQUIRY);
			$this->add_rapp_function(1, _("CRM Reports"), 'reporting/reports_main.php?Class=11&REP_ID=120', 'CRM_REPORTS', MENU_INQUIRY);
			$this->add_rapp_function(1, _("Email Log"), 'modules/KvcodesCRM/inquires/email_log.php?', 'CRM_EMAILS', MENU_INQUIRY);
					
		    $this->add_module(_("Maintainance"));            
		            
			$this->add_lapp_function(2, _("Add Manage Users"), 'modules/KvcodesCRM/manage/users.php', 'CRM_SETTINGS', MENU_ENTRY);        
			$this->add_lapp_function(2, _("Customers"), 'modules/KvcodesCRM/manage/customers.php', 'CRM_CUSTOMERS', MENU_ENTRY);        
			$this->add_lapp_function(2, _("Customer Branches"), 'modules/KvcodesCRM/manage/customer_branches.php', 'CRM_CUSTOMERS', MENU_ENTRY);        
			$this->add_rapp_function(2, _("Suppliers"), 'modules/KvcodesCRM/manage/suppliers.php', 'CRM_SUPPLIERS', MENU_ENTRY);
			$this->add_rapp_function(2, _("Custom Header"), 'modules/KvcodesCRM/manage/custom_header.php', 'CRM_SUPPLIERS', MENU_ENTRY);
			$this->add_rapp_function(2, _("Custom Fields"), 'modules/KvcodesCRM/manage/custom_fields.php', 'CRM_SUPPLIERS', MENU_ENTRY);
			if($_SESSION['wa_current_user']->access == 2 || $_SESSION['wa_current_user']->username == 'root' || $_SESSION['wa_current_user']->username == 'kvcodes' ){
				$this->add_lapp_function(2, _("Pick Lists"), 'modules/KvcodesCRM/picklists.php', 'CRM_SETTINGS', MENU_ENTRY);
				$this->add_lapp_function(2, _("Pick Types"), 'modules/KvcodesCRM/PickType.php', 'CRM_SETTINGS', MENU_ENTRY);
			}
			$this->add_rapp_function(2, _("Email Templates"), 'modules/KvcodesCRM/manage/email_templates.php', 'CRM_EMAILS', MENU_MAINTENANCE); 
			$this->add_rapp_function(2, _("Import Export CSV"), 'modules/KvcodesCRM/import_export.php', 'CRM_SETTINGS', MENU_MAINTENANCE); 
			$this->add_rapp_function(2, _("Backup and Restore"), 'modules/KvcodesCRM/backups.php', 'CRM_SETTINGS', MENU_MAINTENANCE); 
			$this->add_rapp_function(2, _("Documentation"), 'modules/KvcodesCRM/docs/', 'CRM_SETTINGS', MENU_MAINTENANCE); 

			$this->add_rapp_function(2, _("Settings"), 'modules/KvcodesCRM/manage/crm_settings.php', 'CRM_SETTINGS', MENU_MAINTENANCE);  
			$this->add_rapp_function(2, _("Translation"), 'modules/KvcodesCRM/findgettext.php', 'CRM_SETTINGS', MENU_MAINTENANCE);     
		}		 
			
        $this->add_extensions();			
	}

    function GetSingleValue($tablename, $column_single, $conditions=null, $order_by = null, $sql=false){
		$sql0 = "SELECT ".$column_single." FROM ".TB_PREF.$tablename." WHERE 1=1";
		if($conditions){
			foreach($conditions as $key=>$value){
				$sql0 .= " AND {$key} = '${value}'";
			}
		}
		
		if($order_by != null) {
			$sql0 .=" ORDER BY ";
			foreach($order_by as $key=>$value){
				$sql0 .= " {$key} ${value}";
			}
		}
		if($sql)
			return $sql0;
		$result = db_query($sql0, "could not get sales type");

		$row = db_fetch_row($result);

		$data = @unserialize(base64_decode($row[0]));
		if ($data !== false) {
		    return unserialize(base64_decode($row[0]));
		}else
			return $row[0];
	}
} 

function CRM_GetSingleValue($tablename, $column_single, $conditions=null, $order_by = null, $sql=false){
		$sql0 = "SELECT ".$column_single." FROM ".TB_PREF.$tablename." WHERE 1=1";
		if($conditions){
			foreach($conditions as $key=>$value){
				$sql0 .= " AND {$key} = '${value}'";
			}
		}
		
		if($order_by != null) {
			$sql0 .=" ORDER BY ";
			foreach($order_by as $key=>$value){
				$sql0 .= " {$key} ${value}";
			}
		}
		if($sql)
			return $sql0;
		$result = db_query($sql0, "could not get {$tablename}");
		$row = db_fetch_row($result);
		$data = @unserialize(base64_decode($row[0]));
		if ($data !== false) {
		    return unserialize(base64_decode($row[0]));
		}elseif(isset($row[0]))
			return $row[0];
		else
			return false;
	}


class hooks_KvcodesCRM extends hooks {	
	 var $module_name = 'KvcodesCRM';	 
	 function install_tabs($app) {
        $app->add_application(new KvcodesCRM_app);
    }
	/*  Install additonal menu options provided by module	*/
	function install_options($app) {
		global $path_to_root;
		switch($app->id) {
			case 'orders':
				$counter =0;
				foreach ($app->modules[2]->lappfunctions as  $row) {	
					if($row->label =='Add and Manage &Customers'){
						$app->modules[2]->lappfunctions[$counter] = new app_function(_("Add and Manage &Customers"), 'modules/KvcodesCRM/manage/customers.php?', 'SA_CUSTOMER', MENU_ENTRY);
					}
					if($row->label =='Customer &Branches'){     
						$app->modules[2]->lappfunctions[$counter] = new app_function(_("Customer &Branches"), 'modules/KvcodesCRM/manage/customer_branches.php', 'SA_CUSTOMER', MENU_ENTRY);
					}
					$counter++;
				}
				break;
				case 'AP':
				$counter =0;
				foreach ($app->modules[2]->lappfunctions as  $row) {	
					if($row->label =='&Suppliers'){
						$app->modules[2]->lappfunctions[$counter] = new app_function(_("&Suppliers"), 'modules/KvcodesCRM/manage/suppliers.php', 'SA_SUPPLIER', MENU_ENTRY);
					}
					$counter++;
				}
				break;
				case 'system':
				$counter =0;
				foreach ($app->modules[0]->lappfunctions as  $row) {	
					if($row->label =='&User Accounts Setup'){
						$app->modules[0]->lappfunctions[$counter] = new app_function(_("&User Accounts Setup"),'modules/KvcodesCRM/manage/users.php', 'SA_USERS', MENU_ENTRY);
					}
					$counter++;
				}
			break;
		}
	}

	function install_access()	{
		 $security_sections[SS_KVCRM]    = _("CRM");
		
		 $security_areas['CRM_LEADS'] = array(SS_KVCRM|1, _("Leads")); 
         $security_areas['CRM_OPPORTUNITIES'] = array(SS_KVCRM|2, _("Opportunities"));        
         $security_areas['CRM_ATTACHMENTS'] = array(SS_KVCRM|3, _("Attachments"));    
		 $security_areas['CRM_PROJECTS'] = array(SS_KVCRM|4, _("Projects"));
         $security_areas['CRM_TASKS'] = array(SS_KVCRM|5, _("Tasks"));
         $security_areas['CRM_ACTIVITIES'] = array(SS_KVCRM|13, _("Activities"));
         $security_areas['CRM_SETTINGS'] = array(SS_KVCRM|6, _("Settings")); 
         $security_areas['CRM_ESTIMATES'] = array(SS_KVCRM|7, _("Estimates")); 
         $security_areas['CRM_PROPOSAL'] = array(SS_KVCRM|8, _("Proposals")); 
         $security_areas['CRM_CUSTOMERS'] = array(SS_KVCRM|9, _("Customers")); 
         $security_areas['CRM_SUPPLIERS'] = array(SS_KVCRM|10, _("Suppliers")); 
         $security_areas['CRM_REPORTS'] = array(SS_KVCRM|11, _("Reports")); 
         $security_areas['CRM_EMAILS'] = array(SS_KVCRM|12, _("Email Templates")); 
         $security_areas['CRM_COMMENTS'] = array(SS_KVCRM|13, _("Comments")); 
         $security_areas['CRM_TICKETS'] = array(SS_KVCRM|14, _("Tickets")); 
         $security_areas['CRM_SALESTRANSVIEW'] = array(SS_KVCRM|15, _("Sales Transactions")); 
         $security_areas['CRM_SUPPTRANSVIEW'] = array(SS_KVCRM|16, _("Purchase Transactions")); 
		         
		return array($security_areas, $security_sections);
	}
	
	 function activate_extension($company, $check_only=true)  {
        global $db_connections, $path_to_root, $systypes_array;

        if(!defined('ST_SALESESTIMATE')){
			// $fp = fopen($path_to_root.'/includes/types.inc', 'a');//opens file in append mode  
			// fwrite($fp, PHP_EOL."define('ST_SALESESTIMATE',33);".PHP_EOL."define('ST_SALESPROPOSAL',34);".PHP_EOL."define('ST_PROJECTINVOICE',36);".PHP_EOL."define('ST_LEADS',43);".PHP_EOL."define('ST_OPPORTUNITIES',44);".PHP_EOL."define('ST_TASKS',45);".PHP_EOL."define('ST_PROJECT',46);".PHP_EOL."define('ST_CUSTOMER_BRANCH',47);".PHP_EOL.(!defined('ST_EMPLOYEE') ? "define('ST_EMPLOYEE',47);".PHP_EOL : ''));  
			// fclose($fp);  	
			$types_ = file_get_contents($path_to_root.'/includes/types.inc');
			$change_content = "define('ST_MANURECEIVE', 29);

			".(!isset($systypes_array['ST_SALESESTIMATE']) ? 'define("ST_SALESESTIMATE",33);'.PHP_EOL : '' ) 
			.(!isset($systypes_array['ST_SALESPROPOSAL']) ? 'define("ST_SALESPROPOSAL",34);'.PHP_EOL : '' ) 
			.(!isset($systypes_array['ST_PROJECTINVOICE']) ? 'define("ST_PROJECTINVOICE",36);'.PHP_EOL : '' ) 
			.(!isset($systypes_array['ST_LEADS']) ? 'define("ST_LEADS",43);'.PHP_EOL : '' ) 
			.(!isset($systypes_array['ST_OPPORTUNITIES']) ? 'define("ST_OPPORTUNITIES",44);'.PHP_EOL : '' ) 
			.(!isset($systypes_array['ST_TASKS']) ? 'define("ST_TASKS",45);'.PHP_EOL : '' ) 
			.(!isset($systypes_array['ST_PROJECT']) ? 'define("ST_PROJECT",46);'.PHP_EOL : '' ) 
			.(!isset($systypes_array['ST_CUSTOMER_BRANCH']) ? 'define("ST_CUSTOMER_BRANCH",47);'.PHP_EOL : '' ) ;
			//.(!isset($systypes_array['ST_EMPLOYEE']) ? 'define("ST_EMPLOYEE",47);'.PHP_EOL : '' ) ;

		$types_inc = str_replace("define('ST_MANURECEIVE', 29);", $change_content, $types_); 	
		file_put_contents($path_to_root.'/includes/types.inc', $types_inc);
		
		//transactions_db
		$transactions_db = file_get_contents($path_to_root.'/admin/db/transactions_db.inc');
		$transactions_db_change = "case     ST_SUPPLIER    : return array(TB_PREF.'suppliers', null, 'supplier_id', 'supp_ref', null);

        case 	ST_SALESESTIMATE : return array(TB_PREF.'kv_crm_sales_orders', 'trans_type', 'order_no', 'reference', 'ord_date');
        case 	ST_SALESPROPOSAL : return array(TB_PREF.'kv_crm_sales_orders', 'trans_type', 'order_no', 'reference', 'ord_date');
		case 	ST_PROJECTINVOICE : return array(TB_PREF.'kv_crm_sales_orders', 'trans_type', 'order_no', 'reference', 'ord_date');";

		$transactions_db__inc = str_replace('case     ST_SUPPLIER    : return array(TB_PREF."suppliers", null, "supplier_id", "supp_ref", null);', $transactions_db_change, $transactions_db); 	
		file_put_contents($path_to_root.'/admin/db/transactions_db.inc', $transactions_db__inc);

		//sysnames.inc
		$sysnames = file_get_contents($path_to_root.'/includes/sysnames.inc');

		$change = "ST_DIMENSION => _('Dimension'),

		    ".(!isset($systypes_array['ST_SALESESTIMATE']) ? "ST_SALESESTIMATE => _('Sales Estimate'),".PHP_EOL : '' )
		    .(!isset($systypes_array['ST_SALESPROPOSAL']) ? "ST_SALESPROPOSAL => _('Sales Proposal'),".PHP_EOL : '' )
		    .(!isset($systypes_array['ST_PROJECTINVOICE']) ? "ST_PROJECTINVOICE => _('Project Invoice')," .PHP_EOL : '' );

				$sysnames_inc = str_replace('ST_DIMENSION => _("Dimension"),', $change, $sysnames); 	
				$sysnames_inc = str_replace("ST_DIMENSION => _('Dimension'),", $change, $sysnames); 	
			file_put_contents($path_to_root.'/includes/sysnames.inc', $sysnames_inc);		
		} 

        $updates = array(
            'update.sql' => array('KvcodesCRM')
        );
        $result = db_query("SHOW COLUMNS FROM `".TB_PREF."debtor_trans` LIKE 'next_over_due'", "can't get mysql result");
		$exists = (db_num_rows($result))?TRUE:FALSE;
		if(!$exists)
			db_query("ALTER TABLE `".TB_PREF."debtor_trans` ADD `next_over_due` DATE NOT NULL DEFAULT '0000-00-00' AFTER `tax_included`", "can't alter debtor_trans Table");

		$result = db_query("SHOW COLUMNS FROM `".TB_PREF."crm_persons` LIKE 'user_id'", "can't get mysql result");
		$exists = (db_num_rows($result))?TRUE:FALSE;
		if(!$exists)
			db_query("ALTER TABLE `".TB_PREF."crm_persons` ADD `user_id` INT(11) NOT NULL DEFAULT '0' AFTER `id`", "can't alter crm_persons Table");

		$query1 = db_query("SELECT id FROM ".TB_PREF."reflines WHERE trans_type = 33 AND `default`=1", "Can't get the type in it");

		if(db_num_rows($query1) ==0)
			db_query("INSERT INTO `".TB_PREF."reflines` (`id`, `trans_type`, `prefix`, `pattern`, `description`, `default`, `inactive`) VALUES (NULL, '33', '', '{001}/{YYYY}', '', '1', '0');", "Can't get the result");
		
		$query2 = db_query("SELECT id FROM ".TB_PREF."reflines WHERE trans_type = 34 AND `default`=1", "Can't get the type in it");
		if(db_num_rows($query2) ==0)
			db_query("INSERT INTO `".TB_PREF."reflines` (`id`, `trans_type`, `prefix`, `pattern`, `description`, `default`, `inactive`) VALUES (NULL, '34', '', '{001}/{YYYY}', '', '1', '0');", "Can't get the result");
		
		$query3 = db_query("SELECT id FROM ".TB_PREF."reflines WHERE trans_type = 36 AND `default`=1", "Can't get the type in it");
		if(db_num_rows($query3) ==0)
			db_query("INSERT INTO `".TB_PREF."reflines` (`id`, `trans_type`, `prefix`, `pattern`, `description`, `default`, `inactive`) VALUES (NULL, '36', '', '{001}/{YYYY}', '', '1', '0');", "Can't get the result");
		
		//ALTER TABLE `0_debtor_trans` ADD `next_over_due` DATE NOT NULL DEFAULT '0000-00-00' AFTER `tax_included`;
		//ALTER TABLE `0_crm_persons` ADD `user_id` INT(11) NOT NULL DEFAULT '0' AFTER `id`;

        return $this->update_databases($company, $updates, $check_only);
    }

    function deactivate_extension($company, $check_only=true)  {
        global $db_connections;

        $updates = array(
            'drop.sql' => array('ugly_hack') // FIXME: just an ugly hack to clean database on deactivation
        );
       
        return $this->update_databases($company, $updates, $check_only);
    }
	
	function db_postwrite(&$cart, $type) {
    	global $path_to_root;
    	
    	if($type == ST_SALESINVOICE && CRM_GetSingleValue('kv_crm_option', 'option_value', array('option_name' => 'send_email_invoice')) == 1 ){
    		include_once($path_to_root.'/modules/KvcodesCRM/reports/rep107.php');
    		$trans_no = array_keys($cart->trans_no)[0];    		
    		if($trans_no > 0 ){
    			$_POST['trans_no'] = $trans_no;
    			print_invoices($trans_no);
    		}
    	} elseif($type == ST_CUSTPAYMENT && CRM_GetSingleValue('kv_crm_option', 'option_value', array('option_name' => 'send_email_payment')) == 1 ){
    		include_once($path_to_root.'/modules/KvcodesCRM/reports/rep112.php');
    		$trans_no = $cart->trans_no;    		
    		if($trans_no > 0 ){
    			$_POST['trans_no'] = $trans_no;
    			print_receipts($trans_no);
    		}
    	} else {
    		// display_error(json_encode($cart));
    	}
    }       
}

function Update_current_user_session(){
	if(!isset($_SESSION['wa_current_user']->contact)){
		$sql = "SELECT pr.*, con.type, con.entity_id FROM ".TB_PREF."crm_persons AS pr LEFT JOIN ". TB_PREF."crm_contacts AS con ON con.person_id = pr.id AND (con.type = 'customer' OR con.type= 'supplier') WHERE pr.user_id = ".$_SESSION['wa_current_user']->user;
		$res = db_query($sql, "Can't get result of crm persons");

		if(db_num_rows($res) > 0 ){
			if($row = db_fetch($res)){
				$_SESSION['wa_current_user']->contact = $row['id'];
				$_SESSION['wa_current_user']->person = $row['entity_id'];
				$_SESSION['wa_current_user']->type = (($row['type'] == 'customer' || $row['type'] == 'cust_branch'  ) ? ST_CUSTOMER : ($row['type'] == 'supplier' ? ST_SUPPLIER : 99)); 
				$_SESSION['wa_current_user']->user_type = (($row['type'] == 'customer' || $row['type'] == 'cust_branch'  ) ? ST_CUSTOMER : ($row['type'] == 'supplier' ? ST_SUPPLIER : 99)); 
			}
		} else {
			$_SESSION['wa_current_user']->contact = -1;
			$_SESSION['wa_current_user']->user_type =99; 
			//return false;
		}
	}
	//display_error(json_encode($_SESSION['wa_current_user']));
}