<?php
/**********************************************************************
***********************************************************************/
function calculate_task_remaining_totals($line_items)
{
        $task_costs = array();
        
        foreach ($line_items as $line_item)
        {
            if($line_item['high_value_item']){
                $item_reference_cost = $line_item['reference_cost'];
                $item_cost = $line_item['standard_cost'];
            }
            else{
                $item_reference_cost = $line_item['standard_cost'];
                $item_cost = $line_item['standard_cost'];
            }
            
            $line_remaining_qty = $line_item['requested_qty'] - $line_item['total_issued_qty'];
            $this_tran_qty = $line_item['qty'];
            
            if($line_remaining_qty < 0){
                $line_remaining_cost = 0;
                $line_remaining_reference_cost = 0;                
            }
            else{
                $line_remaining_cost = $line_remaining_qty * $item_cost;
                $line_remaining_reference_cost = $line_remaining_qty * $item_reference_cost;
            }
            
            if(isset($line_item['charging_cost'])){
                $charging_cost = $line_item['charging_cost'];
            }
            else{
                $charging_cost = $item_cost;
            }
            
            $line_charging_cost = $this_tran_qty * $charging_cost;
            
            add_to_task_cost($task_costs, $line_item['task_id'], $line_remaining_cost, $line_remaining_reference_cost, $line_charging_cost);
        }
        
        get_task_cost_details($task_costs);
        
        return $task_costs;
}

function calculate_document_total($line_items, $use_reference_costs = false)
{
        $remaining_total = 0;
        foreach ($line_items as $line_item)
        {
            if($use_reference_costs){
                if($line_item->high_value_item){
                    $item_cost = $line_item->reference_cost;
                }
                else{
                    $item_cost = $line_item->standard_cost;
                }
            }
            else{
                $item_cost = $line_item->standard_cost;
            }
            $line_remaining_total = ($line_item->tran_qty * $line_item->convertion_factor)* $item_cost;
            $remaining_total += $line_remaining_total;
        }
        
        return $remaining_total;
}


function validate_transaction_quantity_details($cart)
{
    foreach ($cart->line_items as $line_item) {
        $vilqd_msg = validate_item_line_quantity_details($line_item->line_ref, $line_item->stock_id, $line_item->stock_control_method, $line_item->tran_qty, $line_item->lot_details);
        if($vilqd_msg['success'] !== true){
            return $vilqd_msg;
        } 
    }
    
    return array("success" => true, "message" => "");
}

function validate_item_line_quantity_details($line_ref, $stock_id, $stock_control_method, $line_tran_qty, $lot_details)
{
        if($stock_control_method == SKCM_LOTS){
            $villq_msg = validate_item_line_lot_quantities($line_ref, $stock_id, $line_tran_qty, $lot_details);
            if($villq_msg['success'] !== true){
                return $villq_msg;
            } 
        }
        elseif($stock_control_method == SKCM_SERIAL_NOS){
            $vilsnq_msg = validate_item_line_serial_no_quantities($line_ref, $stock_id, $line_tran_qty, $lot_details);
            if($vilsnq_msg['success'] !== true){
                return $vilsnq_msg;
            }             
        }
        
        return array("success" => true, "message" => "");
}

function add_item_line_quantity_detail_movements($tran_type, $tran_no, $location, 
                                                $date, &$line_item, $increase, $reference = '')
{
    if($line_item->stock_control_method == SKCM_NORMAL){
         return array("success" => true, "tran_no" => $tran_no, "message" => "NORMAL stock control control item");
    }
    elseif($line_item->stock_control_method == SKCM_LOTS){
        $alt = add_lot_transactions($line_item->lot_details, $tran_type, $tran_no, $location, 
                                    $line_item->stock_id, $line_item->convertion_factor, $date, $increase, 
                                    $reference);
        return $alt;
    }
    elseif($line_item->stock_control_method == SKCM_SERIAL_NOS){
        $asnt = add_serial_no_transactions($line_item->lot_details, $tran_type, $tran_no, $location, 
                                    $line_item->stock_id, $date, $increase, $reference);
        return $asnt;
    }
    else{
        return array("success" => false, "tran_no" => $tran_no, "message" => "Unknown stock control methos");
    }
    
}

function get_task_cost_details(&$task_costs)
{
    foreach ($task_costs as &$task_line){
        $task_record = get_task_record($task_line['task_id']); 

        if(!(isset($task_record['task_id']) && $task_record['task_id'] > 0)){
            $msg = "UNEXPECTED: Budget id ".$task_line['task_id']." has been deleted.";
            display_error_cancel($msg);
            exit();
        }
        $task_line['task_description'] = $task_record['description'];
        $task_line['budget'] = $task_record['budget'];
        $task_line['budget_used'] = $task_record['budget_used'];
        $task_line['budget_allocated'] = $task_record['budget_allocated'];
        $task_line['row_state'] = $task_record['row_state'];
    }
}

function create_folder_index_file($folder_path)
{
    $index = "<?php\nheader(\"Location: ../index.php\");\n?>";
    
    @mkdir($folder_path);
    $f = @fopen("$folder_path/index.php", "wb");
    @fwrite($f, $index);
    @fclose($f);
}

function get_movement_type_linked_field_values($linked_field_type, $linked_field_id, $group_company_code='') {
    global $inventory_movement_type_linked_fields;
    
    $path_to_root = "..";    
    $path_to_root_2 = "../..";    
    $linked_field_values = "";

    switch ($linked_field_type) {
        case IMLF_CUSTOMER:
            if (file_exists($path_to_root . "/sales/includes/db/customers_db.inc")) {
                include_once($path_to_root . "/sales/includes/db/customers_db.inc");
            } else {
                include_once($path_to_root_2 . "/sales/includes/db/customers_db.inc"); 
            }
            
            $customer = get_customer($linked_field_id);
                if (is_array($customer)) {
                    $linked_field_values = array("field_name" => $inventory_movement_type_linked_fields[IMLF_CUSTOMER], "value" => $customer['name']);
                } else {
                    $linked_field_values = array("field_name" => $inventory_movement_type_linked_fields[IMLF_CUSTOMER], "value" => 'No customer');
                }
                
            break;
            
        case IMLF_SUPPLIER:
            if (file_exists($path_to_root . "/purchasing/includes/db/suppliers_db.inc")) {
                include_once($path_to_root . "/purchasing/includes/db/suppliers_db.inc");
            } else {
                include_once($path_to_root_2 . "/purchasing/includes/db/suppliers_db.inc"); 
            }
            
            $supplier = get_supplier($linked_field_id);
                if (is_array($supplier)) {
                    $linked_field_values = array("field_name" => $inventory_movement_type_linked_fields[IMLF_SUPPLIER], "value" => $supplier['supp_ref'].' - '.$supplier['supp_name']);
                } else {
                    $linked_field_values = array("field_name" => $inventory_movement_type_linked_fields[IMLF_SUPPLIER], "value" => 'No supplier');
                }
                
            break;
            
        case IMLF_EMPLOYEE:
            if (file_exists($path_to_root . "/payroll/includes/db/employees_db.inc")) {
                include_once($path_to_root . "/payroll/includes/db/employees_db.inc");
            } else {
                include_once($path_to_root_2 . "/payroll/includes/db/employees_db.inc"); 
            }
            
            if (file_exists($path_to_root . "/includes/db/group_companies_db.inc")) {
                include_once($path_to_root . "/includes/db/group_companies_db.inc");
            } else {
                include_once($path_to_root_2 . "/includes/db/group_companies_db.inc"); 
            }
            
            if ($group_company_code == '') {
                $group_company_code = get_default_group_company_code();
            }
            
            $employee = get_group_company_employee_formatted_long_name($group_company_code, $linked_field_id);
                $linked_field_values = array("field_name" => $inventory_movement_type_linked_fields[IMLF_EMPLOYEE], "value" => $employee);
                
            break;
        
        case IMLF_VEHICLE:
            if (file_exists($path_to_root . "/transport/includes/db/vehicles_db.inc")) {
                include_once($path_to_root . "/transport/includes/db/vehicles_db.inc"); 
            } else {
                include_once($path_to_root_2 . "/transport/includes/db/vehicles_db.inc"); 
            }
            
            $vehicle_name = get_vehicle_formatted_name($linked_field_id);
                $linked_field_values = array("field_name" => $inventory_movement_type_linked_fields[IMLF_VEHICLE], "value" => $vehicle_name);
           
            break;
        
        case IMLF_ASSET: 
            if (file_exists($path_to_root . "/assets/includes/db/assets_db.inc")) {
                include_once($path_to_root . "/assets/includes/db/assets_db.inc");
            } else {
                include_once($path_to_root_2 . "/assets/includes/db/assets_db.inc"); 
            }
            
            $asset_name = get_asset_formatted_name($linked_field_id);
                $linked_field_values = array("field_name" => $inventory_movement_type_linked_fields[IMLF_ASSET], "value" => $asset_name);
           
            break;
            
        default:
            $linked_field_values = array("field_name" => "", "value" => "");
            break;
    }
    
    return $linked_field_values;
       
}

function convert_to_base_unit_qty($tran_unit_qty, $tran_unit_convertion_factor)
{
    return $tran_unit_qty * $tran_unit_convertion_factor;
}

function convert_to_tran_unit_qty($base_unit_qty, $tran_unit_convertion_factor)
{
    return $base_unit_qty / $tran_unit_convertion_factor;
}

function display_quantity_cells($guid_name, $tran_type, $line_ref, $stock_id, 
                                $stock_control_method, $cell_prefix, $suggested_qty, $tran_unit, 
                                $dec = 2, $items_table_name = "items_table")
{
    global $Ajax;
    
    $unit_of_parent = $tran_unit;
    
    if($stock_control_method == SKCM_LOTS){
        $Ajax->activate($items_table_name);
        //$lot_popup = viewer_link('', 'inventory/manage/lot_list.php?stock_id='.$_POST['stock_id'].'&popup=1&parent=tran_qty', '', '',  ICON_VIEW);
        //$lot_popup = viewer_link('', 'inventory/manage/lot_list.php?value_ref='.get_post($guid_name).'&stock_id='.$stock_id.'&popup=1&parent='.$cell_prefix.'tran_qty'.'&unit_of_parent='.$unit_of_parent, '', '',  ICON_VIEW);
        $lot_popup = viewer_link('', 'inventory/manage/lot_list.php?value_ref='.$guid_name.'&line_ref='.$line_ref.
                                '&stock_id='.$stock_id.'&popup=1&parent='.$cell_prefix.'tran_qty&unit_of_parent='.$unit_of_parent, '', '',  ICON_VIEW);
        
        qty_cells(null, $cell_prefix.'tran_qty', $suggested_qty, null, $lot_popup, $dec);
    }
    elseif($stock_control_method == SKCM_SERIAL_NOS){
        $Ajax->activate($items_table_name);
        //$lot_popup = viewer_link('', 'inventory/manage/lot_list.php?stock_id='.$_POST['stock_id'].'&popup=1&parent=tran_qty', '', '',  ICON_VIEW);
        $lot_popup = viewer_link('', 'inventory/manage/serial_no_list.php?value_ref='.get_post($guid_name).
                                '&stock_id='.$stock_id.'&popup=1&parent='.$cell_prefix.'tran_qty'.'&unit_of_parent='.$unit_of_parent, '', '',  ICON_VIEW);
        
        qty_cells(null, $cell_prefix.'tran_qty', $suggested_qty, null, $lot_popup, $dec);
    }
    else{
//        $Ajax->activate($items_table_name);
        $Ajax->activate($cell_prefix.'tran_qty');
        qty_cells(null,$cell_prefix.'tran_qty', $suggested_qty, null, null, $dec);
    }
}

//--------------------------------------------------------------------------------------------

function get_selected_lot_serial_info($guid_name, $line_item)
{   
    if(isset($_POST[$guid_name])){
        $lot_info = get_session_variable("lot_info#".$_POST[$guid_name]);
        $name = $line_item->line_ref."_".$line_item->stock_id;
        if(isset($lot_info[$name])){
            return $lot_info[$name];
        }
        else{
            return "";
        }
    }
    else{
        return "";
    }
}

function set_line_ref(&$cart, $line_no)
{
    $line_ref = get_post("line_ref", 0);
    $cart->line_items[$line_no]->line_ref = $line_ref;
    
    $cart->set_next_line_ref();
    
}


function get_yes_no_name($value)
{
    if($value == 1){
        return "Yes";
    }
    else{
        return "No";
    }
}


function is_outside_payroll_entries_allowed_date_range($entry_date)
{
    $entry_date = date2sql($entry_date);
    $module = "payroll";
    
    $entries_allowed_from_date = get_module_parameter_value($module, "entries_allowed_from_date");
    $entries_allowed_to_date = get_module_parameter_value($module, "entries_allowed_to_date");
    
    if($entry_date < $entries_allowed_from_date){
        return array("success" => false, "message" => "Entered date is before the transactions allowed from date");
    }
    
    if($entry_date > $entries_allowed_to_date){
        return array("success" => false, "message" => "Entered date is after the transactions allowed to date");
    }
    
    return array("success" => true, "message" => "");
}


function all_sites_belongs_to_the_project($project_id, $line_items)
{
    $s = "";
    foreach ($line_items as $line_item) {
        if(isset($line_item->site_id) && $line_item->site_id != 0){
            $s .= $line_item->site_id.",";
        }
        elseif(isset($line_item->project_site_id) && $line_item->project_site_id != 0){
            $s .= $line_item->project_site_id.",";
        }
    }
    
    if($s == ""){
        return array("success" => true, "message" => "");
    }
    
    $s = substr($s,0,-1);
    $site_projects = get_site_projects($s);
    while ($row = db_fetch($site_projects)) {
        if($row['project_id'] != $project_id){
            return array("success" => false, "message" => "Job ".$row["site_name"]." does not belong to the selected project.");
        }
    }
    
    return array("success" => true, "message" => "");
}


function all_tasks_belongs_to_the_project($project_id, $line_items)
{
    $t = "";
    foreach ($line_items as $line_item) {
        $t .= $line_item->task_id.", ";
    }
    
    $t = substr($t,0,-1);
    $task_projects = get_task_projects($t);
    while ($row = db_fetch($task_projects)) {
        if($row['project_id'] != $project_id){
            return array("success" => false, "message" => "Task or budget ".$row["task_name"]." does not belong to the selected project.");
        }
    }
    
    return array("success" => true, "message" => "");
}


function validate_admin_functions_access_code($access_code, $type = '')
{
    if(strlen(trim($access_code)) <= 1){
        return false;
    }
    
    $system_value = get_sys_prefs_parameter_value('admin_functions_access_code');
    if($access_code == $system_value){
        return true;
    }
    else{
        return false;
    }
}

function get_workorder_display_status($row)
{
    global $approval_statuses;
    
    if($row['id'] < 0){
        return "Draft";
    }
    
    if($row['closed']){
        return '<i>'._('Closed').'</i>' ;
    }
    
    if($row["released"] == 0){
        if(isset($row['display_status']) && $row['display_status'] != ""){
            return $row['display_status'];
        }
        else{
            return $approval_statuses[$row['approval_status']];
        }
    }
    
    if($row["released"]){
        return "Released";
    }
		
    return "Confimed";
}


function get_group_company_employee_formatted_long_name($company_code, $employee_code)
{
    $emp = get_group_company_employee($company_code, $employee_code);
    if(isset($emp['employee_code'])){
        return ("[".$emp['employee_code']."] - ". $emp['initials']." ".$emp['last_name']." (".$emp['first_name'].")");
    }
    else{
        return "[".$employee_code."] - Can not access the database of this employee";
    }

}

function get_source_pr_ids_string($source_type, $source_tran_no)
{
    $result = get_source_pr_ids($source_type, $source_tran_no);

    $pr_source_ids_string = "";
    while($source_id = db_fetch($result))
    {
        $pr_source_ids_string .= get_supplier_trans_view_str(ST_PURCH_REQ,$source_id['pr_no'], $source_id['pr_no'])." ";
    }

    return trim($pr_source_ids_string);
}

function calculate_common_item_taxes($line_amont, $tax_group_id, $tax_included)
{
//    $shipping_cost = 0;
//    $items = array();
//	$line_amonts = array();
//        if($shipping_cost==null)
//
//    $items[] = $item;
//    $line_amonts[] = $line_amont;		

//    $taxes = get_tax_for_items($items, $line_amonts, $shipping_cost, $tax_group_id, $tax_included);
    
    $ret_tax_array = get_tax_group_items_as_array($tax_group_id);
    
    foreach($ret_tax_array as $k=>$t){
        $ret_tax_array[$k]['Net'] = 0;
    }
    
    $dec = 2;
    calculate_item_taxes($ret_tax_array, $line_amont, $tax_included, $dec, $ret_tax_array);

	return $ret_tax_array;	
}

function write_to_log_file($file_name, $text)
{
    global $installed_path;
    
    $last_visit_date = "";
    if(isset($_SESSION['wa_current_user']->last_visit_date)){
        $last_visit_date = $_SESSION['wa_current_user']->last_visit_date;
    }
    
    $loginname = "";
    if(isset($_SESSION['wa_current_user']->loginname)){
        $loginname = $_SESSION['wa_current_user']->loginname;
    }  
    
    $log_filename = $file_name."_".$last_visit_date."_".$loginname.".txt"; 
    $log_filepathname = $installed_path . '/tmp/program_logs/'.$log_filename;
    file_put_contents($log_filepathname, format_microtime('Y-m-d H:i:s.u')."\r\n",FILE_APPEND);
    file_put_contents($log_filepathname, $text."\r\n"."\r\n",FILE_APPEND);
}

function get_duedate_from_payment_terms($date, $payment_term_id)
{
//	$date = get_class($trans) == 'purch_order' ? $trans->orig_order_date : $trans->tran_date;

	if (!is_date($date))
	{
		$date = Today();
	}
    $payment_term = get_payment_terms($payment_term_id);
	if ($payment_term['day_in_following_month'])
	{ /*Its a day in the following month when due */
		$due_date = add_days(end_month($date), $payment_term["day_in_following_month"]);
	}
	else
	{ /*Use the Days Before Due to add to the invoice date */
		$due_date = add_days($date, $payment_term["days_before_due"]);
	}
    
    return $due_date;
}


function calculate_duedate($payment_term_id, $document_date)
{
	if (!is_date($document_date))
	{
		return new_doc_date();
	}
	
	$myrow = get_payment_terms($payment_term_id);
	
	if (!$myrow){
		return $document_date;
        }

	if ($myrow['day_in_following_month'] > 0){
		$duedate = add_days(end_month($document_date), $myrow['day_in_following_month']);
        }
	else{
		$duedate = add_days($document_date, $myrow['days_before_due']);
        }
	return $duedate;
}


function get_gl_account_formatted_name($account_code)
{
    $account = get_gl_account($account_code);
    if(isset($account['account_code'])){
        return ("[".$account['account_code']."] - ". $account['account_name']);
    }
    else{
        return "Unknown account code [".$account_code."]";
    }

}


function get_group_company_employee_formatted_name_by_id($company_code, $employee_id)
{
    $emp = get_group_company_employee_by_id($company_code, $employee_id);
    if(isset($emp['employee_code'])){
        return ("[".$emp['employee_code']."] - ". $emp['initials']." ".$emp['last_name']." (".$emp['first_name'].")");
    }
    else{
        return "[".$employee_id."] - Can not access the database of this employee";
    }

}


function get_customer_formatted_name($debtor_no) 
{
    $customer = get_customer($debtor_no);	

    if(isset($customer['debtor_no']) && $customer['debtor_no'] > 0){
        return "[".$customer['debtor_ref']."] - ". $customer['name'];
    } else {
        return "Could not find a customer for id $debtor_no";
    }
}


function get_supplier_formatted_name($supplier_id) 
{
    $supplier = get_supplier($supplier_id);	
    if(isset($supplier['supplier_id']) && $supplier['supplier_id'] > 0){
        return "[".$supplier['supp_ref']."] - ". $supplier['supp_name'];
    } else {
        return "Could not find a supplier for id $supplier";
    }
}

function get_asset_formatted_name($asset_id) 
{
    $asset = get_asset($asset_id);	

    if(isset($asset['asset_id']) && $asset['asset_id'] > 0){
        return $asset['asset_code']." - ". $asset['description']." (".$asset['asset_id'].")";
    } else {
        return "Could not find an asset for id $asset_id";
    }
}

function get_asset_depreciation_run_formatted_name($asset_run_id) 
{
    $run = get_asset_depreciation_run_details($asset_run_id);

    if(isset($run['id']) && $run['id'] > 0){
        return $run['period_end_date']." - ". $run['description']." (".$run['id'].")";
    } else {
        return "Could not find an asset depreciation run for id $run";
    }
}

function get_vehicle_formatted_name($vehicle_id) 
{
    $vehicle = get_vehicle($vehicle_id);

    if(isset($vehicle['id']) && $vehicle['id'] > 0){
        return $vehicle['plate_number']." - ".$vehicle['description'];
    } else {
        return "Could not find a vehicle for id $vehicle_id";
    }
}

function get_stock_item_formatted_name($stock_id, $editable=null, $stock_master_description = "", $transaction_saved_description='') {
    
    $display_description = $item = "";
    
    if($editable === null){
        $item = get_stock_item_description_info($stock_id);
        $editable = $item['editable'];
    }
   
    if($editable){
        if($transaction_saved_description != ''){
            $display_description = $transaction_saved_description;
        }
        else{
            if(!is_array($item)){
                $item = get_stock_item_description_info($stock_id);
            }
            $display_description = $item['description'];
        }
    }
    else{
        if($stock_master_description != ''){
            $display_description = $stock_master_description;
        }
        else{
            if(!is_array($item)){
                $item = get_stock_item_description_info($stock_id);
            }
            $display_description = $item['description'];            
        }
        
    }  
   
    return $stock_id." - ".$display_description;
   
}



function get_project_formatted_name($project_id) 
{
    $project = get_project_record($project_id);
    if(is_array($project)){
        return "[".$project['project_code']."] - ".$project['description']." (".$project['project_id'].")";
    } else {
        return "Could not find project details for the project $project_id";
    }
}

function get_project_formatted_code($project_id, $project_code) 
{
    if($project_id > 0 && strlen($project_code) > 0){
        return $project_code."(".$project_id.")";
    } else {
        return "";
    }
}


function validate_movement_type_data($movement_type_id_post_name, $linked_field_id_post_name)
{
    global $path_to_root;
    
        if (! (isset($_POST[$movement_type_id_post_name]) && $_POST[$movement_type_id_post_name] > 0)) {
            $message = 'Select a movement type.';
            return array("success"=>false,"message"=>$message, "set_focus"=>$movement_type_id_post_name);
        } 
        else {
            include_once($path_to_root . "/inventory/includes/db/movement_types_db.inc");
            
            $mv_tp = get_movement_type($_POST[$movement_type_id_post_name]);
            if ($mv_tp['linked_field'] == IMLF_NOT_LINKED) {
                return array("success"=>true,"message"=>"", "set_focus"=>""); 
            }
            else{

                global $inventory_movement_type_linked_fields;
                    
                switch ($mv_tp['linked_field']) {
                    case IMLF_EMPLOYEE:
                        if((strlen($_POST[$linked_field_id_post_name]) <= 2)) {
                            $message = ( _('Select an '.$inventory_movement_type_linked_fields[$mv_tp['linked_field']].'.')); 
                            return array("success"=>false,"message"=>$message, "set_focus"=>$linked_field_id_post_name);
                        }
                        return array("success"=>true,"message"=>"", "set_focus"=>""); 
                    case IMLF_ASSET:
                        if (! ($_POST[$linked_field_id_post_name] > 0)) { 
                            $message = ( _('Select an '.$inventory_movement_type_linked_fields[$mv_tp['linked_field']].'.'));
                            return array("success"=>false,"message"=>$message, "set_focus"=>$linked_field_id_post_name);
                        }
                        return array("success"=>true,"message"=>"", "set_focus"=>"");                         
                    default :
                        if (! ($_POST[$linked_field_id_post_name] > 0)) { 
                            $message = ( _('Select a '.$inventory_movement_type_linked_fields[$mv_tp['linked_field']].'.'));
                            return array("success"=>false,"message"=>$message, "set_focus"=>$linked_field_id_post_name);
                        }
                        return array("success"=>true,"message"=>"", "set_focus"=>"");                         
                }
                    
                if ($mv_tp['linked_field'] == IMLF_ASSET) {
                    include_once($path_to_root . "/assets/includes/db/assets_db.inc"); 
                    $asset_row = get_asset($_POST[$linked_field_id_post_name]);
                    if ($asset_row['type'] == AT_VEHICLE) {
                        $message = 'Selected asset is a Vehicle. Only the assets of types "Fixed Asset" and "Tool" are allowed under this Movement Type.';
                        return array("success"=>false,"message"=>$message, "set_focus"=>$linked_field_id_post_name);
                    }
                    return array("success"=>true,"message"=>"", "set_focus"=>"");     
                }
            }
        }
}

function get_expense_category_expense_item_name($expense_category_id=0, $expense_item_id='') {
    
    global $path_to_root;
    
    $expense_item_name = '';
            switch ($expense_category_id) {
                case EC_PETTY_CASH_EXPENSE:
                    $expense_item_name = '';
                    break;
                case EC_STOCK_ITEM_RECEIPT:
                    include_once($path_to_root . "/inventory/includes/db/petty_cash_item_receive_db.inc"); 
                    $receipts_res = get_petty_cash_item_receive_items_by_source_type(ST_I_OWE_YOU_BATCH, $expense_item_id);
                    $receipts = db_fetch($receipts_res);
                    $receipt_tran_no = 0;
                    if(is_array($receipts)){
                        $receipt_tran_no = $receipts['trans_no'];
                    }
                    $link = get_inventory_trans_view_str(ST_PETTY_CASH_ITEM_RECEIPT, $receipt_tran_no, "Received items");
                    $expense_item_name = $link;
                    break;
                case EC_VEHICLE_MAINTENANCE:
                    include_once($path_to_root . "/transport/includes/db/vehicles_db.inc");  
                    $expense_item_name = get_vehicle_formatted_name($expense_item_id);
                    break;
                case EC_UTILITY_ITEM:
                    include_once($path_to_root . "/admin/db/list_values_db.inc");  
                    $utility_item = get_listvalue_by_id($expense_item_id);
                    $expense_item_name = $utility_item['value_name'];
                    break;
                case EC_ASSET_MAINTENANCE:
                    include_once($path_to_root . "/assets/includes/db/assets_db.inc");  
                    $expense_item_name = get_asset_formatted_name($expense_item_id);
                    break;

                default:
                    break;
            }
            
            return $expense_item_name;
       
}


function get_bank_account_formatted_name($bank_account_id)
{
    $bank_account = get_bank_account($bank_account_id);    

    $s = ( $bank_account['bank_account_number']." - ".$bank_account['bank_account_name']);
    return $s;

}

function get_employee_formatted_long_name($employee_code)
{
    $emp = get_employee($employee_code);
    if(isset($emp['employee_code'])){
        return ("[".$emp['employee_code']."] - ". $emp['initials']." ".$emp['last_name']." (".$emp['first_name'].")");
    }
    else{
        return "[".$employee_code."] - Can not access the database of this employee";
    }
}

function get_employee_formatted_long_name_by_id($employee_id)
{
    $emp = get_employee_record_by_id($employee_id);
    if(isset($emp['employee_code'])){
        return ("[".$emp['employee_code']."] - ". $emp['initials']." ".$emp['last_name']." (".$emp['first_name'].")");
    }
    else{
        return "[".$employee_id."] - Can not access the database of this employee";
    }
}

function get_float_formatted_name($float_id)
{
    $float_name= get_petty_cash_float_name($float_id);
    return $float_name;
}

function get_cheque_details($trans_type, $trans_no)
{    
    global $path_to_root;

    include_once($path_to_root . "/gl/includes/db/print_cheques_db.inc");
    
    $a = array();
    
    $details = get_printed_cheque_details($trans_type, $trans_no);
    if(is_array($details)){
        $a['cheque_no'] = $details['cheque_no'];
        $a['payment_type'] = $details['payment_type'];
        if($a['payment_type'] == 0){
            $a['payment_type_name'] = "Cheque"; 
        }elseif($a['payment_type'] == 1){
            $a['payment_type_name'] = "Online"; 
        }else{
            $a['payment_type_name'] = "Unknown"; 
        }
    }
    else{
        $a['cheque_no'] = "Not printed";
        $a['payment_type'] = "";
        $a['payment_type_name'] = ""; 
    }
    
    return $a;
}


function get_voucher_info($trans_type, $trans_no)
{    
    global $path_to_root;

    include_once($path_to_root . "/gl/includes/db/print_payment_vouchers_db.inc");
    
    $a = array();
    
    $details = get_payment_voucher_record($trans_no, $trans_type);
    if(is_array($details)){
        $a['voucher_code'] = $details['voucher_code'];
        $a['voucher_type_id'] = $details['voucher_type_id'];
        $a['voucher_reference'] = $details['voucher_reference'];
        if(strlen($a['voucher_reference']) > 0){
            $a['display_text'] = $a['voucher_code']." (".$a['voucher_reference'].")";
        }else{
            $a['display_text'] = $a['voucher_code'];
        }
    }
    else{
        $a['voucher_code'] = "Not printed";
        $a['voucher_type_id'] = "";
        $a['voucher_reference'] = "";
        $a['display_text'] = $a['voucher_code'];
    }
    
    return $a;
}



function get_fiscal_year_formatted_name($year_id) 
{
    $fiscalyear = get_fiscalyear($year_id); 

    if(isset($fiscalyear['id']) && $fiscalyear['id'] > 0){
        $status = $fiscalyear['closed'] ? _('Closed') : _('Active');
        return sql2date($fiscalyear['begin'])." - ".sql2date($fiscalyear['end'])." (".$status.")";
    } else {
        return "Could not find a fiscal year for id $year_id";
    }
}


function check_invalid_characters($value) 
{
   if (strstr($value, " ") || strstr($value,"'") || 
        strstr($value, "+") || strstr($value, "\"") || 
        strstr($value, "&") || strstr($value, "\t")||
        strstr($value, "%"))    
   {
       $message = "Only numbers and stabdard characters are allowed in key code values";
       return array("success"=>false,"message"=>$message);     
   }else{       
       return array("success"=>true,"message"=>"");     
   }
}

function build_all_item_units_array() {
    $units_array = array();
    
        $result = get_all_item_units_units();
            while ($row = db_fetch($result)) {
                $units_array[$row['unit_code']] = $row['unit_name'];
            }
            
        return $units_array;
}

function get_payroll_run_formatted_name($payroll_run_id) 
{
    $payroll_run = get_payroll_run_details($payroll_run_id)	;

    if(isset($payroll_run['id']) && $payroll_run['id'] > 0){
        return $payroll_run['description']." (".sql2date($payroll_run['period_start_date'])." - ".sql2date($payroll_run['period_end_date']).")";
    } else {
        return "Could not find details of payroll run #".$payroll_run_id;
    }
}