<?php


function display_fi_transaction_types()
{
    $batch_size = 10000000;
    $cutoff_date_ = $_POST['cutoff_date'];
    $cutoff_date = date2sql($cutoff_date_);
    
    start_table(TABLESTYLE);
    
    $th = array(_('Transaction Type'),_('New transactions'),_('Select'));              

    table_header($th);    
    
        display_fi_transaction_type_row('Inventory', $cutoff_date);   
        display_fi_transaction_type_row(ST_MATERIAL_ISSUE, $cutoff_date);   
        display_fi_transaction_type_row(ST_MATERIAL_RETURN, $cutoff_date);   
        display_fi_transaction_type_row(ST_SITE_MATERIAL_RETURN, $cutoff_date);   
        display_fi_transaction_type_row(ST_INVADJUST, $cutoff_date);   
        display_fi_transaction_type_row(ST_INVENTORY_RECEIPT, $cutoff_date);   
        display_fi_transaction_type_row(ST_INVENTORY_ISSUE, $cutoff_date);   
        display_fi_transaction_type_row(ST_STOCK_COUNT, $cutoff_date);   
        display_fi_transaction_type_row(ST_ITEM_COSTUPDATE, $cutoff_date);   
        display_fi_transaction_type_row(ST_DAILY_ITEM_ISSUE, $cutoff_date);   
        display_fi_transaction_type_row(ST_DAILY_ITEM_RETURN, $cutoff_date);              
        display_fi_transaction_type_row(ST_PETTY_CASH_ITEM_RECEIPT, $cutoff_date);  
        
        display_fi_transaction_type_row('General Ledger', $cutoff_date);
        display_fi_transaction_type_row(ST_UTILITY_BILLS, $cutoff_date); 
        display_fi_transaction_type_row(ST_UTILITY_BILL_CREDIT_NOTE, $cutoff_date);
        
        display_fi_transaction_type_row('Projects', $cutoff_date);
        display_fi_transaction_type_row(ST_PROJECT_INVOICE, $cutoff_date);
        display_fi_transaction_type_row(ST_PROJECT_CREDIT_NOTE, $cutoff_date);    
        display_fi_transaction_type_row(ST_SUBCONTRACTOR_INVOICE, $cutoff_date);
        display_fi_transaction_type_row(ST_SUBCONTRACTOR_CREDIT_NOTE, $cutoff_date);
        display_fi_transaction_type_row(ST_MISCELLANEOUS_PROJECT_COST, $cutoff_date);

        display_fi_transaction_type_row('Sales', $cutoff_date);
        display_fi_transaction_type_row(ST_SALESINVOICE, $cutoff_date);
        display_fi_transaction_type_row(ST_CUSTDELIVERY, $cutoff_date);
        display_fi_transaction_type_row(ST_CUSTOMER_PAYMENT_RETURN, $cutoff_date);
        display_fi_transaction_type_row(ST_CUSTCREDIT, $cutoff_date);
//        display_fi_transaction_type_row(ST_CUSTPAYMENT, $cutoff_date);
        
        display_fi_transaction_type_row('Purchasing', $cutoff_date);
        display_fi_transaction_type_row(ST_SUPPRECEIVE, $cutoff_date);
        display_fi_transaction_type_row(ST_SUPPINVOICE, $cutoff_date);
        display_fi_transaction_type_row(ST_SUPPCREDIT, $cutoff_date);
//        display_fi_transaction_type_row(ST_SUPPAYMENT, $cutoff_date);
        display_fi_transaction_type_row(ST_PR_ISSUE, $cutoff_date);
        display_fi_transaction_type_row(ST_PR_RETURN, $cutoff_date);
        
        display_fi_transaction_type_row('Petty Cash', $cutoff_date);
        display_fi_transaction_type_row(ST_PETTY_CASH_FLOAT_ADJ, $cutoff_date);
        display_fi_transaction_type_row(ST_PETTY_CASH_FLOAT_REIMBUR, $cutoff_date);
        display_fi_transaction_type_row(ST_I_OWE_YOU_BATCH, $cutoff_date);
        display_fi_transaction_type_row(ST_PETTY_CASH_DIRECT_PAYMENTS, $cutoff_date);
        display_fi_transaction_type_row(ST_I_OWE_YOU_PAYMENT, $cutoff_date);
        display_fi_transaction_type_row(ST_PETTY_CASH_PAYMENT, $cutoff_date);
        display_fi_transaction_type_row(ST_I_OWE_YOU_ADVANCES, $cutoff_date);
        
        display_fi_transaction_type_row('Assets', $cutoff_date);
        display_fi_transaction_type_row(ST_ASSET_QUANTITY_ADJUSTMENT, $cutoff_date);
        display_fi_transaction_type_row(ST_STOCK_ASSET_TRANSFER, $cutoff_date);

        display_fi_transaction_type_row('Transport', $cutoff_date);
        display_fi_transaction_type_row(ST_SUPPLIER_TRANSPORT_INVOICES, $cutoff_date);
        
        display_fi_transaction_type_row('Finance', $cutoff_date);
        display_fi_transaction_type_row(ST_COMP_LOAN_REPAYMENT, $cutoff_date);

//        $message = "(This has to be tested in live system. Please call Nalin when generating accounts for Payroll)";
//        display_fi_transaction_type_row("HR & Payroll "."<font color='red'>".$message."</font>", $cutoff_date);
//        display_fi_transaction_type_row(ST_PAYROLL, $cutoff_date);
        
//        display_fi_transaction_type_row('Assets');
//        display_fi_transaction_type_row(ST_TOOL_USAGE_CHARGE);
//        display_fi_transaction_type_row(ST_ASSET_DEPRECIATION);
//        display_fi_transaction_type_row(ST_ASSET_QUANTITY_ADJUSTMENT);
//        display_fi_transaction_type_row(ST_STOCK_ASSET_TRANSFER);
        
        

    end_table(2);
}

function display_fi_transaction_type_row($type, $cutoff_date)
{
    global $systypes_array;
    
    start_row();
    if(is_numeric($type)){
        label_cell(spaces(10).$systypes_array[$type]);
        
        if((!isset_post_string('CheckNewEntries') && !isset_post_string('GenerateFIAccountingEntries')) ||
                isset_post_string('CheckNewEntries')){
            $n = fi_get_remaining_transactions_count($type, $cutoff_date);
            if($n > 0){
//                label_cell(number_format($n, 0),'align=center'); 
                $link = get_fi_remaining_transactions_view_str($type, $cutoff_date, $n);
                label_cell($link,'align=center');
//                get_supplier_trans_view_str($type, $trans_no);
            }
            else{
                label_cell("-",'align=center');
            }
        }
        else{
            label_cell('');
        }
        check_cells('', 'select_fi_type_'.$type);
    }
    else{
        label_cell('<b>'.$type.'</b>', 'colspan=3');
    }
    end_row();
}

function can_generate_fi_entries($cutoff_date_, $batch_size){
    
    if(!is_date($cutoff_date_)){
        $message = "Cutoff date is not a valid date.";
        $setfocus = "cutoff_date";
        return array("success"=>false, "focus"=>$setfocus, "message"=>$message);
    }
    
    if($batch_size > 100){
        $message = "Maximum allowed number for batch size is 100.";
        $setfocus = "batch_size";
        return array("success"=>false, "focus"=>$setfocus, "message"=>$message);
    }
    
    return array("success"=>true, "message"=>"");
}
function generate_fi_entries($cutoff_date_, $batch_size=1)
{
     

    $timeout_at = time() + 1000;
//    $batch_no = create_next_fi_batch_no($cutoff_date_);
//    delete_task_cost_rebuild_task_details($cutoff_date);
    
    $group_id = strtotime(date("Y-m-d H:i:s"));
       
    // Inventory
    $msg = generate_transaction_type_fi_entries($group_id, ST_MATERIAL_ISSUE, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }    
    $msg = generate_transaction_type_fi_entries($group_id, ST_MATERIAL_RETURN, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }   
    $msg = generate_transaction_type_fi_entries($group_id, ST_SITE_MATERIAL_RETURN, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }  
    $msg = generate_transaction_type_fi_entries($group_id, ST_INVADJUST, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_INVENTORY_RECEIPT, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_INVENTORY_ISSUE, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_STOCK_COUNT, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_ITEM_COSTUPDATE, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_DAILY_ITEM_ISSUE, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_DAILY_ITEM_RETURN, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_PETTY_CASH_ITEM_RECEIPT, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;
    }    
    
    
    // GL
    $msg = generate_transaction_type_fi_entries($group_id, ST_UTILITY_BILLS, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_UTILITY_BILL_CREDIT_NOTE, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    
    $msg = generate_transaction_type_fi_entries($group_id, ST_PROJECT_INVOICE, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_PROJECT_CREDIT_NOTE, $cutoff_date_, $timeout_at, $batch_size);    
    if($msg["success"] !== true){
        return $msg;        
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_SUBCONTRACTOR_INVOICE, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_SUBCONTRACTOR_CREDIT_NOTE, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_MISCELLANEOUS_PROJECT_COST, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    
    $msg = generate_transaction_type_fi_entries($group_id, ST_SALESINVOICE, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_CUSTDELIVERY, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_CUSTOMER_PAYMENT_RETURN, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_CUSTCREDIT, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
//    $msg = generate_transaction_type_fi_entries($group_id, ST_CUSTPAYMENT, $cutoff_date_, $timeout_at, $batch_size);
//    if($msg["success"] !== true){
//        return $msg;        
//    }
    
    $msg = generate_transaction_type_fi_entries($group_id, ST_SUPPRECEIVE, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_SUPPINVOICE, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_SUPPCREDIT, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_SUPPAYMENT, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_PR_ISSUE, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_PR_RETURN, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    
    $msg = generate_transaction_type_fi_entries($group_id, ST_PETTY_CASH_FLOAT_ADJ, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_PETTY_CASH_FLOAT_REIMBUR, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_I_OWE_YOU_BATCH, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_PETTY_CASH_DIRECT_PAYMENTS, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_I_OWE_YOU_PAYMENT, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_PETTY_CASH_PAYMENT, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    $msg = generate_transaction_type_fi_entries($group_id, ST_I_OWE_YOU_ADVANCES, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    
    
    $msg = generate_transaction_type_fi_entries($group_id, ST_SUPPLIER_TRANSPORT_INVOICES, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    
    
    $msg = generate_transaction_type_fi_entries($group_id, ST_COMP_LOAN_REPAYMENT, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    
    // Assets
    $msg = generate_transaction_type_fi_entries($group_id, ST_ASSET_QUANTITY_ADJUSTMENT, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    } 
    
    $msg = generate_transaction_type_fi_entries($group_id, ST_STOCK_ASSET_TRANSFER, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    
    
    $msg = generate_transaction_type_fi_entries($group_id, ST_PAYROLL, $cutoff_date_, $timeout_at, $batch_size);
    if($msg["success"] !== true){
        return $msg;        
    }
    
    
//    generate_transaction_type_fi_entries($group_id, ST_TOOL_USAGE_CHARGE, $cutoff_date_, $batch_size);
//    generate_transaction_type_fi_entries($group_id, ST_ASSET_DEPRECIATION, $cutoff_date_);
//    generate_transaction_type_fi_entries($group_id, ST_ASSET_QUANTITY_ADJUSTMENT, $cutoff_date_, $batch_size);
    
    $fi_group = fi_get_group_summary($group_id);
    if(is_array($fi_group)){
        if($fi_group["no_of_batches"] == 1){
            $message = "Batch No ".$fi_group["min_batch_no"]." generated.";
            $success = true;
        }
        elseif($fi_group["no_of_batches"] > 1){
            $message = "Batches Nos ".$fi_group["min_batch_no"]." to ".$fi_group["max_batch_no"]." generated.";
            $success = true;
        }
        else{
            $message = "No FI Batches generated";
            $success = false;
        }
    }
    else{
        $message = "No FI Batches generated";
        $success = false;
    }
    
    return array("success"=>$success, "trans_no"=> $group_id, "message"=>$message);
    
}


function fi_generate_next_batch_no($cutoff_date_, $group_id, $trans_type, $batch_size)
{
    $cutoff_date = date2sql($cutoff_date_);
    $n = fi_get_remaining_transactions_count($trans_type, $cutoff_date, $batch_size);
    if($n > 0){
        $batch_no = create_next_fi_batch_no($cutoff_date_, $group_id, $trans_type);
        return $batch_no;
    }
    
    return 0;
}

function generate_transaction_type_fi_entries($group_id, $type, $cutoff_date_, $timeout_at, $batch_size=1)
{
    global $path_to_root;
    
    $batch_nos_array = array();
    
    if(isset($_POST['select_fi_type_'.$type]) && $_POST['select_fi_type_'.$type] == true){   
        $batch_no = fi_generate_next_batch_no($cutoff_date_, $group_id, $type, $batch_size);
        if($batch_no > 0){
            switch ($type) {
                // Inventory
                case ST_MATERIAL_ISSUE:     
                    $msg = fi_material_issues($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
                case ST_MATERIAL_RETURN:
                    $msg = fi_material_returns($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
                case ST_SITE_MATERIAL_RETURN:
                    $msg = fi_site_material_returns($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
                case ST_INVENTORY_RECEIPT:
                case ST_INVENTORY_ISSUE:
                case ST_INVADJUST:
                    $msg = fi_inventory_adjustments($batch_no, $cutoff_date_, $type, $timeout_at, $batch_size);
                    break;
                case ST_STOCK_COUNT:
                    $msg = fi_stock_counts($batch_no, $cutoff_date_, $type, $timeout_at, $batch_size);
                    break;
                case ST_ITEM_COSTUPDATE:
                    $msg = fi_stock_item_cost_update($batch_no, $cutoff_date_, $type, $timeout_at, $batch_size);
                    break;
                case ST_DAILY_ITEM_ISSUE:
                    $msg = fi_daily_item_issues($batch_no, $cutoff_date_, $type, $timeout_at, $batch_size);
                    break;
                case ST_DAILY_ITEM_RETURN:
                    $msg = fi_daily_item_issues($batch_no, $cutoff_date_, $type, $timeout_at, $batch_size);
                    break;                
                case ST_PETTY_CASH_ITEM_RECEIPT:
                    $msg = fi_petty_cash_item_receipts($batch_no, $cutoff_date_, $type, $timeout_at, $batch_size);
                    break;


                // GL
                case ST_UTILITY_BILLS:
                    $msg = fi_utility_bills($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
                case ST_UTILITY_BILL_CREDIT_NOTE:
                    $msg = fi_utility_bill_credit_notes($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;

//==============Projects=============================
                case ST_PROJECT_INVOICE:
                    $msg = fi_project_invoices($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
                case ST_PROJECT_CREDIT_NOTE:
                    $msg = fi_project_credit_notes($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
                case ST_SUBCONTRACTOR_INVOICE:
                    $msg = fi_subcontractor_invoices($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
                case ST_SUBCONTRACTOR_CREDIT_NOTE:
                    $msg = fi_subcontractor_credit_notes($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
                case ST_MISCELLANEOUS_PROJECT_COST:
                    include_once($path_to_root . "/gl/includes/fi/ui/fi_miscellaneous_project_cost_ui.inc");
                    include_once($path_to_root . "/gl/includes/fi/db/fi_miscellaneous_project_cost_db.inc");
                    fi_miscellaneous_project_costs($batch_no, $cutoff_date_, $batch_size);
    //                break;



                case ST_SALESINVOICE:
                    $msg = fi_sales_invoices($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
                case ST_CUSTDELIVERY:
                    $msg = fi_sales_deliveries($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
                case ST_CUSTOMER_PAYMENT_RETURN:   
                    $msg = fi_sales_invoice_returns($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
                case ST_CUSTCREDIT:
                    $msg = fi_customer_credit_notes($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
//                case ST_CUSTPAYMENT:       
//                    $msg = fi_customer_payments($batch_no, $cutoff_date_, $timeout_at, $batch_size);
//                    break;


                // Purchasing
                case ST_SUPPRECEIVE:
                    $msg = fi_goods_received_notes($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
                case ST_SUPPINVOICE:
                    $msg = fi_supplier_invoices($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
                case ST_SUPPCREDIT:
                    $msg = fi_supplier_credit_notes($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
                case ST_SUPPAYMENT: 
                    $msg = fi_supplier_payments($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
                case ST_PR_ISSUE: 
                    $msg = fi_pr_issues($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
                case ST_PR_RETURN:
                    $msg = fi_pr_returns($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;



                // Petty cash
                case ST_PETTY_CASH_FLOAT_ADJ:
                    $msg = fi_petty_cash_float_adjustments($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
                case ST_PETTY_CASH_FLOAT_REIMBUR:               
                    $msg = fi_petty_cash_float_reimbursements($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
                case ST_I_OWE_YOU_BATCH:              
                    $msg = fi_i_owe_you_batch_expenses($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
                case ST_PETTY_CASH_DIRECT_PAYMENTS:             
                    $msg = fi_petty_cash_direct_payments($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
                case ST_I_OWE_YOU_PAYMENT:
                case ST_PETTY_CASH_PAYMENT:
                case ST_I_OWE_YOU_ADVANCES:              
                    $msg = fi_i_owe_you_payments($batch_no, $type, $cutoff_date_, $timeout_at, $batch_size);
                    break;



                case ST_SUPPLIER_TRANSPORT_INVOICES:             
                    $msg = fi_supplier_transport_invoices($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
                
                case ST_COMP_LOAN_REPAYMENT:              
                    $msg = fi_company_loan_repayments($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;


                

            
                        

//            case ST_TOOL_USAGE_CHARGE:
//                fi_tool_usage_charges($batch_no, $cutoff_date_);
//                break;
//            case ST_ASSET_DEPRECIATION:
//                fi_asset_depreciation($batch_no, $cutoff_date_);
//                break;
            case ST_ASSET_QUANTITY_ADJUSTMENT:
                $msg = fi_asset_quantity_adjustments($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                break;
            case ST_STOCK_ASSET_TRANSFER:
                $msg = fi_stock_asset_transfers($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                break;

                case ST_PAYROLL:
                    include_once($path_to_root . "/includes/db/group_companies_db.inc");
                    include_once($path_to_root . "/gl/includes/fi/ui/fi_payroll_ui.inc");
                    include_once($path_to_root . "/gl/includes/fi/db/fi_payroll_db.inc");                
                    include_once($path_to_root . "/admin/db/list_values_db.inc");                
                    include_once($path_to_root . "/payroll/includes/db/payroll_accounts_setup_db.inc"); 
                    $msg = fi_payroll_summaries($batch_no, $cutoff_date_, $timeout_at, $batch_size);
                    break;
            
            
                default:
                    break;
            }
        }else{
            $msg = array("success"=>true, "message"=>"");
        }
        
    }
    else{
        return array("success"=>true, "message"=>"");
    }
    
    if($msg["success"] !== true){
        return $msg;            
    } 
    else{
        unset($_POST['select_fi_type_'.$type]);    
        return array("success"=>true, "message"=>"");
    }
    
}


function add_fi_trans_std_cost($batch_no, $type, $trans_id, $detail_line_id, $date_, $account, $dimension, $dimension2,
	$memo_,	$amount, $currency=null, $person_type_id=null, $person_id=null, $err_msg="")
{
	if ($amount != 0){
		return add_fi_trans($batch_no, $type, $trans_id, $detail_line_id, $date_, $account, $dimension, $dimension2, $memo_,
			$amount, $currency, $person_type_id, $person_id, $err_msg);
        }
	else{
		return 0;
        }
}


function add_fi_trans_supplier($batch_no, $type, $type_no, $detail_line_id, $date_, $account, $dimension, $dimension2,  
	$amount, $supplier_id, $currency_code = null, $rate=0, $memo="")
{

        $err_msg = "The supplier GL transaction could not be inserted";        
	if ($amount != 0){	
            return add_fi_trans($batch_no, $type, $type_no, $detail_line_id, $date_, $account, $dimension, $dimension2, $memo, 
		$amount, $currency_code, PT_SUPPLIER, $supplier_id, $err_msg, $rate);
        }
	else{
		return 0;
        }
}


// Function for even out rounding problems
function add_fi_balance($batch_no, $type, $trans_id, $date_, $amount, $currency_code = null, $person_type_id=null, $person_id=null, $memo = '', $project_id=0)
{
    $non_zero_fi_balances_account = get_company_pref('fi_balances_act');

    if (floatcmp($amount, 0)){
            return add_fi_trans($batch_no, $type, $trans_id, 0, $date_, $non_zero_fi_balances_account, $project_id, 0, $memo,
                    $amount, $currency_code, $person_type_id, $person_id, "The balanced GL transaction could not be inserted");

    } 
    else{
            return 0;
    }
}


function add_fi_trans_customer($batch_no, $type, $type_no, $detail_line_id, $date_, $account, $dimension, $dimension2,
                                $amount, $customer_id, $currency_code = null, $rate=0, $memo="")
{

        $err_msg = "The customer GL transaction could not be inserted";        

	return add_fi_trans($batch_no, $type, $type_no, $detail_line_id, $date_, $account, $dimension, $dimension2, $memo, 
                $amount, $currency_code, PT_CUSTOMER, $customer_id, $err_msg, $rate);
}

function add_fi_tax_details($gl_code, $trans_type, $trans_no, $amount, $ex_rate, $date, $memo, $included=0, $net_amount = null)
{
	$tax_type = is_tax_account($gl_code);
	if(!$tax_type){
            return;	// $gl_code is not tax account
        }
	
	$tax = get_tax_type($tax_type);
	//if ($gl_code == $tax['sales_gl_code'])
	if ($trans_type == ST_SALESINVOICE || $trans_type == ST_CUSTDELIVERY || $trans_type == ST_CUSTCREDIT){
		$amount = -$amount;
        }
        
	// we have to restore net amount as we cannot know the base amount
	if ($net_amount===null) {
		if ($tax['rate'] == 0) {
//			display_warning(_("You should not post gl transactions  
//				to tax account with	zero tax rate."));
			$net_amount = 0;
		} else { 
			// calculate net amount
			$net_amount = $amount/$tax['rate']*100; 
		}
	}
	add_trans_tax_details($trans_type, $trans_no, $tax['id'], $tax['rate'], $included, 
		$amount, $net_amount, $ex_rate, $date, $memo);
			
}

function write_fi_log($log_id, $message=""){
    global $installed_path;
    $log_filename = "fi_batch_no_"; 
    $log_filename .= $log_id.".txt"; 

    $log_filepathname = $installed_path . '/tmp/financial_integration_logs/'.$log_filename;
//    file_put_contents($log_filepathname, format_microtime('Y-m-d H:i:s'), FILE_APPEND);
    file_put_contents($log_filepathname, format_microtime('Y-m-d H:i:s')." ".$message."\r\n", FILE_APPEND);     
}

function read_fi_log($batch_no){
    if(!($batch_no > 0)){
        return;
    }
    global $installed_path;
    $user_activity_log_file_data_array = array();
    $file_path_name = $installed_path."/tmp/financial_integration_logs/fi_batch_no_$batch_no.txt";
        
        if(file_exists($file_path_name)){
            $file_handle = fopen($file_path_name, "r");
        }else{
            return array();
        }

        if($file_handle) {            
            while(!feof($file_handle) ){
                $line = fgetcsv($file_handle, 1024);
                $time = substr($line[0], 0, 19);
                $page_name = substr($line[0], 19);
                if(strlen($time) > 0){
                    $a = array("time" => $time, "page_name" => $page_name);
                    $user_activity_log_file_data_array[] = $a;
                }
            }
        }
       
    display_fi_log($user_activity_log_file_data_array);
}

function display_fi_log($user_activity_log_file_data_array){
    
    if(count($user_activity_log_file_data_array) > 0){
        start_table(TABLESTYLE, "width=70%");
            $th = array("Time", "Error");
            table_header($th);

            foreach($user_activity_log_file_data_array as $value){
                start_row();
                    label_cell($value["time"], 'align=center'); 
                    label_cell($value["page_name"]);   
                end_row();
            }
        end_table(1);
    }
}

function get_fi_integration_timeout_message()
{
    return "Process has been timed out before completing all the transactions. Please rerun it to complete the rest.";
}

function can_generate_fi_transaction($tran_type, $trans_no, $tran_date){
    
    global $systypes_array;
    
    $error_prefix = $systypes_array[$tran_type]. "#".$trans_no." : ";
    
    if (!is_date_in_fiscalyear($tran_date, true)) {
        $message = (_($error_prefix."Transaction date is not in fiscal year.")); 
        return array("success"=>false, "message"=>$message);
    }
        
    $msg = is_accounting_period_open($tran_date, true);
    if ($msg['success'] !== true)
    {
        $message = ($error_prefix.$msg['message']); 
        return array("success"=>false, "message"=>$message);
    }
    
    return array("success"=>true, "message"=>"");
}
/*
UPDATE 0_company_loan_payments SET fi_batch_no = 0;
UPDATE 0_debtor_trans SET fi_batch_no = 0;
UPDATE 0_grn_batch SET fi_batch_no = 0;
UPDATE 0_i_owe_you_batches SET fi_batch_no = 0;
UPDATE 0_i_owe_you_float_reimbursements SET fi_batch_no = 0;
UPDATE 0_i_owe_you_payments SET fi_batch_no = 0;
UPDATE 0_issue_materials SET fi_batch_no = 0;
UPDATE 0_miscellaneous_project_costs SET fi_batch_no = 0;
UPDATE 0_petty_cash_float_adjustments SET fi_batch_no = 0;
UPDATE 0_project_credit_notes SET fi_batch_no = 0;
UPDATE 0_project_invoices SET fi_batch_no = 0;
UPDATE 0_return_materials SET fi_batch_no = 0;
UPDATE 0_site_material_returns SET fi_batch_no = 0;
UPDATE 0_stock_adjustments SET fi_batch_no = 0;
UPDATE 0_subcontractor_credit_notes SET fi_batch_no = 0;
UPDATE 0_subcontractor_invoices SET fi_batch_no = 0;
UPDATE 0_supp_trans SET fi_batch_no = 0;
UPDATE 0_supp_trans SET fi_batch_no = 0;
UPDATE 0_utility_bill_credit_notes SET fi_batch_no = 0;
UPDATE 0_utility_bills SET fi_batch_no = 0;

//DELETE FROM 0_fi_batch_details WHERE fi_batch_no = ?????????;
 * 
 * 
 */



function fi_include_files($path_to_root)
{
    // Inventory
    include_once($path_to_root . "/gl/includes/fi/ui/fi_material_issues_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_material_issues_db.inc");

    include_once($path_to_root . "/gl/includes/fi/ui/fi_material_returns_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_material_returns_db.inc");

    include_once($path_to_root . "/gl/includes/fi/ui/fi_site_material_returns_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_site_material_returns_db.inc");

    include_once($path_to_root . "/gl/includes/fi/ui/fi_inventory_adjustments_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_inventory_adjustments_db.inc");

    include_once($path_to_root . "/gl/includes/fi/ui/fi_stock_counts_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_stock_counts_db.inc");

    include_once($path_to_root . "/gl/includes/fi/ui/fi_stock_item_cost_update_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_stock_item_cost_update_db.inc");
    
    include_once($path_to_root . "/gl/includes/fi/ui/fi_daily_item_issues_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_daily_item_issues_db.inc");    
    
    include_once($path_to_root . "/gl/includes/fi/ui/fi_petty_cash_item_receipts_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_petty_cash_item_receipts_db.inc");

    

    include_once($path_to_root . "/gl/includes/fi/ui/fi_utility_bills_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_utility_bills_db.inc");

    include_once($path_to_root . "/gl/includes/fi/ui/fi_utility_bill_credit_notes_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_utility_bill_credit_notes_db.inc");
    
    

    include_once($path_to_root . "/gl/includes/fi/ui/fi_project_invoices_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_project_invoices_db.inc");

    include_once($path_to_root . "/gl/includes/fi/ui/fi_project_credit_notes_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_project_credit_notes_db.inc");

    include_once($path_to_root . "/gl/includes/fi/ui/fi_subcontractor_invoice_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_subcontractor_invoice_db.inc");


    include_once($path_to_root . "/gl/includes/fi/ui/fi_subcontractor_credit_notes_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_subcontractor_credit_notes_db.inc");
    
    include_once($path_to_root . "/gl/includes/fi/ui/fi_miscellaneous_project_cost_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_miscellaneous_project_cost_db.inc");
    


    include_once($path_to_root . "/gl/includes/fi/ui/fi_sales_invoices_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_sales_invoices_db.inc");

    include_once($path_to_root . "/gl/includes/fi/ui/fi_sales_deliveries_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_sales_deliveries_db.inc");

    include_once($path_to_root . "/gl/includes/fi/ui/fi_sales_invoice_returns_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_sales_invoice_returns_db.inc");     

    include_once($path_to_root . "/gl/includes/fi/ui/fi_customer_credit_notes_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_customer_credit_notes_db.inc");

    include_once($path_to_root . "/gl/includes/fi/ui/fi_customer_payments_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_customer_payments_db.inc");          
    
    

    include_once($path_to_root . "/gl/includes/fi/ui/fi_goods_received_notes_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_goods_received_notes_db.inc"); 

    include_once($path_to_root . "/gl/includes/fi/ui/fi_supplier_invoice_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_supplier_invoice_db.inc"); 

    include_once($path_to_root . "/gl/includes/fi/ui/fi_supplier_credit_note_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_supplier_credit_note_db.inc");

    include_once($path_to_root . "/gl/includes/fi/ui/fi_supplier_payments_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_supplier_payments_db.inc");   

    include_once($path_to_root . "/gl/includes/fi/ui/fi_pr_issues_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_pr_issues_db.inc");   

    include_once($path_to_root . "/gl/includes/fi/ui/fi_pr_returns_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_pr_returns_db.inc");   
    
    


    include_once($path_to_root . "/gl/includes/fi/ui/fi_petty_cash_float_adjustments_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_petty_cash_float_adjustments_db.inc");

    include_once($path_to_root . "/gl/includes/fi/ui/fi_petty_cash_float_reimbursements_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_petty_cash_float_reimbursements_db.inc");                

    include_once($path_to_root . "/gl/includes/fi/ui/fi_i_owe_you_batch_expenses_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_i_owe_you_batch_expenses_db.inc");                

    include_once($path_to_root . "/gl/includes/fi/ui/fi_petty_cash_direct_payments_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_petty_cash_direct_payments_db.inc");                

    include_once($path_to_root . "/gl/includes/fi/ui/fi_i_owe_you_payments_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_i_owe_you_payments_db.inc");               
    
    

    include_once($path_to_root . "/gl/includes/fi/ui/fi_supplier_transport_invoices_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_supplier_transport_invoices_db.inc");         
    
    

    include_once($path_to_root . "/gl/includes/fi/ui/fi_company_loan_repayments_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_company_loan_repayments_db.inc");     
    
    
    
    include_once($path_to_root . "/gl/includes/fi/ui/fi_asset_quantity_adjustments_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_asset_quantity_adjustments_db.inc");     
    include_once($path_to_root . "/assets/includes/db/assets_db.inc");     
    
    include_once($path_to_root . "/gl/includes/fi/ui/fi_stock_asset_transfers_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_stock_asset_transfers_db.inc");     
    
    

    include_once($path_to_root . "/includes/db/group_companies_db.inc");
    include_once($path_to_root . "/gl/includes/fi/ui/fi_payroll_ui.inc");
    include_once($path_to_root . "/gl/includes/fi/db/fi_payroll_db.inc");                
    include_once($path_to_root . "/admin/db/list_values_db.inc");                
    include_once($path_to_root . "/payroll/includes/db/payroll_accounts_setup_db.inc"); 

                
}


function set_fi_applicable_expense_account($project_type_id, &$expense_account, $coc_account)
{
    switch ($project_type_id) {
        case PROJ_TYPE_CONSUMPTION:
            $expense_account = $coc_account;
            break;

        default:
            break;
    }

}