<?php
/**********************************************************************
***********************************************************************/

$page_security = 'SA_REP_PAY_VOUCHER';
// ----------------------------------------------------------------
// $ Revision:	2.0 $
// Creator:	Joe Hunt
// date_:	2005-05-19
// Title:	Purchase Remittance/SA_REP_PAY_VOUCHER
// ----------------------------------------------------------------
$path_to_root="..";

include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/includes/db/crm_contacts_db.inc");
include_once($path_to_root . "/purchasing/includes/db/suppliers_db.inc"); 
include_once($path_to_root . "/sales/includes/db/customers_db.inc"); 
include_once($path_to_root . "/payroll/includes/db/employees_db.inc"); 
include_once($path_to_root . "/gl/includes/ui/print_payment_vouchers_ui.inc"); 
include_once($path_to_root . "/gl/includes/db/print_payment_vouchers_db.inc"); 
include_once($path_to_root . "/gl/includes/db/pre_gl_adjustments_db.inc");
include_once($path_to_root . "/admin/db/list_values_db.inc");  
include_once($path_to_root . "/sales/includes/db/customers_db.inc"); 
include_once($path_to_root . "/gl/includes/db/batch_bank_transfer_db.inc"); 
include_once($path_to_root . "/petty_cash/includes/db/petty_cash_payments_db.inc"); 

print_payment_vouchers();

function get_bank_trans_payment_voucher($trans_no, $type, $person_id, $person_type_id) {
    $sql = "SELECT bt.*, bk.bank_account_name 
            FROM ".TB_PREF."bank_trans bt 
                JOIN ".TB_PREF."bank_accounts bk 
                    ON bt.bank_act = bk.id 
            WHERE bt.trans_no = ".db_escape($trans_no)." 
                AND bt.type = ".db_escape($type)." 
                AND bt.person_id = ".db_escape($person_id)." 
                AND bt.person_type_id = ".db_escape($person_type_id);
        
   	$result = db_query($sql, "get_bank_trans_payment_voucher");
        
        return db_fetch($result);
}

function get_student_customer($debtor_no) {
    $sql = "SELECT *   
            FROM ".TB_PREF."students_master  
            WHERE debtor_no = ".db_escape($debtor_no);

        $result = db_query($sql, "get_student_customer");
        return db_fetch($result);
}

function get_customer_address($debtor_no) {
    $sql = "SELECT address  
            FROM ".TB_PREF."debtors_master dm 
                LEFT JOIN ".TB_PREF."cust_branch cb 
                    ON dm.debtor_no = cb.debtor_no 
            WHERE dm.debtor_no = ".db_escape($debtor_no);

        $result = db_query($sql, "get_customer_address");
        return db_result_value($result, 'address', '');
}

function get_customer_name_and_address($debtor_no) {
    $stu_customer = get_student_customer($debtor_no);
        if (is_array($stu_customer)) {
            $customer_name = get_student_formatted_name($stu_customer['student_id']);
            $stu_contct = get_contact_details_latest_record(CDO_STUDENT, $stu_customer['student_id']);
                $customer_address = $stu_contct['address'];
        } else {
            $customer_name = get_customer_formatted_name($debtor_no);
            $customer_address = get_customer_address($debtor_no);
        }
    
        return array('customer_name' => $customer_name, 'customer_address' => $customer_address);
}

function get_customer_allocations($trans_type, $trans_no) {
    $sql = "SELECT ca.*, trans_type_to type, date_alloc tran_date, amt alloc, 
                    bt.trans_no, ABS(bt.amount) Total, '' reference 
            FROM ".TB_PREF."cust_allocations ca 
                JOIN ".TB_PREF."bank_trans bt  
                    ON ca.trans_no_to = bt.trans_no  
                        AND ca.trans_type_to = bt.type 
            WHERE bt.trans_no = ".db_escape($trans_no)." 
                AND bt.type = ".db_escape($trans_type);

        return db_query($sql, "get_customer_allocations");
}

function get_employee_by_id($id) {
    $sql = "SELECT * 
            FROM ".TB_PREF."employee_master 
            WHERE employee_id = ".db_escape($id);
    
        $result = db_query($sql, "get_employee_by_id");

        return db_fetch($result);
}

function get_supplier_payment_voucher($trans_no, $type) { 
   	$sql = "SELECT ".TB_PREF."supp_trans.*, 
                    (".TB_PREF."supp_trans.ov_amount+".TB_PREF."supp_trans.ov_gst) AS amount,
                    ".TB_PREF."supp_trans.ov_discount,
                    ".TB_PREF."suppliers.supp_name,  ".TB_PREF."suppliers.supp_account_no, 
                    ".TB_PREF."suppliers.curr_code, ".TB_PREF."suppliers.payment_terms, ".TB_PREF."suppliers.gst_no AS tax_id, 
                    ".TB_PREF."suppliers.address, ".TB_PREF."currencies.hundreds_name, 
                    bt.cheque_no, bt.bank_act,    
                    ".TB_PREF."supp_trans.reference ref, 
                    ".TB_PREF."supp_trans.tran_date trans_date,
                    ".PT_SUPPLIER." person_type_id,
                    ".TB_PREF."supp_trans.supplier_id person_id,
                    ".TB_PREF."payment_vouchers.voucher_date, ".TB_PREF."payment_vouchers.voucher_code, ".TB_PREF."payment_vouchers.voucher_reference,
                    lv.value_name bank_account_name 
            
		FROM ".TB_PREF."supp_trans 
                    JOIN ".TB_PREF."suppliers 
                        ON ".TB_PREF."supp_trans.supplier_id = ".TB_PREF."suppliers.supplier_id 
                            
                    JOIN ".TB_PREF."currencies 
                        ON ".TB_PREF."suppliers.curr_code = ".TB_PREF."currencies.curr_abrev 
                        
                    LEFT JOIN ".TB_PREF."bank_trans bt 
                        ON ".TB_PREF."supp_trans.trans_no = bt.trans_no  
                        AND ".TB_PREF."supp_trans.type = bt.type  
                            
                    LEFT JOIN ".TB_PREF."payment_vouchers 
                        ON ".TB_PREF."supp_trans.trans_no = ".TB_PREF."payment_vouchers.trans_no  
                        AND ".TB_PREF."supp_trans.type = ".TB_PREF."payment_vouchers.type 
                           
                    LEFT JOIN ".TB_PREF."bank_accounts act 
                        ON act.id = bt.bank_act 
                        
                    LEFT JOIN ".TB_PREF."list_values lv 
                        ON act.bank_id = lv.id 
                            
		WHERE ".TB_PREF."supp_trans.trans_no = ".db_escape($trans_no)." AND ".TB_PREF."supp_trans.type = ".db_escape($type); 
                
        
   	return db_query($sql, "The payment voucher cannot be retrieved");
}

function rep_get_iou_payment_voucher($trans_no, $type) { 
   	$sql = "SELECT ioup.*,
                    0 bank_act, 
                    ioup.id trans_no, 
                    $type type,
                    ".PT_EMPLOYEE." person_type_id,
                    iou.employee_code person_id,
                    pv.voucher_code, pv.voucher_reference, pv.voucher_date   
		FROM ".TB_PREF."i_owe_you_payments ioup  
                    JOIN ".TB_PREF."i_owe_you iou 
                        ON iou.id = ioup.iou_id 
                        AND ioup.expense_source = ". db_escape(ST_I_OWE_YOU)." 
                    JOIN ".TB_PREF."payment_vouchers pv 
                        ON ioup.id = pv.trans_no  
                        AND pv.type = ". db_escape(ST_I_OWE_YOU_PAYMENT)."
		WHERE ioup.id = ".db_escape($trans_no)." AND ioup.expense_source = ".db_escape(ST_I_OWE_YOU); 
                
        
   	return db_query($sql, "The payment voucher cannot be retrieved");
}

function get_supplier_allocations($type, $trans_no) {
    $sql = "SELECT *
		FROM ".TB_PREF."supp_allocations sa
		WHERE (sa.trans_type_from = ".db_escape($type)." AND sa.trans_no_from =".db_escape($trans_no).") 
                    OR (sa.trans_type_to = ".db_escape($type)." AND sa.trans_no_to =".db_escape($trans_no).")";
    
    $result = db_query($sql, "The payment voucher cannot be retrieved");
    if (db_num_rows($result) == 0) {
        return false;
    } else {
        return true;
    }
}

function get_allocations_for_payment_voucher($supplier_id, $type, $trans_no) {
    $sql = "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,
                supplier.address
            FROM ".TB_PREF."supp_trans as trans
                LEFT JOIN ".TB_PREF."suppliers as supplier 
                    ON trans.supplier_id=supplier.supplier_id
            WHERE trans.trans_no=".db_escape($trans_no)."
                AND trans.type=".db_escape($type)." 
                AND trans.supplier_id=".db_escape($supplier_id);

    $sql .= " ORDER BY trans_no";
    
    return db_query($sql, "Cannot retreive alloc to transactions");
}

function get_bank_trans_new($trans_no, $trans_no_2, $type, $person_type_id=null, $person_id=null) {
    $sql = "SELECT bt.*, act.*,
            lv.value_name bank_account_name,
            IFNULL(abs(dt.ov_amount), IFNULL(ABS(st.ov_amount), bt.amount)) settled_amount,
            IFNULL(abs(dt.ov_amount/bt.amount), IFNULL(ABS(st.ov_amount/bt.amount), 1)) settle_rate,
            IFNULL(debtor.curr_code, IFNULL(supplier.curr_code, act.bank_curr_code)) settle_curr,
            crr.hundreds_name, st.tran_date, st.reference, st.ov_amount,
            pv.voucher_type_id, pv.voucher_date, pv.voucher_code, pv.voucher_reference 
            
            FROM ".TB_PREF."bank_trans bt
                LEFT JOIN ".TB_PREF."debtor_trans dt ON dt.type=bt.type AND dt.trans_no=bt.trans_no
                LEFT JOIN ".TB_PREF."debtors_master debtor ON debtor.debtor_no = dt.debtor_no
                LEFT JOIN ".TB_PREF."supp_trans st ON st.type=bt.type AND st.trans_no=bt.trans_no
                LEFT JOIN ".TB_PREF."suppliers supplier ON supplier.supplier_id = st.supplier_id
                LEFT JOIN ".TB_PREF."currencies crr ON supplier.curr_code = crr.curr_abrev 
                LEFT JOIN ".TB_PREF."payment_vouchers pv ON bt.type = pv.type AND bt.trans_no = pv.trans_no,  
                          ".TB_PREF."bank_accounts act
                LEFT JOIN ".TB_PREF."list_values lv ON act.bank_id = lv.id 

            WHERE act.id = bt.bank_act ";
    
    if ($type != null)
        $sql .= " AND bt.type = ".db_escape($type);
    if ($trans_no != null && $trans_no_2 != null)
        $sql .= " AND bt.trans_no >= ".db_escape($trans_no)." AND bt.trans_no <= ".db_escape($trans_no_2);
    if ($person_type_id != null)
        $sql .= " AND bt.person_type_id = ".db_escape($person_type_id);
    if ($person_id != null)
        $sql .= " AND bt.person_id = ".db_escape($person_id);
    
    $sql .= " ORDER BY trans_date, bt.id";

    return db_query($sql, "query for bank transaction");
}

function get_alloc_supp_sql_report($extra_fields=null, $extra_conditions=null, $extra_tables=null) {
    $sql = "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,
                supplier.address";

    if ($extra_fields)
        $sql .= ", $extra_fields ";

    $sql .= " FROM ".TB_PREF."supp_trans as trans, ".TB_PREF."suppliers as supplier";
    
    if ($extra_tables)
        $sql .= " ,$extra_tables ";

    $sql .= " WHERE trans.supplier_id=supplier.supplier_id";

    if ($extra_conditions)
        $sql .= " AND $extra_conditions";

    return $sql;
}

function get_allocations_for_payment_voucher_allocations($supplier_id, $type, $trans_no) {
    $sql = get_alloc_supp_sql_report("amt, supp_reference, trans.alloc", "trans.trans_no = alloc.trans_no_to
            AND trans.type = alloc.trans_type_to
            AND alloc.trans_no_from=".db_escape($trans_no)."
            AND alloc.trans_type_from=".db_escape($type)."
            AND trans.supplier_id=".db_escape($supplier_id),
            TB_PREF."supp_allocations as alloc");
    $sql .= " ORDER BY trans_no";
    
    return db_query($sql, "Cannot retreive alloc to transactions");
}

function get_bank_payments_for_report($type, $trans_id) {
	$sql = "SELECT gl.*, cm.account_name, IFNULL(refs.reference, '') AS reference, user.real_name, 
			COALESCE(st.tran_date, dt.tran_date, bt.trans_date, grn.delivery_date, gl.tran_date) as doc_date,
			IF(ISNULL(st.supp_reference), '', st.supp_reference) AS supp_reference
	FROM ".TB_PREF."gl_trans as gl
		LEFT JOIN ".TB_PREF."chart_master as cm ON gl.account = cm.account_code
		LEFT JOIN ".TB_PREF."refs as refs ON (gl.type=refs.type AND gl.type_no=refs.id)
		LEFT JOIN ".TB_PREF."audit_trail as audit ON (gl.type=audit.type AND gl.type_no=audit.trans_no AND NOT ISNULL(gl_seq))
		LEFT JOIN ".TB_PREF."users as user ON (audit.user=user.id)
	# all this below just to retrieve doc_date :>
		LEFT JOIN ".TB_PREF."supp_trans st ON gl.type_no=st.trans_no AND st.type=gl.type AND (gl.type!=".ST_JOURNAL." OR gl.person_id=st.supplier_id)
		LEFT JOIN ".TB_PREF."grn_batch grn ON grn.id=gl.type_no AND gl.type=".ST_SUPPRECEIVE." AND gl.person_id=grn.supplier_id
		LEFT JOIN ".TB_PREF."debtor_trans dt ON gl.type_no=dt.trans_no AND dt.type=gl.type AND (gl.type!=".ST_JOURNAL." OR gl.person_id=dt.debtor_no)
		LEFT JOIN ".TB_PREF."bank_trans bt ON bt.type=gl.type AND bt.trans_no=gl.type_no AND bt.amount!=0
			 AND bt.person_type_id=gl.person_type_id AND bt.person_id=gl.person_id
		LEFT JOIN ".TB_PREF."journal j ON j.type=gl.type AND j.trans_no=gl.type_no"

		." WHERE gl.type= ".db_escape($type) 
		." AND gl.type_no = ".db_escape($trans_id)
		." AND gl.amount > 0"
		." ORDER BY tran_date, counter";

	return db_query($sql, "get_bank_payments_for_report");
}

function rep_get_i_owe_you_payments_for_voucher_printing($type, $trans_id) {
	$sql = "SELECT ioup.*, ioup.comment memo_, 
                    '' account, pcf.name account_name 
                FROM ".TB_PREF."i_owe_you_payments as ioup 
                    JOIN ".TB_PREF."petty_cash_floats as pcf 
                        ON pcf.id = ioup.float_id  
		WHERE ioup.expense_source = ".db_escape(ST_I_OWE_YOU)." 
		AND ioup.id = ".db_escape($trans_id)." 
		ORDER BY ioup.payment_date, ioup.id ";

	return db_query($sql, "rep_get_i_owe_you_payments_for_voucher_printing");
}

function get_journal_trans_new($trans_no, $trans_no_2, $type, $person_type_id=null, $person_id=null) {
    $sql = "SELECT bt.*, act.*,
            IFNULL(abs(dt.ov_amount), IFNULL(ABS(st.ov_amount), bt.amount)) settled_amount,
            IFNULL(abs(dt.ov_amount/bt.amount), IFNULL(ABS(st.ov_amount/bt.amount), 1)) settle_rate,
            IFNULL(debtor.curr_code, supplier.curr_code) settle_curr,
            crr.hundreds_name, bt.tran_date, bt.reference, st.ov_amount, 
            '' bank_act, bt.reference ref, bt.tran_date trans_date,
            pv.voucher_type_id, pv.voucher_date, pv.voucher_code, pv.voucher_reference 
            FROM ".TB_PREF."journal bt
                JOIN ".TB_PREF."gl_trans gl ON bt.type=gl.type AND bt.trans_no=gl.type_no 
                LEFT JOIN ".TB_PREF."debtor_trans dt ON dt.type=bt.type AND dt.trans_no=bt.trans_no
                LEFT JOIN ".TB_PREF."debtors_master debtor ON debtor.debtor_no = dt.debtor_no
                LEFT JOIN ".TB_PREF."supp_trans st ON st.type=bt.type AND st.trans_no=bt.trans_no
                LEFT JOIN ".TB_PREF."suppliers supplier ON supplier.supplier_id = st.supplier_id
                LEFT JOIN ".TB_PREF."currencies crr ON supplier.curr_code = crr.curr_abrev 
                LEFT JOIN ".TB_PREF."payment_vouchers pv ON bt.type = pv.type AND bt.trans_no = pv.trans_no,   
                          ".TB_PREF."chart_master act

            WHERE act.account_code = gl.account ";
    
    if ($type != null)
        $sql .= " AND bt.type = ".db_escape($type);
    if ($trans_no != null && $trans_no_2 != null)
        $sql .= " AND bt.trans_no >= ".db_escape($trans_no)." AND bt.trans_no <= ".db_escape($trans_no_2);
    if ($person_type_id != null)
        $sql .= " AND bt.person_type_id = ".db_escape($person_type_id);
    if ($person_id != null)
        $sql .= " AND bt.person_id = ".db_escape($person_id);
    
    $sql .= " ORDER BY bt.tran_date, gl.counter LIMIT 1";

    return db_query($sql, "get_journal_trans_new");
}

function draw_payment_items_table($column_headers_start, &$rep, &$st_row) {
    $rep->row = $column_headers_start;
    
    $iline7 = $column_headers_start + 12;
    $iline5 = $column_headers_start - 5;
    
    $rep->LineTo(25, $iline7, 570, $iline7);
    $rep->LineTo(25, $iline5, 570, $iline5);
    
    $top_line_row = $iline7;
    $st_row = $top_line_row;
}

function draw_vertical_lines_from_loop(&$rep, &$st_row, &$ed_row) {
    $rep->LineTo(25, $st_row, 25, $ed_row);
    $rep->LineTo(85, $st_row, 85, $ed_row);
    $rep->LineTo(500, $st_row, 500, $ed_row);
    $rep->LineTo(570, $st_row, 570, $ed_row);
}

function draw_table_cloase_horizontal_line_after_loop(&$rep, $ed_row) {
    $rep->LineTo(25, $ed_row, 570, $ed_row);
}

function get_latest_cheque_print_report($trans_no, $trans_type) {
    $sql = "SELECT cpg.*,
                ba.bank_account_number,
                 bn.value_name bank_name,
                crsn.value_name crossing_name,
                us.real_name created_user
            FROM ".TB_PREF."cheque_printing_log cpg
                LEFT JOIN ".TB_PREF."bank_accounts ba 
                    ON cpg.bank_account = ba.id
                INNER JOIN ".TB_PREF."list_values bn 
                    ON ba.bank_id = bn.id         
                LEFT JOIN ".TB_PREF."list_values crsn 
                    ON cpg.crossing_id = crsn.id 
                LEFT JOIN ".TB_PREF."users us 
                    ON us.id = cpg.created_by
            WHERE cpg.type =". db_escape($trans_type)." AND cpg.trans_no = ". db_escape($trans_no);

    $sql .= " ORDER BY cpg.id DESC LIMIT 1";
             
    $result = db_query($sql,"Could not cheque_printing details");        
    return db_fetch($result);
}

function get_pre_journal($type, $trans_no) {
    $sql = "SELECT * FROM ".TB_PREF."pre_journal 
            WHERE `type` = ".db_escape($type)." AND `trans_no` = ".db_escape($trans_no);

    $myrow = db_query($sql, 'get_pre_journal');
    return db_fetch($myrow);
}

function display_voucher_header_details($rep, $print_table=true) {
    
    global $systypes_array;
    
    $payeee_name = $payeee_address = '';
        switch ($rep->params['trans_type']) {
            case ST_SUPPAYMENT:
                    $supplier = get_supplier($rep->params['person_id']);
                    if (is_array($supplier)) {
                        $payeee_name = get_supplier_formatted_name($supplier['supplier_id']);
                        $payeee_address = $supplier['address'];
                    }
                break;
            
            case ST_BANKPAYMENT:
            case ST_CASH_PAYMENT:
                        switch ($rep->params['person_type_id']) {
                            case PT_MISC:
                                    $payeee_name = $rep->params['person_id'];
                                break;
                            case PT_CUSTOMER:
                                $customer = get_customer_name_and_address($rep->params['person_id']);
                                    $payeee_name = $customer['customer_name'];
                                    $payeee_address = $customer['customer_address'];
                                break;
                            case PT_SUPPLIER:
                                $supplier = get_supplier($rep->params['person_id']);
                                    if (is_array($supplier)) {
                                        $payeee_name = $supplier['supp_name'];
                                        $payeee_address = $supplier['address'];
                                    }
                                break;
                            case PT_QUICKENTRY:
                                break;
                            case PT_EMPLOYEE:
                                $employee = get_employee_by_id($rep->params['person_detail_id']);
                                    if (is_array($employee)) {
                                        $payeee_name = get_employee_formatted_long_name($employee['employee_code']);
                                    }
                                break;

                            default:
                                break;
                        }
                break;
                        
            case ST_BANKTRANSFER:
                $bank_transfer = get_bank_transfer_record($rep->params['trans_no'], false);
                $payeee_name = get_bank_account_formatted_name($bank_transfer['bank_act']);
                break;
                        
            case ST_I_OWE_YOU_PAYMENT:
                $employee = get_employee($rep->params['person_id']);
                $payeee_name = get_employee_formatted_long_name($employee['employee_code']);
                break;
        }

        $cheque_details = get_latest_cheque_print_report($rep->params['trans_no'], $rep->params['type']);
    
                $rep->row += 40;

                $row_line = $rep->row;

                $rep->RoundedRect(30, 100, 260, 80, 10);

                $rep->row = $row_line;
                $rep->Text(45, "Payee :");
                $rep->Font('bold');
                $rep->TextWrapLines(100, 190, $payeee_name);

                $rep->NewLine(1);
                $rep->TextWrapLines(100, 190, $payeee_address);
                $rep->Font();


                $rep->row = $row_line; 

                $rep->Text(340, _("Voucher No :"));
                $rep->Font('bold');
                $rep->Text(440, $rep->params['voucher_code']);
                $rep->Font();
                $rep->row -= 4; 

                $rep->NewLine();
                $rep->Text(340, _("Chq/Online No. :"));
                $rep->Font('bold');
                $voucher_reference = "........................";
                if(strlen($rep->params['cheque_no']) > 0){
                    $voucher_reference = $rep->params['cheque_no'];
                }                
                $rep->Text(440, $voucher_reference);
                $rep->Font();
                $rep->row -= 4; 

                $rep->NewLine();
                $rep->Text(340, _("Date :"));
                $rep->Font('bold');
                $rep->Text(440, sql2date($rep->params['voucher_date']));
                $rep->Font();
                $rep->row -= 4; 

                $rep->NewLine();
                $rep->Text(340, _("Amount :"));
                $rep->Font('bold');
                $rep->Text(440, number_format(abs($rep->params['amount']), 2));
                $rep->Font();
                $rep->row -= 4; 

                $rep->NewLine();
                $rep->Font('I');
                $rep->Text(340, $systypes_array[$rep->params['type']]." #".$rep->params['trans_no']);
                $rep->Font();
                $rep->row -= 4; 

                if(isset($rep->params['cheque_no']) && $rep->params['cheque_no'] > 0){
                    $rep->NewLine();
                    $rep->Text(25, _("Cheque No").":");
                    $rep->Font('bold');
                    $rep->Text(80, $rep->params['cheque_no']);
                    $rep->Font();
                    $rep->Text(150, _("Cheque Date").":");
                    $rep->Font('bold');
                    $rep->Text(215, (isset($cheque_details['cheque_date'])) ? sql2date($cheque_details['cheque_date']) : '');
                    $rep->Font();
                    $rep->Text(300, _("Bank").":");
                    $rep->Font('bold');
                    $rep->Text(330, $rep->params['bank_account_name']);
                    $rep->Font();

                    $rep->row -= 4; 
                }
                
                $st_row = 0;
                
                if ($print_table) {
                    $column_headers_start = $rep->row - $rep->lineHeight * 2;
                    draw_payment_items_table($column_headers_start, $rep, $st_row);
                    
                    $rep->Font('bold');
                    $rep->Text(33, 'Acc. Code');
                    $rep->Text(270, 'Details');
                    $rep->Text(518, 'Amount');
                    $rep->Font();
                }
                
                
                $rep->NewLine(2);
                
                return $st_row;
}

function display_vouchers_footer_details($rep) {
    $rep->Text(30, "Prepared By");
    $rep->Text(90, _("..........................................."));
    $rep->Text(230, "Authorized By");
    $rep->Text(280, _("..........................................."));
    $rep->Text(410, "Approved By");
    $rep->Text(470, _("..........................................."));
    $rep->NewLine(2);
    $rep->Text(30, _("Received By"));                      
    $rep->Text(90, _("..........................................."));
    $rep->Text(230, "Signature");
    $rep->Text(280, _("..........................................."));
    $rep->Text(410, "Date");
    $rep->Text(470, _("..........................................."));
}


function print_payment_vouchers() {
    global $path_to_root;

    include_once($path_to_root . "/reporting/includes/pdf_report.inc");

    $trans_type = $_POST['PARAM_0'];
    $trans_no = $_POST['PARAM_1'];
    $voucher_type_id = $_POST['PARAM_2'];
    $voucher_date = $_POST['PARAM_3'];
    $voucher_reference = $_POST['PARAM_4'];
    $bank_account_id = $_POST['PARAM_5'];
    
//    get_next_trans_no($trans_type);
    $msg = save_payment_vouchers($trans_type, $trans_no, $voucher_type_id, $voucher_date, $voucher_reference, $bank_account_id);
        if ($msg['success'] !== true) {
            display_error($msg['message']);
            return;
        }
    
    $trans_no_2 = $trans_no;

    if (! $trans_no || ! $trans_no_2) return;

    $dec = user_price_dec();

    $cols = array(4, 60, 160, 210, 275, 360, 450, 528);

    // $headers in doctext.inc
    $aligns = array('center', 'left', 'center', 'left', 'right', 'right', 'right');
    $headers  = array(_("Date"),_(" Type"), _("#"), _(" Reference"), _("Total Amount"), _("Left to Allocate"), _("This Allocation"));
    $params = array('voucher_type_id' => $voucher_type_id);

    $cur = get_company_Pref('curr_default');


    $rep = new FrontReport(_('PAYMENT VOUCHER'), "PaymentVoucher", 'A4', 9, 'P');
    
        switch ($trans_type) {
            case ST_BANKPAYMENT:
            case ST_BANKTRANSFER:
			case ST_PETTY_CASH_FLOAT_REIMBUR:
                $result = get_bank_trans_new($trans_no, $trans_no_2, $trans_type);
                    $myrow = db_fetch($result);
                break;            
            case ST_CASH_PAYMENT:
                $result = get_journal_trans_new($trans_no, $trans_no_2, $trans_type);
                    $myrow = db_fetch($result);
                break;
            case ST_SUPPAYMENT:
                $result = get_supplier_payment_voucher($trans_no, $trans_type);
                    $myrow = db_fetch($result);
                break;
            case ST_I_OWE_YOU_PAYMENT:
                $result = rep_get_iou_payment_voucher($trans_no, $trans_type);
                    $myrow = db_fetch($result);
                break;
        }
        
        $params['trans_type'] = $trans_type;
        $params['bankaccount'] = $myrow['bank_act'];
        $params['tran_no'] = $myrow['trans_no'];
        $params['trans_no'] = $myrow['trans_no'];
        $params['type'] = $myrow['type'];
        $params['person_type_id'] = $myrow['person_type_id'];
        $params['person_id'] = $myrow['person_id'];
        if ($trans_type == ST_CASH_PAYMENT) {
            $pre_journal = get_pre_journal($trans_type, $trans_no);
                $params['person_detail_id'] = $pre_journal['person_detail_id'];
        } else {
            $params['person_detail_id'] = isset ($myrow['person_detail_id']) ? $myrow['person_detail_id'] : 0;
        }
        $params['voucher_code'] = $myrow['voucher_code'];
        $params['voucher_reference'] = $myrow['voucher_reference'];
        $params['voucher_date'] = $myrow['voucher_date'];
        $params['amount'] = abs($myrow['amount']);
        $params['cheque_no'] = isset ($myrow['cheque_no']) ? $myrow['cheque_no'] : '';
        $params['bank_account_name'] = isset ($myrow['bank_account_name']) ? $myrow['bank_account_name'] : '';

        $rep->SetHeaderType('form_650');
        $rep->currency = $cur;
        $rep->Font();
        
        
        $rep->Info($params, $cols, $headers, $aligns);
        
        $rep->NewPage();
        
        $st_row = display_voucher_header_details($rep);
        
                        
                        $brs = 12;
                        
                        switch ($trans_type) {
                            case ST_BANKPAYMENT:
                            case ST_BANKTRANSFER:
                            case ST_PETTY_CASH_FLOAT_REIMBUR:
                                $items_result = get_bank_payments_for_report($trans_type, $trans_no);

                                break;
                            case ST_CASH_PAYMENT:
                                $items_result = get_bank_payments_for_report($trans_type, $trans_no);

                                break;
                            case ST_SUPPAYMENT:
                                $items_result = get_bank_payments_for_report($trans_type, $trans_no);

                                break;
                            case ST_I_OWE_YOU_PAYMENT:
                                $items_result = rep_get_i_owe_you_payments_for_voucher_printing($trans_type, $trans_no);

                                break;
                        }
                        
                        $db_num_rows = db_num_rows($items_result);
                        $add_new_line = false;
                            while ($item = db_fetch($items_result)) {
                                $loop_row = $rep->row;
                                
                                if ($add_new_line) {
                                    $rep->NewLine();
                                }
                                
                                if ($rep->row < $rep->bottomMargin + (6 * $rep->lineHeight)) {
                                    $ed_row = $rep->row;
                                    $ed_row += 12;
                                    draw_table_cloase_horizontal_line_after_loop($rep, $ed_row);
                                    
                                    $rep->NewLine(2);
                                    display_vouchers_footer_details($rep);
                                    
                                    $rep->NewPage();
                                    
                                    $loop_row = display_voucher_header_details($rep);
                                }
                                
                                $rep->Text(28, $item['account']);
                                $rep->Text(88, $item['account_name']);
                                $rep->TextCol(6, 7, number_format($item['amount'], 2));
                                
                                if ($rep->row < $rep->bottomMargin + (6 * $rep->lineHeight)) {
                                    $ed_row = $rep->row;
                                    $ed_row += 12;
                                    draw_table_cloase_horizontal_line_after_loop($rep, $ed_row);
                                    
                                    $rep->NewLine(2);
                                    display_vouchers_footer_details($rep);
                                    
                                    $rep->NewPage();
                                    
                                    $loop_row = display_voucher_header_details($rep);
                                }
                                
                                if (strlen($item['memo_']) > 0) {
                                    $rep->NewLine();
                                    $rep->TextWrapLines(88, 503, $item['memo_']);
                                    $brs -= 2;
                                } else {
                                    $rep->NewLine();
                                    $brs -= 1;
                                }
                                
                                $ed_row = $rep->row;
                                if (! $add_new_line) {
                                    if ($db_num_rows == 1) {
                                        $rep->NewLine();
                                        $ed_row = $rep->row;
                                    }
                                    draw_vertical_lines_from_loop($rep, $st_row, $ed_row);
                                } else {
                                    draw_vertical_lines_from_loop($rep, $loop_row, $ed_row);
                                }
                                
                                $add_new_line = true;
                                
                                $brs--;
                            }
                            
                            
                            $ed_row = $rep->row;
                            draw_table_cloase_horizontal_line_after_loop($rep, $ed_row);
                            
                            $memos = get_comments_string($trans_type, $myrow['trans_no']);
                                if (strlen($memos) > 0) {
                                    $rep->NewLine(2);
                                    $rep->Font();
                                    $rep->Text(88, _("Details :"));
                                    $rep->Font('bold');
                                    $rep->Font();

                                    $rep->Font('bold');
                                    foreach (explode("\n", $memos) as $key => $memo) {
                                        $rep->Text(120, $memo);
                                        $rep->NewLine();
                                        
                                        if ($rep->row < $rep->bottomMargin + (5 * $rep->lineHeight)) {
                                            $rep->NewPage();
                                            display_voucher_header_details($rep, false);
                                        }
                                        
                                        $brs--;
                                    }
                                    $rep->Font();
                                }
                                
                            if($trans_type == ST_BANKTRANSFER){
                                $batch_h = get_batch_bank_transfer_record_by_fund_transfer_no($trans_no);
                                if(is_array($batch_h)){
                                    print_batch_bank_transfer_details($rep, $voucher_type_id, $batch_h);
                                }
                            }
                            elseif($trans_type == ST_PETTY_CASH_FLOAT_REIMBUR){
                                $batch_h = get_float_reimbursement_header_for_report($trans_no);
                                if(is_array($batch_h)){
                                    print_float_reimbursement_transactions($rep, $trans_type, $voucher_type_id, $batch_h);
                                }
                            }
                            
                            $rep->NewLine(2);
                        
                        $rep->Font('bold');
                        $words = price_in_words($myrow['amount']*-1, $myrow['type']);
                        $company_currency = get_company_currency();
                        $currency = get_currency($company_currency);
                        if ($words != "") {
                            $rep->Text(30, "LKR" . ": " . $words." ".$currency['hundreds_name'], - 2);
                            $rep->NewLine(2);
                        }
                        $rep->Font();
                        
                        display_vouchers_footer_details($rep);
                        
    $rep->End();
}

function print_float_reimbursement_transactions(&$rep, $trans_type, $voucher_type_id, $batch_h)
{
    global $systypes_array;
    
    $cols = array($x=0, $x+=100, $x+=20, $x+=50, $x+=60, $x+=300);

    // $headers in doctext.inc
    $aligns = array('left', 'center', 'center', 'right', 'left');
    $headers  = array(_(" Type"), _("#"), _("Date"), _("Amount"), _("Details"));
    $params = array('voucher_type_id' => $voucher_type_id);
    
    $rep->Info($params, $cols, $headers, $aligns);
    
    $rep->fontSize -= 2;
    $rep->NewLine(2);
    $rep->Font('bold');
    $rep->Text(30, $systypes_array[ST_PETTY_CASH_FLOAT_REIMBUR]." #".$batch_h['id']." Details" );
    $rep->Font('');
    $rep->row -= 5;
    $rep->LineTo(25, $rep->row, 570, $rep->row);
    $rep->NewLine();
    $c=0;
    foreach ($headers as $htext) {
        $rep->TextCol($c, $c+1, $htext, 0, 0, 0, 0, NULL, 1, 'center'); 
        $c++;
    }
    $rep->row -= 5;
    $rep->LineTo(25, $rep->row, 570, $rep->row);
    
    $batch_d_res = get_petty_cash_float_reimbursement_transactions_for_report($batch_h['id']);
    
    while ($batch_d = db_fetch($batch_d_res)) {
        $rep->NewLine();
        $rep->TextCol(0, 1, $systypes_array[$batch_d['batch_tran_type']]);
        $rep->TextCol(1, 2, $batch_d['batch_type_no']);
        $rep->TextCol(2, 3, $batch_d['tran_date']);
        $rep->AmountCol(3, 4, $batch_d['amount'], 2, -5);
        
        $text = "";
        switch ($batch_d['batch_tran_type']) {
            case ST_I_OWE_YOU_PAYMENT:
                $trans = get_i_owe_you_payment($batch_d['batch_type_no']);
                $text = $trans['comment'];
                break;
            case ST_CASH_PAYMENT:
                $trans = get_pre_gl_adjustment_transaction_header($batch_d['batch_tran_type'], $batch_d['batch_type_no']);
                $text = $trans['comment'];
                break;

            default:
                break;
        }
//        $rep->TextCol(4, 5, payment_person_name($batch_d["person_type_id"], $batch_d["person_id"]), 5);
        $rep->TextCol(4, 5, $text);

    }
    
    $rep->row -= 5;
    $rep->LineTo(25, $rep->row, 570, $rep->row);
    $rep->fontSize += 2;
}


function print_batch_bank_transfer_details(&$rep, $voucher_type_id, $batch_h)
{
    global $systypes_array;
    
    $cols = array($x=0, $x+=100, $x+=20, $x+=50, $x+=60, $x+=100, $x+=200);

    // $headers in doctext.inc
    $aligns = array('center', 'left', 'center', 'right', 'left', 'left');
    $headers  = array(_(" Type"), _("#"), _("Date"), _("Amount"), _("Details"), _("Comment"));
    $params = array('voucher_type_id' => $voucher_type_id);
    
    $rep->Info($params, $cols, $headers, $aligns);
    
    $rep->fontSize -= 2;
    $rep->NewLine(2);
    $rep->Font('bold');
    $rep->Text(30, $systypes_array[ST_BATCH_BANK_TRANSFER_REQ]." #".$batch_h['trans_no']." Details" );
    $rep->Font('');
    $rep->row -= 5;
    $rep->LineTo(25, $rep->row, 570, $rep->row);
    $rep->NewLine();
    $c=0;
    foreach ($headers as $htext) {
        $rep->TextCol($c, $c+1, $htext, 0, 0, 0, 0, NULL, 1, 'center'); 
        $c++;
    }
    $rep->row -= 5;
    $rep->LineTo(25, $rep->row, 570, $rep->row);
    
    $batch_d_res = get_batch_bank_transfer_details(ST_BATCH_BANK_TRANSFER_REQ, $batch_h['trans_no']);
    while ($batch_d = db_fetch($batch_d_res)) {
        $rep->NewLine();
        $rep->TextCol(0, 1, $systypes_array[$batch_d['source_type']]);
        $rep->TextCol(1, 2, $batch_d['source_trans_no']);
        $rep->TextCol(2, 3, $batch_d['trans_date']);
//        $rep->TextCol(3, 4, number_format($batch_d['amount']));
        $rep->AmountCol(3, 4, -$batch_d['amount'], 2, -5);
        $rep->TextCol(4, 5, payment_person_name($batch_d["person_type_id"], $batch_d["person_id"]), 5);
        $rep->TextCol(5, 6, get_comments_string($batch_d["source_type"], $batch_d["source_trans_no"]));

    }
    
    $rep->row -= 5;
    $rep->LineTo(25, $rep->row, 570, $rep->row);
    $rep->fontSize += 2;



//	    $params = array('voucher_type_id' => $voucher_type_id);	
//    	
//    $rep->Info($params, $cols, $headers, $aligns);	
//    	
//    $rep->fontSize -= 2;	
//    $rep->NewLine(2);	
//    $rep->Font('bold');	
//    $rep->Text(30, $systypes_array[ST_BATCH_BANK_TRANSFER_REQ]." #".$batch_h['trans_no']." Details" );	
//    $rep->Font('');	
//    $rep->row -= 5;	
//    $rep->LineTo(25, $rep->row, 570, $rep->row);	
//    $rep->NewLine();	
//    $c=0;	
//    foreach ($headers as $htext) {	
//        $rep->TextCol($c, $c+1, $htext, 0, 0, 0, 0, NULL, 1, 'center'); 	
//        $c++;	
//    }	
//    $rep->row -= 5;	
//    $rep->LineTo(25, $rep->row, 570, $rep->row);    	
//    $batch_d_res = get_batch_bank_transfer_details(ST_BATCH_BANK_TRANSFER_REQ, $batch_h['trans_no']);	
//    while ($batch_d = db_fetch($batch_d_res)) {	
//        $rep->NewLine();	
//        $rep->TextCol(0, 1, $systypes_array[$batch_d['source_type']]);	
//        $rep->TextCol(1, 2, $batch_d['source_trans_no']);	
//        if($batch_d['removed_by'] > 0){	
//            $message = "**************************** This transaction has been removed ****************************";	
//            $rep->TextCol(2, 6, $message);	
//        }	
//        else{	
//            $rep->TextCol(2, 3, $batch_d['trans_date']);	
//    //        $rep->TextCol(3, 4, number_format($batch_d['amount']));	
//            $rep->AmountCol(3, 4, -$batch_d['amount'], 2, -5);	
//            $rep->TextCol(4, 5, payment_person_name($batch_d["person_type_id"], $batch_d["person_id"]));	
//            $rep->TextCol(5, 6, "   ".get_comments_string($batch_d["source_type"], $batch_d["source_trans_no"]));	
//        }	
//    } 	
//    	
//    $rep->row -= 5;	
//    $rep->LineTo(25, $rep->row, 570, $rep->row);	
//    $rep->fontSize += 2;	
}	



function get_float_reimbursement_header_for_report($id)	
{	
        $sql= "SELECT 	
            flr.*,	
            fl.name float_name 	
        FROM ".TB_PREF."i_owe_you_float_reimbursements flr 	
                INNER JOIN ".TB_PREF."petty_cash_floats fl ON 	
                        flr.float_id = fl.id 	
                	
        WHERE flr.id = ".db_escape($id);	
        	
	$result = db_query($sql,"get_float_reimbursement_header_for_report");		
    	
    return db_fetch($result);	
}	
  	
function get_petty_cash_float_reimbursement_transactions_for_report($id)	
{	
    $sql = "SELECT frd.*, 	
                    CASE 	
                        WHEN frd.tran_type = ".db_escape(ST_I_OWE_YOU_BATCH)." THEN ioub.tran_date	
                        ELSE ft.tran_date 	
                    END as tran_date 	
            FROM ".TB_PREF."float_reimbursement_details frd 	
                LEFT JOIN ".TB_PREF."petty_cash_float_trans ft 	
                    ON ft.tran_type = frd.tran_type 	
                    AND ft.type_no = frd.type_no 	
                LEFT JOIN ".TB_PREF."i_owe_you_batches ioub  	
                    ON frd.tran_type = ".db_escape(ST_I_OWE_YOU_BATCH)." 	
                    AND ioub.batch_no = frd.type_no 	
            WHERE frd.reimbursement_id = ".db_escape($id);	
    	
    return db_query($sql, "get_petty_cash_float_reimbursement_transactions_for_report");   	
}	
