<?php


//we need to add this line in get_systype_db_info()
//  case     ST_UNDEFINED  : return array(TB_PREF."bank_trans", "type", "trans_no", "ref", "trans_date");

//we need update this queries
//SET sql_mode="";
// ALTER TABLE `0_bank_trans` ADD `account_no` VARCHAR(50) NOT NULL AFTER `person_id`, ADD `account_name` VARCHAR(250) NOT NULL AFTER `account_no`, ADD `entry_date` DATE NOT NULL DEFAULT '0000-00-00' AFTER `account_name`,ADD `imported` TINYINT NOT NULL DEFAULT '0' AFTER `entry_date` ;
// define('ST_UNDEFINED', 101);


// include_once($path_to_root . "/gl/includes/ui/gl_bank_ui.inc");
// include_once($path_to_root . "/gl/includes/gl_db.inc");
// include_once($path_to_root . "/gl/includes/gl_ui.inc"); 
global $payment_person_types;
if(!defined('PT_BKTRANS'))
    define('PT_BKTRANS',count_array($payment_person_types)+1);

function import_bank_statements($file_name){
    global $unknown,$path_to_root ;
    $file =fopen($file_name, 'r');
    $counter =-1;
    $result='';
    $for_next =array();
    $unformatted_csv=false;
    include_once($path_to_root . "/modules/Kvcodes_importexport/includes/bank_templates/".$_POST['bank_name'].".inc");
}



function CreateNewAutoBankAccount($Bank, $Account, $Currency='') {
  if($Currency == '')
    $Currency = get_company_pref('curr_default');
  $bank_charge_act = get_company_pref('bank_charge_act');
  $code = CreateGLAccounts('name', 18);
  $bank = ['account_code' => $code, 'account_type' => 2, 'bank_account_name' => $Bank, 'bank_account_number' => $Account, 'bank_name' => $Bank, 'bank_curr_code' => $Currency, 'dflt_curr_act' => 0 , 'bank_charge_act' => $bank_charge_act];
  $bank['id'] = Insert('bank_accounts', $bank);
  return $bank;
}


function CreateGLAccounts($name, $account_type){
  $code = HasCodeExists();
  Insert('chart_master', array('account_code' => $code, 'account_name' => $name, 'account_type' => $account_type));
  return $code;
}


function HasCodeExists(){
  $codes = [1010,1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020];
  $sql = "SELECT account_code FROM ".TB_PREF."chart_master WHERE account_code BETWEEN 1010 AND 1020";
  $existing_charts = db_query($sql, "Can't get results");
  if(db_num_rows($existing_charts) > 0 ){
     while($single = db_fetch($existing_charts)){
        if (($key = array_search($single['account_code'], $codes)) !== false) {
            unset($codes[$key]);
        }
     }
   }
   return reset($codes);
}


function GetUnpaidSalesInvoices(){
  
  $sql2 = "(SELECT trans.type,    trans.trans_no, trans.reference,  trans.tran_date,  debtor.name AS DebtorName, 
        debtor.curr_code, IF(prep_amount, prep_amount, ov_amount+ov_gst+ov_freight+ov_freight_tax+ov_discount) AS Total,
        trans.alloc,trans.due_date, debtor.address, trans.version,  amt,  trans.debtor_no,  trans.branch_code
       FROM ".TB_PREF."debtor_trans as trans  LEFT JOIN ".TB_PREF."cust_allocations as alloc
            ON trans.trans_no = alloc.trans_no_to AND trans.type = alloc.trans_type_to AND alloc.person_id=trans.debtor_no,".TB_PREF."debtors_master as debtor
       WHERE   trans.debtor_no=debtor.debtor_no  AND (  trans.type='10' AND round(IF(prep_amount, prep_amount, ov_amount+ov_gst+ov_freight+ov_freight_tax+ov_discount)-alloc,6) > 0   OR
          trans.type='11' AND round(-IF(prep_amount, prep_amount, ov_amount+ov_gst+ov_freight+ov_freight_tax+ov_discount)-alloc,6) > 0  OR
            trans.type = '0' AND ov_amount+ov_gst+ov_freight+ov_freight_tax+ov_discount>0   OR
            trans.type = '1'  AND ov_amount+ov_gst+ov_freight+ov_freight_tax+ov_discount>0
        ) GROUP BY type, trans_no ORDER BY trans_no) 
    UNION (SELECT sorder.trans_type as type,  sorder.order_no as trans_no,  sorder.reference, sorder.ord_date,  debtor.name AS DebtorName,  debtor.curr_code,
      total-IFNULL(invoiced.amount,0) as Total, sorder.alloc, sorder.delivery_date as due_date, debtor.address, sorder.version, amt,  sorder.debtor_no,
      sorder.branch_code  FROM ".TB_PREF."sales_orders as sorder
        LEFT JOIN ".TB_PREF."debtors_master as debtor ON sorder.debtor_no = debtor.debtor_no
        LEFT JOIN ".TB_PREF."cust_allocations as alloc 
          ON sorder.order_no = alloc.trans_no_to AND sorder.trans_type = alloc.trans_type_to AND alloc.person_id=sorder.debtor_no
        LEFT JOIN (SELECT order_, sum(prep_amount) amount FROM ".TB_PREF."debtor_trans dt
        WHERE prep_amount>0 AND dt.type=10 GROUP BY order_) as invoiced ON sorder.order_no = invoiced.order_
      WHERE sorder.trans_type=30 AND round(sorder.prep_amount)>0 and Total>0  GROUP BY sorder.order_no)";
  db_query("SET sql_mode='';");
  $res = db_query($sql2, "Can't get result");
  $final = [];
  if(db_num_rows($res) > 0 ){
    while($row = db_fetch($res)){
      $final[] = $row;
    }
  }
  return  $final; 
}
function CustomersList(){

  $sql = "SELECT deb.*, br.bank_account FROM ".TB_PREF."debtors_master AS deb LEFT JOIN ".TB_PREF."cust_branch AS br ON br.debtor_no = deb.debtor_no WHERE !deb.inactive GROUP BY deb.debtor_no";
   db_query("SET sql_mode='';");
  $res = db_query($sql, "Can't get result");
  $final = [];
  if(db_num_rows($res) > 0 ){
    while($row = db_fetch($res)){
      $final[] = $row;
    }
  }
  return  $final; 
}

function get_cust_branch_bank($CustomerId) {
 return GetRow('cust_branch', ['debtor_no' => $CustomerId]); 
}

function GetUnpaidPurchaseInvoices(){
  $sql2 = "(SELECT      trans.type,       trans.trans_no,      IF(trans.supp_reference='',trans.reference,trans.supp_reference) as reference,
        trans.tran_date,      supplier.supp_name,       supplier.curr_code, 
        ov_amount+ov_gst+ov_discount AS Total,     trans.alloc,
        trans.due_date,        trans.supplier_id,        amt,        supp_reference
     FROM ".TB_PREF."supp_trans as trans
            LEFT JOIN ".TB_PREF."supp_allocations as alloc
                ON trans.trans_no = alloc.trans_no_to AND trans.type = alloc.trans_type_to AND alloc.person_id=trans.supplier_id,".TB_PREF."suppliers as supplier
     WHERE
         trans.supplier_id=supplier.supplier_id AND round(ov_amount+ov_gst+ov_discount-alloc,6) > 0
            AND trans.type NOT IN (22,1) GROUP BY type, trans_no ORDER BY trans_no) 
  UNION (SELECT       18 as type,       porder.order_no as trans_no,      porder.reference,       porder.ord_date,        supplier.supp_name AS DebtorName, 
        supplier.curr_code,      total as Total,      porder.alloc,     due_dates.date as due_date,      supplier.address,       amt,       requisition_no as supp_ref
        FROM ".TB_PREF."purch_orders as porder
            LEFT JOIN ".TB_PREF."suppliers as supplier ON porder.supplier_id = supplier.supplier_id
            LEFT JOIN ".TB_PREF."supp_allocations as alloc
                ON porder.order_no = alloc.trans_no_to AND alloc.trans_type_to=18 AND alloc.person_id=porder.supplier_id
            LEFT JOIN ".TB_PREF."grn_batch as grn ON porder.order_no = grn.purch_order_no
            LEFT JOIN (SELECT order_no, MIN(delivery_date) as date
        FROM ".TB_PREF."purch_order_details det
        GROUP BY det.order_no) due_dates ON due_dates.order_no=porder.order_no
        WHERE total>0 AND ISNULL(grn.purch_order_no)  GROUP BY porder.order_no, grn.purch_order_no) ORDER BY due_date";
    db_query("SET sql_mode='';");
  $res = db_query($sql2, "Can't get result");
  $final = [];
  if(db_num_rows($res) > 0 ){
    while($row = db_fetch($res)){
      $final[] = $row;
    }
  }
  return  $final; 
}


function SuppliersList(){
  $sql = "SELECT * FROM ".TB_PREF."suppliers WHERE !inactive";
   db_query("SET sql_mode='';");
  $res = db_query($sql, "Can't get result");
  $final = [];
  if(db_num_rows($res) > 0 ){
    while($row = db_fetch($res)){
      $final[] = $row;
    }
  }
  return  $final; 
}


function create_cart($type, $trans_no)
{
  global $Refs;

  if (isset($_SESSION['pay_items']))
  {
    unset ($_SESSION['pay_items']);
  }

  $cart = new items_cart($type);
    $cart->order_id = $trans_no;

  $cart->reference = $Refs->get_next($cart->trans_type, null, $cart->tran_date);
  $cart->tran_date = new_doc_date();
  if (!is_date_in_fiscalyear($cart->tran_date))
    $cart->tran_date = end_fiscalyear();


  $_POST['memo_'] = $cart->memo_;
  $_POST['ref'] = $cart->reference;
  $_POST['date_'] = $cart->tran_date;

  $_SESSION['pay_items'] = &$cart;
}



function check_bank_trans_settings($single,$header){
  global $Refs,$bank_trans_settings,$path_to_root,$unpaid_sales,$CustomersList,$unpaid_purchase,$SuppliersList;
  $is_defined=false;
  foreach ($bank_trans_settings as $row) {
    if(strpos($single['description'],$row['keyword']) !== false){
      $is_defined=true;
    }else{
      continue;
    }
    if($row['negative_only'] && $single['debitcredit'] !="D"){
      $is_defined=false;
    }elseif(!$row['negative_only'] &&$single['debitcredit'] !="C"){
      $is_defined=false;
    }

    if($row['min_price'] && $single['price'] <$row['min_price']){
      $is_defined=false;
    }elseif($row['max_price'] && $single['price'] >$row['max_price']){
      $is_defined=false;
    }

    if($is_defined){
      $current_row=$row;
      break;
    }
  }

  if($is_defined){
      $inv_allocated=false;
      if($single['debitcredit']=="D") {

        if($current_row['pay_type']==PT_SUPPLIER){
          $person_id ="";
          if($current_row['person_id']){
            $person_id = $current_row['person_id'];
          }

         
          $_SESSION['alloc'] = new allocation(ST_SUPPAYMENT, 0, $person_id);
          if($_SESSION['alloc']->allocs){
            foreach ($_SESSION['alloc']->allocs as $key => $value) {
              if($value->amount -$value->amount_allocated ==$single['price']){
                $inv_allocated=true;
                $_SESSION['alloc']->allocs[$key]->current_allocated=$single['price'];
              }
            }
          }
        }


        if(!$inv_allocated){
          create_cart(ST_BANKPAYMENT, 0);
          $person_id ="";
          if($current_row['person_id']){
            $person_id = $current_row['person_id'];
          }

          //check accountName
          if($single['accountName'] && !isset($current_row['person_id'])){                                          
            $nospace_lower = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$single['accountName']));
            foreach($CustomersList as $single1 ){
              $custname = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$single1['debtor_ref']));
              if(isset($nospace_lower) && $nospace_lower != '' && ($nospace_lower == $custname)){
                $person_id = $single1['debtor_no'];
                break;
              }
            }
          }


          if($single['account'] && !isset($current_row['person_id'])){                                          
            foreach($CustomersList as $single1 ){
              if(isset($single['account']) && $single['account'] != '' && ($single['account'] == $single1['bank_account'])){
                $person_id = $single1['debtor_no'];
                break;
              }
            }
          }



          //check supplier
          if($single['accountName'] && !isset($current_row['person_id'])){                                          
            $nospace_lower = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$single['accountName']));
            foreach($SuppliersList as $single1 ){
              $suppname = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$single1['supp_ref']));
              if(isset($nospace_lower) && $nospace_lower != '' && (/*stripos($nospace_lower, $custname) !== false || */$nospace_lower == $suppname)){
                $person_id = $single1['debtor_no'];
                break;
              }
            }
          }


          if($single['account'] && !isset($current_row['person_id'])){  
            foreach($SuppliersList as $single1 ){
              if(isset($single['account']) && $single['account'] != '' && ($single['account'] == $single1['bank_account'])){
                $person_id = $single1['supplier_id'];
                break;
              }
            }
          }



        }


      }elseif($single['debitcredit']=="C" ) {

         $inv_allocated=false;
        if($current_row['pay_type']==PT_CUSTOMER){
          if($current_row['person_id']){
             $person_id = $current_row['person_id'];
          }
          $_SESSION['alloc'] = new allocation(ST_CUSTPAYMENT, 0, $person_id);
          if($_SESSION['alloc']->allocs){
            foreach ($_SESSION['alloc']->allocs as $key => $value) {
              if($value->amount -$value->amount_allocated ==$single['price']){
                $inv_allocated=true;
                $_SESSION['alloc']->allocs[$key]->current_allocated=$single['price'];
              }
            }
          }
        }
        if(!$inv_allocated){
          create_cart(ST_BANKDEPOSIT,0);
          $person_id ="";
          if($current_row['person_id']){
             $person_id = $current_row['person_id'];
          }

          //check accountName
          if($single['accountName'] && !isset($current_row['person_id'])){                                          
            $nospace_lower = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$single['accountName']));
            foreach($CustomersList as $single1 ){
              $custname = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$single1['debtor_ref']));
              if(isset($nospace_lower) && $nospace_lower != '' && (/*stripos($nospace_lower, $custname) !== false || */$nospace_lower == $custname))
              $person_id = $single1['debtor_no'];
              break;
            }
          }


          if($single['account'] && !isset($current_row['person_id'])){                                          
            foreach($CustomersList as $single1 ){
              if(isset($single['account']) && $single['account'] != '' && ($single['account'] == $single1['bank_account'])){
                $person_id = $single1['debtor_no'];
                break;
              }
            }
          }

          //check supplier
          if($single['accountName'] && !isset($current_row['person_id'])){                                          
            $nospace_lower = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$single['accountName']));
            foreach($SuppliersList as $single1 ){
              $suppname = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$single1['supp_ref']));
              if(isset($nospace_lower) && $nospace_lower != '' && (/*stripos($nospace_lower, $custname) !== false || */$nospace_lower == $suppname)){
                $person_id = $single1['debtor_no'];
                break;
              }
            }
          }

          if($single['account'] && !isset($current_row['person_id'])){  
            foreach($SuppliersList as $single1 ){
              if(isset($single['account']) && $single['account'] != '' && ($single['account'] == $single1['bank_account'])){
                $person_id = $single1['supplier_id'];
                break;
              }
            }
          }
        }
      }

      
      if($current_row['pay_type']==PT_BKTRANS){

        $form_bank =$header['bank_id'];
        $to_bank =$current_row['person_id'];
        

        // if($single['debitcredit'] =="D"){
        //   $form_bank =$header['bank_id'];
        //   $to_bank =$current_row['person_id'];
        // }elseif($single['debitcredit'] =="C"){
        //   $form_bank =$current_row['person_id'];
        //   $to_bank =$header['bank_id'];
        // }

        if($form_bank ==$to_bank){
          return false;
        }


        begin_transaction();
        $filter = array('trans.amount' => ($single['debitcredit'] == 'D' ? -$single['price']: $single['price']), 'trans.trans_date' => $single['date'], 'cm.memo_' =>$single['description']);
        if($single['accountName'] !="")
           $filter['trans.account_name']=$single['accountName'];

        $new =1;
        $entry = GetDataJoin('bank_trans AS trans', array( array('join' => 'LEFT', 'table_name' => 'comments AS cm', 'conditions' => '`cm`.`type` = `trans`.`type` AND `cm`.`id` = `trans`.`trans_no`')), ['trans.*, cm.memo_'],$filter, null, false, true);

        if($entry){
          if($entry['type'] ==ST_UNDEFINED){
            $new =2;
            Delete('bank_trans', array('type' => ST_UNDEFINED, 'trans_no' => $entry['trans_no']));
            Delete('comments', array('type' => ST_UNDEFINED, 'id' => $entry['trans_no']));
          }
          else{
            $new =3;
            return true;
          }
        }


        $payment_no = get_next_trans_no(ST_BANKTRANSFER);
        $payment_type = ST_BANKTRANSFER;
        $payment_ref =  $Refs->get_next(ST_BANKTRANSFER, null, sql2date($single['date'])); 
        $_POST['BankCharges'] =$person_type = $person_id = 0;
       // $bank_charge_act = get_company_details('bank_charge_act');
        $bt  = array();
        $bta  =GetRow('bank_accounts', array('id' => $form_bank));
        $bto  =GetRow('bank_accounts', array('id' => $to_bank));
       // echo $single['price'].'--'.$_POST['BankCharges'];
        if($single['debitcredit'] =="D"){
          $res = Insert('bank_trans', array('type' => $payment_type, 'trans_no'=>$payment_no, 'bank_act' => $to_bank, 'ref' => $payment_ref, 'trans_date' => $single['date'], 'amount' => $single['price'],'imported'=>1));

        Insert('bank_trans', array('type' => $payment_type, 'trans_no'=>$payment_no, 'bank_act' => $form_bank, 'ref' => $payment_ref, 'trans_date' => $single['date'], 'amount' => -$single['price'],'imported'=>1));

           Insert('gl_trans', array('type' => ST_BANKTRANSFER, 'type_no' => $payment_no, 'account' => $bta['account_code'], 'amount' => ($single['price']-input_num($_POST['BankCharges'])), 'tran_date' => $single['date'] ,'memo_' => $single['description']));

            Insert('gl_trans', array('type' => ST_BANKTRANSFER, 'type_no' => $payment_no, 'account' => $bto['account_code'], 'amount' => $single['price'], 'tran_date' => $single['date'], 'memo_' =>$single['description']));

           if($_POST['BankCharges'] > 0 ) 
            Insert('gl_trans', array('type' => ST_BANKTRANSFER, 'type_no' => $payment_no, 'account' => $bta['bank_charge_act'], 'amount' => $_POST['BankCharges'], 'tran_date' => $tran_date, 'memo_' => $single['description']));
           
        } else {
          $res = Insert('bank_trans', array('type' => $payment_type, 'trans_no'=>$payment_no, 'bank_act' => $to_bank, 'ref' => $payment_ref, 'trans_date' => $single['date'], 'amount' => -$single['price'],'imported'=>1));

          Insert('bank_trans', array('type' => $payment_type, 'trans_no'=>$payment_no, 'bank_act' => $form_bank, 'ref' => $payment_ref, 'trans_date' => $single['date'], 'amount' => $single['price'],'imported'=>1));


          $single['price'] = -$single['price'];
           Insert('gl_trans', array('type' => ST_BANKTRANSFER, 'type_no' => $payment_no, 'account' => $bto['account_code'], 'amount' => ($single['price']), 'tran_date' => $single['date'], 'memo_' =>$single['description']));

            Insert('gl_trans', array('type' => ST_BANKTRANSFER, 'type_no' => $payment_no, 'account' => $bta['account_code'], 'amount' => ($single['price']+$_POST['BankCharges']), 'tran_date' => $single['date'], 'memo_' =>$single['description']));

           if($_POST['BankCharges'] > 0 ) 
            Insert('gl_trans', array('type' => ST_BANKTRANSFER, 'type_no' => $payment_no, 'account' => $bto['bank_charge_act'], 'amount' => -$_POST['BankCharges'], 'tran_date' => $single['date'], 'memo_' =>$single['description']));

        }
        commit_transaction();
        return true;
      }



      if(isset($_SESSION['pay_items'])){
        $amount = ($_SESSION['pay_items']->trans_type==ST_BANKPAYMENT ? 1:-1) * $single['price'];
        if($single['account']){
          $temp_account_row =array();
          $code_id=$single['account'];
        }else{
          $temp_account_row =GetRow('chart_master');
          $code_id=$temp_account_row['account_code'];
        }
        
        $_SESSION['pay_items']->add_gl_item($code_id, 0,
          0, $amount, $single['description']);
        if(!empty($temp_account_row)){
          $_SESSION['pay_items']->gl_items[0]->code_id="";
          $_SESSION['pay_items']->gl_items[0]->description="";
        }

        begin_transaction();
        $filter = array('trans.amount' => ($single['debitcredit'] == 'D' ? -$single['price']: $single['price']), 'trans.trans_date' => $single['date'], 'cm.memo_' =>$single['description']);
        if($single['accountName'] !="")
           $filter['trans.account_name']=$single['accountName'];

        $new =1;
        $entry = GetDataJoin('bank_trans AS trans', array( array('join' => 'LEFT', 'table_name' => 'comments AS cm', 'conditions' => '`cm`.`type` = `trans`.`type` AND `cm`.`id` = `trans`.`trans_no`')), ['trans.*, cm.memo_'],$filter, null, false, true);

        if($entry){
          if($entry['type'] ==ST_UNDEFINED){
            $new =2;
            Delete('bank_trans', array('type' => ST_UNDEFINED, 'trans_no' => $entry['trans_no']));
            Delete('comments', array('type' => ST_UNDEFINED, 'id' => $entry['trans_no']));
          }
          else{
            $new =3;
            return true;
          }
        }
        

        $_SESSION['pay_items'] = &$_SESSION['pay_items'];
        $new = $_SESSION['pay_items']->order_id = 0;

        add_new_exchange_rate(get_bank_account_currency($header['bank_id']),$single['date'], input_num('_ex_rate'));
        $trans = write_bank_transaction(
          $_SESSION['pay_items']->trans_type,0, $header['bank_id'],
          $_SESSION['pay_items'], sql2date($single['date']),
          $current_row['pay_type'], $person_id, get_post('PersonDetailID'),
          $_SESSION['pay_items']->reference, $single['description'], true, input_num('settled_amount', null));



        $trans_type = $trans[0];
          $trans_no = $trans[1];
        
        $_SESSION['pay_items']->clear_items();
        unset($_SESSION['pay_items']);

        Update('bank_trans',array("type"=>$trans_type,"trans_no"=>$trans_no),array('imported'=>1));
        commit_transaction();
        return true;
      }
      elseif($_SESSION['alloc']){
        if($current_row['pay_type']==PT_CUSTOMER){
          begin_transaction();
          $filter = array('trans.amount' => ($single['debitcredit'] == 'D' ? -$single['price']: $single['price']), 'trans.trans_date' => $single['date'], 'cm.memo_' =>$single['description']);
          if($single['accountName'] !="")
             $filter['trans.account_name']=$single['accountName'];

          $new =1;
          $entry = GetDataJoin('bank_trans AS trans', array( array('join' => 'LEFT', 'table_name' => 'comments AS cm', 'conditions' => '`cm`.`type` = `trans`.`type` AND `cm`.`id` = `trans`.`trans_no`')), ['trans.*, cm.memo_'],$filter, null, false, true);

          if($entry){
            if($entry['type'] ==ST_UNDEFINED){
              $new =2;
              Delete('bank_trans', array('type' => ST_UNDEFINED, 'trans_no' => $entry['trans_no']));
              Delete('comments', array('type' => ST_UNDEFINED, 'id' => $entry['trans_no']));
            }
            else{
              $new =3;
              return true;
            }
          }

          new_doc_date(sql2date($single['date']));

          $new_pmt = !$_SESSION['alloc']->trans_no;
          //Chaitanya : 13-OCT-2011 - To support Edit feature
          $ref = $Refs->get_next(ST_CUSTPAYMENT, null, array(
            'customer' =>$person_id, 'date' => sql2date($single['date'])));
          $PersonDetailID = ANY_NUMERIC;

          $payment_no = write_customer_payment($_SESSION['alloc']->trans_no, $person_id, $PersonDetailID,
            $header['bank_id'], sql2date($single['date']), $ref,
            $single['price'], input_num('discount'), $single['description'], 0, input_num('charge'), $single['price']);
          $_SESSION['alloc']->trans_no = $payment_no;
          $_SESSION['alloc']->date_ = sql2date($single['date']);
          $_SESSION['alloc']->write();

          unset($_SESSION['alloc']);
          Update('bank_trans',array("type"=>ST_CUSTPAYMENT,"trans_no"=>$payment_no),array('imported'=>1));
          commit_transaction();
          return true;
        }elseif($current_row['pay_type']==PT_SUPPLIER){
          begin_transaction();

           $ref = $Refs->get_next(ST_SUPPAYMENT, null, array(
            'supplier' =>$person_id, 'date' => sql2date($single['date'])));


          $payment_id = write_supp_payment(0, $person_id, $header['bank_id'],
          sql2date($single['date']), $ref, $single['price'],  input_num('discount'), $single['description'], 
            input_num('charge'), input_num('bank_amount', $single['price']));
          new_doc_date(sql2date($single['date']));

          $_SESSION['alloc']->trans_no = $payment_id;
          $_SESSION['alloc']->date_ = $_POST['bank_trans_date'];
          $_SESSION['alloc']->write();
          unset($_SESSION['alloc']);
          Update('bank_trans',array("type"=>ST_SUPPAYMENT,"trans_no"=>$payment_id),array('imported'=>1));
          commit_transaction();
          return true;
        }
      }
    return true;
  }else{
    return false;
  }
}


function Import_Bank_Statement($result) {
  global $Refs,$unpaid_sales,$CustomersList,$unpaid_purchase,$SuppliersList;
  $fiscal_year = get_company_pref('f_year');
  $sql_bank = "SELECT * FROM ".TB_PREF."bank_accounts WHERE ( bank_name LIKE ".db_escape('%'.$result['Bank'].'%')." AND Replace(coalesce(bank_account_number,''), ' ','')  LIKE ".db_escape('%'.($result['Bank'] == 'ING' ? substr($result['Account'], 1) : $result['Account'] ).'%')."  ) AND bank_curr_code = ".db_escape($result['Currency']);
  $bank = db_query($sql_bank, "can't get bank results");
  if(db_num_rows($bank) >0){
    $bank = db_fetch($bank);
    $bank_id = $bank['id'];   
  }
  else {
    $bank = CreateNewAutoBankAccount($result['Bank'], $result['Account'], $result['Currency']);
    $bank_id = $bank['id'];
  }                      
  $unpaid_sales = GetUnpaidSalesInvoices();
  $CustomersList = CustomersList();                     
  $unpaid_purchase = GetUnpaidPurchaseInvoices();
  $SuppliersList = SuppliersList();
  begin_transaction();

  $kv= $rate = 1;     
  $i= 0;
  foreach($result['Transactions'] as $single){
                          //$i++;
   // if($single['cancellation'] == false /*&& $i <= 5*/){                                
      $selected_person = 0;
      $ref_selected_inv_no = [];
      $price_select_inv = [];
      $payment_type ='C';
      $sref_selected_inv_no = [];
      $sprice_select_inv = [];
      $right_inv = 0;
      $tran_date = sql2date($single['date']);
      $tran_date_ = $single['date'];
      if(check_bank_trans_settings($single,array('bank_id'=>$bank_id))){
        continue;
      }              
    foreach($single as $key => $value){
        if(isset($single['debitcredit']) && $single['debitcredit'] == 'D'){  // Purchase payment or sales credit
          $payment_type ='D';
        } 
               

        if($payment_type == 'C'){
          if($key == 'accountName'){                                          
            $nospace_lower = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$value));
            foreach($CustomersList as $single1 ){
              $custname = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$single1['debtor_ref']));
              if(isset($nospace_lower) && $nospace_lower != '' && (/*stripos($nospace_lower, $custname) !== false || */$nospace_lower == $custname))
                $selected_person = $single1['debtor_no'];
                $selected_person_currency = $single1['curr_code'];
              }
            }
            if($key == 'account'){                                          
                //$nospace_lower = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$value));
              foreach($CustomersList as $single1 ){
                          //echo $single1['bank_account'].'_'.$value.'<br>';
                          //$custname = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$single1['debtor_ref']));
                if(isset($value) && $value != '' && ($value == $single1['bank_account'])){
                  $selected_person = $single1['debtor_no'];
                  break;
                }
              }
            }
                                     // echo '+++'.$selected_person.'+++';
            if($key == 'price'){                                            
              $pmt_amt = round(preg_replace('#[^\w()/.%\-&]#',"",$value), 2);
              foreach($unpaid_sales as $key1 => $single1 ){
                $inv_amt = round($single1['Total'], 2);
                if($pmt_amt == $inv_amt)
                  $price_select_inv[] = $key1;
              }
            }
            if($key == 'description'){                                          
              $description = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$value));
              foreach($unpaid_sales as $key2 => $single1 ){
                $reference = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$single1['reference']));
               
                if(isset($description) && $description != '' && (stripos($description, $reference) !== false || $description == $reference)){
                  $ref_selected_inv_no[] = $key2;

                }
              }

              foreach($CustomersList as $single1 ){
                $custname = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$single1['debtor_ref']));                          
                $name = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$single1['name']));
                if(isset($description) && $description != '' && (stripos($description, $custname) !== false || stripos($description, $name) !== false || $description == $custname))
                  $selected_person = $single1['debtor_no'];
                  $selected_person_currency = $single1['curr_code'];
              }

              $description = $value;
            }
            
            if(count($ref_selected_inv_no) == 1 && count($price_select_inv) == 0)
              $final = $ref_selected_inv_no;
            elseif(count($ref_selected_inv_no) == 0 && count($price_select_inv) == 1)
              $final = $price_select_inv;
            else
              $final = array_intersect($ref_selected_inv_no, $price_select_inv);
            if(!empty($final) && count($final) == 1){
              $right_inv = $unpaid_sales[$final[0]]['trans_no'];
              if($selected_person == 0 )
                $selected_person = $unpaid_sales[$final[0]]['debtor_no'];
                foreach($CustomersList as $single_cust){
                  if($single_cust['debtor_no'] == $selected_person)
                    $selected_person_currency = $single_cust['curr_code'];
                }
            }
            // display_error( $right_inv.'__cust'.$selected_person);
        } elseif($payment_type == 'D' ){
            if($key == 'accountName'){                                          
              $nospace_lower = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$value));
              foreach($SuppliersList as $single1 ){
              $custname = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$single1['supp_ref']));
              if(isset($nospace_lower) && $nospace_lower != '' && (/*stripos($nospace_lower, $custname) !== false ||*/ $nospace_lower == $custname))
                $selected_person = $single1['supplier_id'];
              }
            }

            if(!isset($selected_person) && $key == 'account'){                                          
              //$nospace_lower = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$value));
              foreach($SuppliersList as $single1 ){
                //$custname = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$single1['debtor_ref']));
                if(isset($value) && $value != '' && (/*stripos($nospace_lower, $custname) !== false || */$value == $single1['bank_account']))
                  $selected_person = $single1['supplier_id'];
              }
            }
            if($key == 'price'){                                            
              $pmt_amt = round(preg_replace('#[^\w()/.%\-&]#',"",$value), 2);
              foreach($unpaid_purchase as $key3 => $single1 ){
                $inv_amt = round($single1['Total'], 2);
                if($pmt_amt == $inv_amt)
                  $sprice_select_inv[] = $key3;
              }
            }
            if($key == 'description'){                                          
              $description = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$value));
              foreach($unpaid_purchase as $key4 => $single1 ){
                $reference = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$single1['reference']));
                $supp_reference = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$single1['supp_reference']));
                if(isset($description) && $description != '' && ( (stripos($description, $supp_reference) !== false || $description == $supp_reference) || (stripos($description, $reference) !== false || $description == $reference) ))
                $sref_selected_inv_no[] = $key4;
              }

              foreach($SuppliersList as $single1 ){
                $custname = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$single1['supp_ref']));
                $supp_name = strtolower(preg_replace('#[^\w()/.%\-&]#',"",$single1['supp_name']));
                if(isset($description) && $description != '' && (stripos($description, $custname) !== false || stripos($description, $supp_name) !== false || $description == $custname))
                  $selected_person = $single1['supplier_id'];
                }
              $description = $value;
            }
                      
            if(count($sref_selected_inv_no) == 1 && count($sprice_select_inv) == 0)
              $final = $sref_selected_inv_no;
            elseif(count($sref_selected_inv_no) == 0 && count($sprice_select_inv) == 1)
              $final = $sprice_select_inv;
            else
              $final = array_intersect($sref_selected_inv_no, $sprice_select_inv);
            if(!empty($final) && count($final) == 1) {
              $right_inv = $unpaid_purchase[$final[0]]['trans_no'];
              if($selected_person == 0 )
                $selected_person = $unpaid_purchase[$final[0]]['supplier_id'];
            }
        }
      }

      $new = 0;
      $entry = GetDataJoin('bank_trans AS trans', array( array('join' => 'LEFT', 'table_name' => 'comments AS cm', 'conditions' => '`cm`.`type` = `trans`.`type` AND `cm`.`id` = `trans`.`trans_no`')), ['trans.*, cm.memo_'], array('trans.amount' => ($payment_type == 'D' ? -$pmt_amt: $pmt_amt), 'trans.trans_date' => $tran_date_, 'trans.account_name' => $single['accountName'], 'cm.memo_' => $single['description']), null, false, true);
      if(is_array($entry)) {
         if($entry['type'] == 101){
          $new = 2;
                      //foreach($entry as $single_cmt){
                        // $new = GetSingleValue('comments', 'COUNT(*)', array( 'type' => $single_cmt['type'], 'memo_' => $single['description']), null, false);
                        // if($new >= 1)
                        //   break;
                      //}
        } else 
            $new = 1;
      }
                  //if($single['account'] == 674773837)
                   // echo $new.'<br>';
      if($new==0 || $new == 2){
        $this_alloc = $total_disc = $inv_alloc = $CI_alloc = 0 ;
        if($payment_type == 'C' && $selected_person > 0 ) {
            $payment_ref =  ''; 
            $trans_no_payment = 0 ;
            if($new== 2){
              Delete('bank_trans', array('type' => 101, 'trans_no' => $entry['trans_no']));
              Delete('comments', array('type' => 101, 'id' => $entry['trans_no']));
            } 
           
            if($right_inv > 0 && GetSingleValue('debtor_trans', 'COUNT(*)', array('type' => ST_CUSTPAYMENT, 'ov_amount' => $pmt_amt, 'tran_date' => $tran_date_, 'debtor_no' => $selected_person)) == false){   //customer Payment   
              $type = ST_CUSTPAYMENT;       
              $OtherAllocations =  $diff = 0; //(isset($pmt['diff']) ? $pmt['diff'] : 0 );                               
              $branch = get_cust_branch_bank($selected_person);
                                
              $payment_ref =  (isset($pmt['reference']) ? $pmt['reference'] : $Refs->get_next(ST_CUSTPAYMENT, null, $tran_date)); 
              $trans_no_payment = get_next_trans_no(ST_CUSTPAYMENT);
              Insert('bank_trans', array('type' => ST_CUSTPAYMENT, 'trans_no' => $trans_no_payment, 'bank_act' => $bank_id, 'ref' => $payment_ref, 'trans_date' => $tran_date_, 'amount' => $pmt_amt, 'person_type_id' => 2, 'person_id' => $selected_person, 'account_no' => $single['account'], 'account_name' => $single['accountName'], 'entry_date' =>  $single['date'], 'imported' => 1));
              $this_alloc += $pmt_amt;
              $total_disc += $diff;
              $allocatedAmt = $pmt_amt; //($right_inv > 0 ? ( $pmt_amt+$diff <= $inv_alloc ? $pmt_amt+$diff  : $inv_alloc ) : 0 )+ $OtherAllocations;
              $array = array('trans_no' => $trans_no_payment, 'type' => ST_CUSTPAYMENT, 'debtor_no' => $selected_person, 'branch_code' => $branch['branch_code'], 'reference' => $payment_ref,  'tran_date' => $tran_date_, 'due_date' => '0000-00-00', 'ov_amount' => $pmt_amt, 'ov_discount' => 0, 'ov_gst' => 0, 'rate' => 1, 'alloc' => $pmt_amt , 'tax_included' => 0);
              Insert('debtor_trans', $array);

              $total = add_gl_trans_customer_bank(ST_CUSTPAYMENT, $trans_no_payment, $tran_date,$branch["receivables_account"], 0, 0,-$pmt_amt, $selected_person,"",$rate, (isset($selected_person_currency) ? $selected_person_currency : get_company_pref('curr_default')));
              $total += add_gl_trans(ST_CUSTPAYMENT, $trans_no_payment, $tran_date, $bank['account_code'], 0, 0, '',  ($pmt_amt ), $bank['bank_curr_code'], PT_CUSTOMER, $selected_person,'',$rate);
              if ($total != 0)  {
                $variance_act = get_company_pref('exchange_diff_act');
                add_gl_trans(ST_CUSTPAYMENT, $trans_no_payment, $tran_date, -$variance_act, 0, 0, '',$total, null, PT_CUSTOMER,  $selected_person,'',$rate);
              }                          

              if(isset($diff) && $diff != 0 && isset($bank)){
                add_gl_trans(ST_CUSTPAYMENT, $trans_no_payment, $tran_date, 8310, 0, 0, '',  $diff, null, PT_CUSTOMER, $selected_person,'',0);
                if($diff > 0 ){
                                          //echo ($pmt_amt+($diff < 0  ?  $diff : $diff));
                  Update('gl_trans', array('type' => ST_CUSTPAYMENT, 'type_no' => $trans_no_payment, 'account' => $bank['account_code']), array('amount' => ($pmt_amt+($diff < 0  ?  $diff : 0 ))));
                  Update('gl_trans', array('type' => ST_CUSTPAYMENT, 'type_no' => $trans_no_payment, 'account' => $branch['receivables_account']), array('amount' => -($pmt_amt+($diff < 0  ?  $diff : $diff))));                                                    
                } else {
                  Update('gl_trans', array('type' => ST_CUSTPAYMENT, 'type_no' => $trans_no_payment, 'account' => $bank['account_code']), array('amount' => ($pmt_amt)));
                  Update('gl_trans', array('type' => ST_CUSTPAYMENT, 'type_no' => $trans_no_payment, 'account' => $branch['receivables_account']), array('amount' => -($pmt_amt+$diff)));
                }
              }

              $trans_detail_row= GetRow('debtor_trans', array('type' => ST_SALESINVOICE, 'trans_no'=> $right_inv));

              Update('debtor_trans', ['trans_no' => $right_inv, 'type' => ST_SALESINVOICE], ['alloc' => $trans_detail_row['alloc']+$pmt_amt]);
              Insert('cust_allocations', array('person_id' => $selected_person, 'amt' => $pmt_amt, 'date_alloc' => $tran_date, 'trans_no_from' => $trans_no_payment, 'trans_type_from' => ST_CUSTPAYMENT, 'trans_no_to' => $right_inv, 'trans_type_to' => ST_SALESINVOICE));
              foreach($unpaid_sales as $key => $tran){
                if($tran['trans_no'] == $right_inv)
                  unset($unpaid_sales[$key]);
              }

            } elseif(GetSingleValue('bank_trans', 'COUNT(*)', array('type' => ST_BANKDEPOSIT, 'amount' => $pmt_amt, 'trans_date' => $tran_date_, 'person_type_id' => 2, 'person_id' => $selected_person, 'account_name' => $single['accountName'])) == false && GetSingleValue('bank_trans', 'COUNT(*)', array('type' => ST_CUSTPAYMENT, 'amount' => $pmt_amt, 'trans_date' => $tran_date_, 'person_type_id' => 2, 'person_id' => $selected_person, 'account_name' => $single['accountName'])) == false){  // Customer Bank Deposits
              $type = ST_BANKDEPOSIT;
              $payment_ref =  $Refs->get_next(ST_BANKDEPOSIT, null, $tran_date); 
              $trans_no_payment = get_next_trans_no(ST_BANKDEPOSIT);
              $res = Insert('bank_trans', array('type' => ST_BANKDEPOSIT, 'trans_no'=>$trans_no_payment, 'bank_act' => $bank_id, 'ref' => $payment_ref, 'trans_date' => $tran_date_, 'amount' => $pmt_amt, 'person_type_id' => 2, 'person_id' => $selected_person, 'account_no' => $single['account'], 'account_name' => $single['accountName'], 'entry_date' => $single['date'], 'imported' => 1));
                         
              $customer = get_cust_branch_bank($selected_person);
                          //var_dump($customer);
              $res = Insert('debtor_trans', array('trans_no' => $trans_no_payment, 'type' => $type, 'alloc' => 0, 'debtor_no' => $selected_person, 'branch_code' => $customer['branch_code'], 'reference' => $payment_ref, 'tran_date' => $tran_date_, 'due_date' => '0000-00-00', 'ov_amount' => $pmt_amt));                       
                        
              add_gl_trans(ST_BANKDEPOSIT, $trans_no_payment, $tran_date, $customer['receivables_account'], 0, 0, '', -$pmt_amt, $bank['bank_curr_code'], 2, $selected_person, '', 0);
                           
              Insert('gl_trans', array('type' => ST_BANKDEPOSIT, 'type_no' => $trans_no_payment, 'account'=>$bank['account_code'], 'tran_date'=>$tran_date_,'amount'=>$pmt_amt));

            }  // end of Customer deposit

            if(isset($trans_no_payment) && $trans_no_payment > 0 && isset($payment_ref) && $payment_ref != ''){
              Insert('comments', array('type' => $type, 'id' => $trans_no_payment, 'memo_' => $description, 'date_' => $tran_date_));
              Insert('audit_trail', array('type' => $type, 'trans_no' => $trans_no_payment, 'user' => $_SESSION['wa_current_user']->user, 'fiscal_year' => $fiscal_year, 'gl_date' => $tran_date_));
              $Refs->save($type, $trans_no_payment, $payment_ref); 
            }
        } elseif($payment_type == 'D' && $selected_person > 0 ){
            $payment_ref =  ''; 
            $trans_no_payment = 0 ;
            if($new== 2){
              Delete('bank_trans', array('type' => 101, 'trans_no' => $entry['trans_no']));
              Delete('comments', array('type' => 101, 'id' => $entry['trans_no']));
            } 
            //display_error($right_inv.'__'.$selected_person);
            if($right_inv > 0 && GetSingleValue('supp_trans', 'COUNT(*)', array('type' => 22, 'ov_amount' => -$pmt_amt, 'tran_date' => $tran_date_, 'supplier_id' => $selected_person)) == false){      // Supplier Payment   
              $type = ST_SUPPAYMENT;    
              $due_date = '0000-00-00';                               
              $payment_ref =  $Refs->get_next(ST_SUPPAYMENT, null, $tran_date); 
              $trans_no_payment = get_next_trans_no(ST_SUPPAYMENT);
              $supp = GetRow('suppliers', array('supplier_id' => $selected_person));
              Insert('bank_trans', array('type' => ST_SUPPAYMENT, 'trans_no' => $trans_no_payment, 'bank_act' => $bank_id, 'ref' => $payment_ref, 'trans_date' => $tran_date_, 'amount' => -$pmt_amt, 'person_type_id' => 3, 'person_id' => $selected_person, 'account_no' => $single['account'], 'account_name' => $single['accountName'], 'entry_date' => $single['date'], 'imported' => 1));
              $CI_alloc += $pmt_amt;
              $array = array('trans_no' => $trans_no_payment, 'type' => ST_SUPPAYMENT, 'supplier_id' => $selected_person, 'reference' => $payment_ref, 'supp_reference' => '', 'tran_date' => $tran_date_, 'due_date' => $due_date, 'ov_amount' => -$pmt_amt, 'ov_discount' => 0, 'ov_gst' => 0, 'rate' => 1, 'alloc' => $pmt_amt, 'tax_included' => 0);
              Insert('supp_trans', $array,false);

              $total = add_gl_trans_supplier_bank(ST_SUPPAYMENT, $trans_no_payment, $tran_date, $supp["payable_account"], 0, 0, $pmt_amt, $selected_person,"", $rate,'', $supp['curr_code']);
              $total += add_gl_trans(ST_SUPPAYMENT, $trans_no_payment, $tran_date, $bank['account_code'], 0, 0, '',  -($pmt_amt ), $bank['bank_curr_code'], PT_SUPPLIER, $selected_person,'',$rate);

                          /*Post a balance post if $total != 0 due to variance in AP and bank posted values*/
              if ($total != 0)  {
                $variance_act = get_company_pref('exchange_diff_act');
                add_gl_trans(ST_SUPPAYMENT, $trans_no_payment, $tran_date, $variance_act, 0, 0, '',-$total, null, PT_SUPPLIER,  $selected_person,'',$rate);
              }

              $trans_detail_row= GetRow('supp_trans', array('type' => ST_SUPPINVOICE, 'trans_no'=> $right_inv));

              Update('supp_trans', ['trans_no' => $right_inv, 'type' => ST_SUPPINVOICE], ['alloc' => $trans_detail_row['alloc']+$pmt_amt]);
              Insert('supp_allocations', array('person_id' => $selected_person, 'amt' => $pmt_amt, 'date_alloc' => $tran_date, 'trans_no_from' => $trans_no_payment, 'trans_type_from' => ST_SUPPAYMENT, 'trans_no_to' => $right_inv, 'trans_type_to' => ST_SUPPINVOICE));

              foreach($unpaid_purchase as $key => $tran){
                if($tran['trans_no'] == $right_inv)
                  unset($unpaid_purchase[$key]);
              }

            } elseif(GetSingleValue('bank_trans', 'COUNT(*)', array('type' => ST_BANKPAYMENT, 'amount' => -$pmt_amt, 'trans_date' => $tran_date_, 'person_type_id' => 3, 'person_id' => $selected_person, 'account_name' => $single['accountName'])) == false && GetSingleValue('bank_trans', 'COUNT(*)', array('type' => ST_SUPPAYMENT, 'amount' => -$pmt_amt, 'trans_date' => $tran_date_, 'person_type_id' => 3, 'person_id' => $selected_person, 'account_name' => $single['accountName'])) == false) { // Bank Payment
                        //echo GetSingleValue('supp_trans', 'COUNT(*)', array('type' => ST_BANKPAYMENT, 'ov_amount' => $pmt_amt, 'tran_date' => $tran_date_, 'supplier_id' => $selected_person), null, true);
              $type = ST_BANKPAYMENT;
              $payment_ref =  $Refs->get_next(ST_BANKPAYMENT, null, $tran_date); 
              $trans_no_payment = get_next_trans_no(ST_BANKPAYMENT);
              $res = Insert('bank_trans', array('type' => ST_BANKPAYMENT, 'trans_no'=>$trans_no_payment, 'bank_act' => $bank_id, 'ref' => $payment_ref, 'trans_date' => $tran_date_, 'amount' => -$pmt_amt, 'person_type_id' => 3, 'person_id' => $selected_person, 'account_no' => $single['account'], 'account_name' => $single['accountName'], 'entry_date' => $single['date'], 'imported' => 1));
                         
              $supplier = GetRow('suppliers', array('supplier_id' => $selected_person));
                          //var_dump($customer);
              $res = Insert('supp_trans', array('trans_no' => $trans_no_payment, 'type' => $type, 'alloc' => 0, 'supplier_id' => $selected_person,  'reference' => $payment_ref, 'tran_date' => $tran_date_, 'due_date' => '0000-00-00', 'ov_amount' => -$pmt_amt));                       
                        
              add_gl_trans(ST_BANKPAYMENT, $trans_no_payment, $tran_date, $supplier['payable_account'], 0, 0, '', $pmt_amt, $bank['bank_curr_code'], 3, $selected_person, '', 0);
                           
              Insert('gl_trans', array('type' => ST_BANKPAYMENT, 'type_no' => $trans_no_payment, 'account'=>$bank['account_code'], 'tran_date'=>$tran_date,'amount'=>-$pmt_amt));
            }
            if(isset($trans_no_payment) && $trans_no_payment > 0 && isset($payment_ref) && $payment_ref != ''){
              Insert('comments', array('type' => $type, 'id' => $trans_no_payment, 'memo_' => $description, 'date_' => $tran_date_));
              Insert('audit_trail', array('type' => $type, 'trans_no' => $trans_no_payment, 'user' => $_SESSION['wa_current_user']->user, 'fiscal_year' => $fiscal_year, 'gl_date' => $tran_date_));
              $Refs->save($type, $trans_no_payment, $payment_ref); 
            }
          } elseif($new==0) {
            $trans_no_payment = get_next_trans_no(ST_UNDEFINED);
            Insert('bank_trans', array('type' => ST_UNDEFINED, 'trans_no' => $trans_no_payment, 'bank_act' => $bank_id, 'ref' => '', 'trans_date' => $tran_date_, 'amount' => ($payment_type == 'D' ? -$pmt_amt: $pmt_amt), 'person_type_id' => 0, 'person_id' => null, 'account_no' => $single['account'], 'account_name' => $single['accountName'], 'entry_date' => $single['date'], 'imported' => 1));
            Insert('comments', array('type' => ST_UNDEFINED, 'id' => $trans_no_payment, 'memo_' => $description, 'date_' => $tran_date_));
          }
      }                  
    }   

    commit_transaction();
    return $bank_id;
  //}
}

// function get_next_trans_no ($trans_type, TB_PREF=null){ 
 
//   $st = get_systype_db_info($trans_type);
//   if (!($st && $st[0] && $st[2])) { // this is in fact internal error condition.
//     display_error( _('Internal error: invalid type passed to get_next_trans_no()'));
//     return 0;
//   }
//   $sql1 = "SELECT MAX(`$st[2]`) as last_no FROM $st[0]";
//   if ($st[1] != null)
//      $sql1 .= " WHERE `$st[1]`=".db_escape($trans_type);
//   // check also in voided transactions (some transactions like location transfer are removed completely)
//   $sql2 = "SELECT MAX(`id`) as last_no FROM ".TB_PREF."voided WHERE `type`=".db_escape($trans_type);
//   $sql = "SELECT max(last_no) last_no FROM ($sql1 UNION $sql2) a";
//   $result = db_query($sql, "Retreive currency of customer $customer_id");
//   $res = 0;

//   if($myrow=db_fetch_row($result))
//     $res = $myrow['last_no'];

//   return $res + 1;
// }

function add_gl_trans_supplier_bank($type, $type_no, $date_, $account, $dimension, $dimension2, $amount, $supplier_id, $err_msg="", $rate=0, $memo="", $currency ='USD'){
  if ($err_msg == "")
    $err_msg = "The supplier GL transaction could not be inserted"; 
    
  return add_gl_trans($type, $type_no, $date_, $account, $dimension, $dimension2, $memo,  $amount, $currency,  PT_SUPPLIER, $supplier_id, $err_msg, $rate);
}

function add_gl_trans_customer_bank($type, $type_no, $date_, $account, $dimension, $dimension2, $amount, $customer_id, $err_msg="", $rate=0, $currency='USD'){
  if ($err_msg == "")
    $err_msg = "The customer GL transaction could not be inserted";

  return add_gl_trans($type, $type_no, $date_, $account, $dimension, $dimension2, "", $amount,  get_customer_currency($customer_id),  PT_CUSTOMER, $customer_id, $err_msg, $rate);
}

?>