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

function display_customer_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();

	customer_list_cells(_("Customer: "), 'customer_id', null, "Select a customer", 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();
//    }
//    else{
//        $_POST['from_date'] = Today();
//        hidden('from_date', $_POST['from_date']);
        
//        $_POST['to_date'] = Today();
//        hidden('to_date', $_POST['to_date']);
//    }
    end_table();

    set_global_customer($_POST['customer_id']);
    
}


function get_customer_calculated_openning_balance(&$ob, $customer_id, $balances_before_date_, $no_zeros, $to_date_)
{
    $begin_date_ = sql2date(INFINITE_START_DATE);
    
    $result = get_customer_transactions($customer_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($trans['TotalAmount'], $trans['Allocated']) == 0){
            continue;
        }

        if(in_array($trans['type'], array(ST_SALESINVOICE, ST_BANKPAYMENT, ST_PROJECT_INVOICE, ST_CASH_PAYMENT, ST_GL_DEBIT))){
            $debit_type = true;
            $allocated = get_customer_transaction_allocation_from_within_period($trans['type'], $trans['trans_no'], $begin_date_, $to_date_) * $rate;
        }
        else{
            $debit_type =  false;
            $allocated = get_customer_transaction_allocation_to_within_period($trans['type'], $trans['trans_no'], $begin_date_, $to_date_) * $rate;
        }

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

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

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

        $ob[0] += $debit;
        $ob[1] += $credit;
        $ob[2] += $allocated;                           
        $ob[3] += $balance;
        $ob[4] = $accumulate;                   

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

}



function display_customer_opening_balance(&$ob, $customer_id, $from_date_, $no_zeros, $to_date_)
{
    $convert = true;
    $dec = 2;
    
    $curr_code = '';
    $customer = get_customer($customer_id);
    if (isset($customer['debtor_no']) && $customer['debtor_no'] > 0) {
        $curr_code = $customer['curr_code'];
    }  
    $rate = $convert ? get_exchange_rate_from_home_currency($curr_code, Today()) : 1;
    
    $balances_before_date_ = add_days($from_date_, -1);
    get_customer_calculated_openning_balance($ob, $customer_id, $balances_before_date_, $no_zeros, $to_date_);
    
    $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[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;   
    
//    display_heading2($customer['name']." - ".$customer['curr_code']);
//    br(1);
//    
//    if ($customer["dissallow_invoices"] != 0)
//    {
//    	echo "<center><font color=red size=4><b>" . _("CUSTOMER ACCOUNT IS ON HOLD") . "</font></b></center>";
//        br(1);
//    }


//    start_table(TABLESTYLE, "width=80%");
//    $th = array(_(""), _("Debits"), _("Credits"),
//    	_("Allocated"), _("Balance"), _("Outstanding"));
//    table_header($th);

	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);
        label_cell('');
//	amount_cell($ob_outstanding, true);
        label_cell('');
	amount_cell($ob_balance, true);
	amount_cell($ob_outstanding, true);
	end_row();

//	end_table();
}


function display_customer_balances($customer_id, $from_date_, $to_date_, $no_zeros)
{
    global $systypes_array, $customer_debit_types_array;

//    if($no_zeros){
//        $from_date_ = sql2date(INFINITE_START_DATE);        
//        $to_date_ = sql2date(INFINITE_END_DATE);
//    }
    
    $result = get_customer_transactions($customer_id, $from_date_, $to_date_);


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

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

    //inactive_control_column($th);
    table_header($th);
    
    $ob = array(0,0,0,0,0);
    display_customer_opening_balance($ob, $customer_id, $from_date_, 0, $to_date_);
    
    $k = $balance_total = 0;
    $rate =1;
    $dec = 2;
    $accumulate = $ob[4];
    $total = array(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($trans['TotalAmount'], $trans['Allocated']) == 0){
//            continue;
//        }

        if(in_array($trans['type'], $customer_debit_types_array)){
            $debit_type = true;
            $allocated = get_customer_transaction_allocation_from_within_period($trans['type'], $trans['trans_no'], $alloc_from_date_, $to_date_) * $rate;
        }
        else{
            $debit_type =  false;
            $allocated = get_customer_transaction_allocation_to_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(!($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_SALESINVOICE){
                    label_cell(sql2date($trans['due_date']), 'align=center');
                }
                else{
                    label_cell('');
                }

        

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

                if ($debit_type)
                {
                        amount_cell($debit);
                        label_cell('');
                }
                else
                {
                        label_cell('');
                        amount_cell($credit);                
                }

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

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

                $accumulate += $trans['TotalAmount']; 


                amount_cell($allocated);
                amount_cell($balance);
                
                $balance_total += $balance;
                amount_cell($balance_total);
            
                amount_cell($accumulate);



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

                if(!$debit_type){
                    $trans['TotalAmount'] *= -1;
                }
                
                $accumulate += $trans['TotalAmount'];             
        }
        
        $total[0] += $debit;
        $total[1] += $credit;
        $total[2] += $allocated;                           
        $total[3] += $balance;
        $total[4] = $accumulate;   

    }
    
    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('');
    end_row();
    
    start_row();
        label_cell(text_bold("Closing Balance"), 'align=left colspan=5');
        amount_cell($ob[0] + $total[0], true);
        amount_cell($ob[1] + $total[1], true);
//        amount_cell($ob[2] + $total[2], true);
        label_cell('');
        label_cell('');
//        amount_cell($ob[3] + $total[3], true);
        amount_cell($total[3], true);
        amount_cell($total[4], true);
    end_row();

    end_table(1);
}

