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

function display_supplier_balances_filtering_criteria(){
    
//    Start Date') => 'DATEBEGIN',
//			_('End Date') => 'DATEENDM',
//			_('Customer') => 'CUSTOMERS_NO_FILTER',
//			_('Show Balance') => 'YES_NO',
//			_('Currency Filter') => 'CURRENCY',
//			_('Suppress Zeros') => 'YES_NO',
//			_('Comments') => 'TEXTBOX',
//			_('Orientation') => 'ORIENTATION',
//			_('Destination') => 'DESTINATION'));
                            
    start_table(TABLESTYLE_NOBORDER);
    start_row();

	supplier_list_cells(_("Select a supplier: "), 'supplier_id', null, true, true, false);

        date_cells(_("From:"), 'from_date', '', null, 0);
        date_cells(_("To:"), 'to_date', '', null, 7);
        
        yesno_list_cells("Suppress Zeros", 'suppess_zeros', null, "", "", true);
         

    submit_cells('RefreshInquiry', _("Search"),'',_('Refresh Inquiry'), 'default');
    end_row();
    end_table();

    set_global_supplier($_POST['supplier_id']);
    
}


function display_supplier_opening_balance(&$ob, $customer_id, $from_date_, $no_zeros, $to_date_)
{
    $convert = true;
    $dec = 2;
    
    $customer = get_customer($customer_id);
    $rate = (isset($convert['debtor_no']) && $convert['debtor_no'] > 0) ? get_exchange_rate_from_home_currency($customer['curr_code'], Today()) : 1;
    
    $balances_before_date_ = add_days($from_date_, -1);
    $bal = get_supplier_calculated_opening_balance($ob, $customer_id, $balances_before_date_, $no_zeros, $to_date_);
    
//    $ob_debits = round2(abs($bal['charges']*$rate), $dec);
//    $ob_credits = round2(Abs($bal['credits']*$rate), $dec);
//    $ob_allocated = round2($bal['Allocated']*$rate, $dec);
//    $ob_balance = round2(($ob_debits + $ob_credits ) - $ob_allocated, $dec);
//    $ob_outstanding = round2($bal['OutStanding']*$rate, $dec);
    
    $ob_debits = round2($ob[0]*$rate, $dec);
    $ob_credits = round2($ob[1]*$rate, $dec);
    $ob_allocated = round2($ob[2]*$rate, $dec);
    $ob_balance = round2(($ob_debits + $ob_credits ) - $ob_allocated, $dec);
    $ob_balance = round2($ob[3]*$rate, $dec);
    $ob_outstanding = round2(($ob[0]-$ob[1])*$rate, $dec);

//    $ob[0] += $ob_debits;
//    $ob[1] += $ob_credits;
//    $ob[2] += $ob_allocated;                           
//    $ob[3] += $ob_outstanding;
//    $ob[4] += $ob_outstanding;   
    

//	start_row();
//        label_cell(text_bold("Opening Balance"), 'align=left colspan=5');
//	amount_cell($ob_debits, true);
//	amount_cell($ob_credits, true);
//	amount_cell($ob_allocated, true);
//	amount_cell($ob_outstanding, true);
//	amount_cell($ob_outstanding, true);
//        label_cell('', 'colspan=5');
//	end_row();

//	end_table();
    
    
    	start_row();
        label_cell(text_bold("Opening Balance"), 'align=left colspan=5');
        amount_cell($ob_credits, true);
	amount_cell($ob_debits, true);
	
//	amount_cell($ob_allocated, true);
        label_cell('');
//	amount_cell($ob_outstanding, true);
        label_cell('');
	amount_cell($ob_balance, true);
	amount_cell($ob_outstanding, true);
	end_row();
}


function get_supplier_calculated_opening_balance(&$ob, $supplier_id, $balances_before_date_, $no_zeros, $to_date_)
{
    
    $begin_date_ = sql2date(INFINITE_START_DATE);
    
    $result = get_supplier_transactions($supplier_id, $begin_date_, $balances_before_date_);

    $rate =1;
    $dec = 2;
    $accumulate = 0;
    
    while ($trans = db_fetch($result)) 
    {
        
	$debit = $credit = $allocated = $balance = 0;
                    
        if ($no_zeros && floatcmp(abs($trans['TotalAmount']), $trans['Allocated']) == 0){
            continue;
        }

        
        if(in_array($trans['type'], array(ST_SUPPINVOICE,ST_BANKDEPOSIT,ST_SUBCONTRACTOR_INVOICE, ST_UTILITY_BILLS, 
                                          ST_SUPPLIER_TRANSPORT_INVOICES, ST_CASH_RECEIPT, ST_GL_CREDIT, ST_PURCHORDER))){ 
            $debit_type = true;
            $allocated = get_supplier_transaction_allocation_to_within_period($trans['type'], $trans['trans_no'], $begin_date_, $to_date_) * $rate;
        }
        else{
            $debit_type =  false;
            $allocated = get_supplier_transaction_allocation_from_within_period($trans['type'], $trans['trans_no'], $begin_date_, $to_date_) * $rate;
        }

        if(!$debit_type){
                $trans['TotalAmount'] *= -1;
        }
			
        if ($debit_type)
        {
            if ($trans['type'] != ST_PURCHORDER) {
                $debit = round2(abs($trans['TotalAmount']) * $rate, $dec);
            } 
        }
        else
        {
                $credit = round2(Abs($trans['TotalAmount']) * $rate, $dec);                
        }

        $balance = (Abs($trans['TotalAmount']) - $allocated ) * $rate;

        if(!$debit_type){
            $balance *= -1; 
        }
                            
        $accumulate += $trans['TotalAmount'];

        $ob[0] += $debit;
        if ($trans['type'] != ST_PURCHORDER) {
            $ob[1] += $credit;
        } else {
            $balance = -1 * $allocated; 
        }
        $ob[2] += $allocated;                           
        $ob[3] += $balance;     
        $ob[4] = $accumulate;      

    }
    
    $ob[4] = $ob[0] - $ob[1];
}




function display_supplier_balances($supplier_id, $from_date_, $to_date_, $no_zeros)
{
    global $systypes_array;
    
    $result = get_supplier_transactions($supplier_id, $from_date_, $to_date_);

    start_table(TABLESTYLE, "width=99%");

    $th = array(_("Type"),_("Trans#"),_("Reference#"),_("Tran. Date"),_("Due Date"),                
                _("Debits"),_("Credits"),_("Allocated"),_("Balance"), _("Balance Total"), _("Outstaning"),
                _("Bank Account"),_("Chq. No"),_("Chq. Date"), _("Comment"));

    //inactive_control_column($th);
    table_header($th);
    
    $ob = array(0,0,0,0,0);
    display_supplier_opening_balance($ob, $supplier_id, $from_date_, 0, $to_date_);
    
    $k = $balance_total = 0;
    $rate =1;
    $dec = 2;
    $accumulate = $ob[4];
    
    $total = array(0,0,0,0,0,0);
    
    $total[3] = $ob[3];
    $total[4] = $accumulate;
    
    $alloc_from_date_ = sql2date(INFINITE_START_DATE);
    
    while ($trans = db_fetch($result)) 
    {
        $debit = $credit = $allocated = $balance = 0;
        
//        if ($no_zeros && floatcmp(abs($trans['TotalAmount']), $trans['Allocated']) == 0){
//            continue;
//        }
        if(in_array($trans['type'], array(ST_SUPPINVOICE, ST_BANKDEPOSIT, ST_SUBCONTRACTOR_INVOICE, ST_UTILITY_BILLS, 
                                          ST_SUPPLIER_TRANSPORT_INVOICES, ST_CASH_RECEIPT, ST_GL_CREDIT, ST_PURCHORDER))) {
            $debit_type = false;
            $allocated = get_supplier_transaction_allocation_to_within_period($trans['type'], $trans['trans_no'], $alloc_from_date_, $to_date_) * $rate;
        }
        else{
            $debit_type =  true;
            $allocated = get_supplier_transaction_allocation_from_within_period($trans['type'], $trans['trans_no'], $alloc_from_date_, $to_date_) * $rate;
        }
        
	$balance = (Abs($trans['TotalAmount']) - $allocated ) * $rate;
        if(ABS($balance) < 0.000001){
            $balance = 0;
        }
        
        if ($debit_type)
        {
                $debit = round2(abs($trans['TotalAmount']) * $rate, $dec);
        }
        else
        {
                $credit = round2(Abs($trans['TotalAmount']) * $rate, $dec);                
        }
        
        if ($trans['type'] == ST_PURCHORDER){
            $balance = -1 * $allocated; 
        }
        
        if(!($no_zeros && $balance == 0)){
            alt_table_row_color($k);	
            label_cell($systypes_array[$trans['type']]);
            $link = get_trans_view_str($trans['type'], $trans['trans_no']);
            label_cell($link, 'align=center');
            label_cell($trans['reference']);
            label_cell(sql2date($trans['tran_date']), 'align=center');

            if ($trans['type'] == ST_SUPPINVOICE){
                label_cell(sql2date($trans['due_date']), 'align=center');
            }
            else{
                label_cell('');
            }

//            if(!$debit_type){
//                    $trans['TotalAmount'] *= -1;
//            }

            if ($trans['type'] != ST_PURCHORDER) {
                if ($debit_type)
                {
                        amount_cell($debit);
                        label_cell('');
                }
                else
                {
                        label_cell('');
                        amount_cell($credit);                
                }
            } else {
                label_cell(''); label_cell('');
            }

//        $allocated = $trans['Allocated'] * $rate;
        

            if($debit_type){
                $balance *= -1; 
            }

            if ($trans['type'] != ST_PURCHORDER) {
                $accumulate += $trans['TotalAmount'];  
            }

            amount_cell($allocated);
            amount_cell($balance);
            $balance_total += $balance;
            
            amount_cell($balance_total);
            
            if ($trans['type'] != ST_PURCHORDER) {
                amount_cell($accumulate);
            } else {
                label_cell('');
            }
            
            $cheque_no = $cheque_date = $bank_act_no = "";
            $cheq_res = get_latest_cheque_print_details($trans['type'],$trans['trans_no']);
            if (isset($cheq_res['id']) && $cheq_res['id'] > 0) {
                $cheque_no = $cheq_res['cheque_no'];
                $cheque_date = sql2date($cheq_res['cheque_date']);
                
                if(strlen($cheq_res["bank_account_number"]) > 1){
                    $bank_act_no = $cheq_res["bank_account_number"]." - ".$cheq_res["bank_name"];
                }
            }

//        $acct_name_payee = $cheq_res["account_name"];
        
            $comments = '';
            if($trans['type'] == ST_BANKDEPOSIT || $trans['type'] == ST_SUPPAYMENT) {
                $comments = get_comments_string($trans["type"], $trans["trans_no"]);
            }

            label_cell($bank_act_no);
            label_cell($cheque_no, 'align=center');
            label_cell($cheque_date, 'align=center');
            label_cell($comments);

            end_row();

        }
        else{
            if($debit_type){
                $balance *= -1; 
            }

//            if(!$debit_type){
//                $trans['TotalAmount'] *= -1;
//            }
            
            $accumulate += $trans['TotalAmount'];  
//            $balance_total += $balance;
            
        }
        
        $total[0] += $debit;
        if ($trans['type'] != ST_PURCHORDER) {
            $total[1] += $credit;
        }
        $total[2] += $allocated;                           
        $total[3] += $balance;
        $total[4] = $accumulate;    
//        $total[5] = $balance_total;    
    }
    
    start_row();
        label_cell(text_bold("Total for Selected Period"), 'align=right colspan=5');
        amount_cell($total[0], true);
        amount_cell($total[1], true);
//        amount_cell($total[2], true);
        label_cell('');
//        amount_cell($total[3], true);
        label_cell('');
//        amount_cell($total[4], true);
        label_cell('');
        label_cell('', 'colspan=5');
    end_row();
    
    start_row();
        label_cell(text_bold("Closing Balance"), 'align=left colspan=5');
        amount_cell($ob[1] + $total[0], true);
        amount_cell($ob[0] + $total[1], true);
//        amount_cell($ob[2] + $total[2], true);
        label_cell('');
//        amount_cell($ob[3] + $total[3], true);
        label_cell('');
        amount_cell($total[3], true);
        amount_cell($total[4], true);
        label_cell('', 'colspan=4');
    end_row();

    end_table(1);
}