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

$page_security = 'SA_COMPANY_LOAN_INSTALMENTS';
if (!@$_GET['popup'])
	$path_to_root = "..";
else	
	$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/ui.inc");
include_once($path_to_root . "/includes/inventory.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/finance/includes/db/company_loan_installments_db.inc");
include_once($path_to_root . "/finance/includes/db/company_loans_db.inc");
include_once($path_to_root . "/finance/includes/db/credit_facilities_db.inc");

$js = '';

if ($SysPrefs->use_popup_windows) {
	$js .= get_js_open_window(900, 500);
}

if (user_use_date_picker()) {
	$js .= get_js_date_picker();
}

page(_($help_context = "Company Loan Installments"), false, false, "", $js);

//----------------------------------------------------------------------------------------

simple_page_mode(true);

$company_loan_id = -1;

if (isset($_GET['id']))
{
    $_POST['company_loan_id'] = $_GET['id'];
}
if (isset($_POST['company_loan_id']) && $_POST['company_loan_id'] > 0)
{
    $company_loan_id = $_POST['company_loan_id'];
}


if (isset($_GET['credit_facility_id']))
{
    $_POST['credit_facility_id'] = $_GET['credit_facility_id'];
}


function can_delete_company_loan_installment($selected_id)
{
    $installment = get_company_loan_installment($selected_id);
    if($installment['paid_amount'] > 0){    
        display_error(_("Selected company installment has payment. It can not be deleted."));
        return false; 
    }
    return true;
}


function can_commit_installment($loan_id, $selected_id)
{   
//    if($selected_id > 0){
//        $installment = get_company_loan_installment($selected_id);
//        if($installment['paid'] == 1){    
//            display_error( _("This transaction has been completed. It can not be edited."));
//            set_focus('installment_amount');
//            return false; 
//        }
//    }
    
    if(!check_num('company_loan_id', 0))
    {
        display_error(_("Please select a company loan."));
        set_focus('company_loan_id');
        return false;        
    }
 
    if (!check_num('interest_amount', 0))
    {
        display_error( _("Interest amount entered was not numeric or positive."));
        set_focus('interest_amount');
        return false;
    }
      
    if (!check_num('paid_amount', 0))
    {
        display_error( _("Capital paid amount entered was not numeric or positive."));
        set_focus('paid_amount');
        return false;
    }
    
    if (!check_num('total_payment_interest', 0))
    {
        display_error( _("Interest paid amount entered was not numeric or positive."));
        set_focus('total_payment_interest');
        return false;
    }
    
    if (!check_num('total_late_interest', 0))
    {
        display_error( _("Late interest paid amount entered was not numeric or positive."));
        set_focus('total_late_interest');
        return false;
    }
                
                
    if (!check_num('installment_amount', 0))
    {
        display_error( _("Installment amount entered was not numeric or possitive."));
        set_focus('installment_amount');
        return false;
    }   
    
    if(!(input_num('installment_amount') > 0 || input_num('interest_amount') > 0)){
        display_error( _("Either Installment amount or Interest amount should have a possitive value."));
        set_focus('installment_amount');
        return false;
    }
    
//    $loan = get_company_loan($loan_id);
//    if($loan['inactive']){
//        display_error(_("This loan is not active. Can not make transactions against it."));
//        set_focus('installment_amount');
//        return false;
//    }
//    
//    if($loan['completed']){
//        display_error( _("This loan is completed. Can not make any further transactions against it."));
//        set_focus('installment_amount');
//        return false;
//    }
//    
//    
//    if(!is_date($_POST['tran_date'])){
//        display_error(_("Installment date is invalid."));
//        set_focus('tran_date');
//        return false;
//    }
//    
//    if(input_num('installment_amount') > $loan['loan_amount'] - $loan['total_captal_paid']){
//        display_error( _("Maximum amount payble for this loan is ".($loan['loan_amount'] - $loan['total_captal_paid'])));
//        set_focus('installment_amount');
//        return false;
//    }
    
    return true;    
}

//-----------------------------------------------------------------------------------------------------


//function can_process_payment($loan_id, $selected_id)
//{   
//    global $Refs;
//    
////    if($selected_id > 0){
////        $installment = get_company_loan_installment($selected_id);
////        if($installment['paid'] == 1){    
////            display_error( _("This transaction has been completed. It can not be edited."));
////            set_focus('installment_amount');
////            return false; 
////        }
////    }
//    
//    if(!$Refs->is_valid($_POST['batch_ref'])){
//        display_error( _("Please enter a reference."));
//        set_focus('batch_ref');
//        return false; 
//    }
//
//    $ref_msg = reference_exists(get_post('batch_ref'), ST_COMP_LOAN_REPAYMENT);
//    if($ref_msg){
//        display_error($ref_msg);
//        set_focus('batch_ref');
//        return false; 
//    }
//    
//    if(!check_num('company_loan_id', 0))
//    {
//        display_error( _("Please select a company loan."));
//        set_focus('company_loan_id');
//        return false;        
//    }
// 
//    
//        
//        
//    //-- Capital payment
//    if (!check_num('payment_amount', 0))
//    {
//        display_error( _("Payment amount entered is not numeric or possitive."));
//        set_focus('payment_amount');
//        return false;
//    } 
//    
//    if (input_num('payment_amount') > 0)
//    {
//        if(!($_POST['bank_account_id'] > 0)){
//            display_error(_("Please select a bank account for capital amount payment."));
//            set_focus('bank_account_id');
//            return false;
//        }
//    } 
//    
//    //-- Interest payment
//    
//    if (!check_num('payment_interest_amount', 0))
//    {
//        display_error( _("Payment interest amount entered is not numeric."));
//        set_focus('payment_interest_amount');
//        return false;
//    }
//      
//    if (input_num('payment_interest_amount') > 0)
//    {
//        if(!($_POST['interest_account'] > 0)){
//            display_error(_("Please select a bank account for interest payment."));
//            set_focus('interest_account');
//            return false;
//        }
//    } 
//      
//    //-- Late Interest payment
//    
//    if (!check_num('late_interest_amount', 0))
//    {
//        display_error( _("Late payment interest amount entered is not numeric."));
//        set_focus('late_interest_amount');
//        return false;
//    }
//      
//    if (input_num('late_interest_amount') > 0)
//    {
//        if(!($_POST['late_interest_account'] > 0)){
//            display_error(_("Please select a bank account for late interest payment."));
//            set_focus('late_interest_account');
//            return false;
//        }
//    } 
//    
//    $this_payment_total = input_num('payment_amount') + input_num('payment_interest_amount') + input_num('late_interest_amount');
//    if(!($this_payment_total > 0)){
//        display_error(_("Please enter a value for one of the amounts at least."));
//        set_focus('payment_amount');
//        return false;
//    }
//    
//    
//    if(!is_date($_POST['payment_date'])){
//        display_error(_("Payment date is invalid."));
//        set_focus('payment_date');
//        return false;
//    }
//    
////    $loan_installments = get_company_loan_installment($selected_id);
////    $sum_amount = input_num('payment_amount') + $loan_installments['paid_amount'];
////    $real_amount =  $loan_installments['installment_amount'] - $sum_amount ;
//    
//    $loan_installment = get_company_loan_installment($selected_id);
//    $balance_amount = $loan_installment['installment_amount'] - $loan_installment['paid_amount'] + 0.00000001;
//    $payment_amount = input_num('payment_amount');
//    
//    if($balance_amount < $payment_amount){
//        display_error("The entered payment amount should be less than or equal to ".$balance_amount);
//        set_focus('payment_amount');
//        return false;
//    }
//    
//    
//    $loan = get_company_loan($loan_id);
//    
//    if (!(strlen($loan['loan_account']) > 1))
//    {
//        display_error(_("Loan account of this company loan is emplty. Can not process the payment."));
//        set_focus('loan_account');
//        return false;
//        
//    } 
//    
//    if (!(strlen($loan['interest_account']) > 1))
//    {
//        display_error(_("Interest account of this company loan is emplty. Can not process the payment."));
//        set_focus('interest_account');
//        return false;
//        
//    } 
//    
//    if (!(strlen($loan['late_interest_account']) > 1))
//    {
//        display_error(_("Late interest account of this company loan is emplty. Can not process the payment."));
//        set_focus('late_interest_account');
//        return false;
//        
//    }     
//    
//    if($loan['inactive']){
//        display_error(_("This loan is not active. Can not make transactions against it."));
//        set_focus('installment_amount');
//        return false;
//    }
//    
//    if($loan['completed']){
//        display_error(_("This loan is completed. Can not make any further transactions against it."));
//        set_focus('installment_amount');
//        return false;
//    }
//        
//    if(input_num('payment_amount') > $loan['loan_amount'] - $loan['total_captal_paid'] + 0.00000001 ){
//        display_error( _("Maximum amount payble for this loan is ".($loan['loan_amount'] - $loan['total_captal_paid'])));
//        set_focus('payment_amount');
//        return false;
//    }
//    
//    return true;    
//}

//--------------------------------------------------------------------------------------------------

function display_loan_header($company_loan_id)
{
    if(!($company_loan_id > 0 )){
        return;
    }
    
    br();
    
    hidden('company_loan_id', $company_loan_id);
    
    $company_loan = get_company_loan($company_loan_id);
    if($company_loan['credit_facility_id'] > 0){
        $credit_facility = get_credit_facility($company_loan['credit_facility_id']); 
        $credit_facility_name = $credit_facility['name'];
    }
    else{
        $credit_facility_name = '';        
    }
    
    $loan_name = "Loan #".$company_loan_id." - ".$company_loan['name']." - ".$company_loan['description'];
    $link = get_finance_trans_view_str(ST_COMPANY_LOAN_INSTALLMENTS, $company_loan_id, $loan_name);
    
    display_heading2($link);
    
//    $bank_account_number = $company_loan['bank_account_number'];
//    
////    $total_paid_and_interset = get_total_paid_and_total_interest_for_company_loan_installments($_POST['company_loan_id']);
//    
////    start_table(TABLESTYLE_NOBORDER);
//    start_outer_table(TABLESTYLE2, "width=40%");
//    table_section(1);
//    start_row();
//    label_row("Reference :", $company_loan['name']);  
//    label_row("Description :", $company_loan['description']);
//    label_row("Credit Facility :", $credit_facility_name);
//    
//    $bank_account = get_bank_account($company_loan['bank_account_id']);
//    label_row("Bank Account :", $bank_account['bank_account_number']." - ".$bank_account['bank_account_name']);
//        
//    if($company_loan['inactive'] == 0){
//        label_row("On Hold :", "No");
//    }else{
//        label_row("On Hold :", "Yes"); 
//    }
//
//    if($company_loan['completed'] == 0){
//        label_row("Completed :", "No");
//    }
//    else{
//        label_row("Completed :", "Yes");
//    }
//    
//    
//    table_section(2);
//    label_row("Total Loan :", number_format($company_loan['loan_amount'],2));
//    label_row("Total Capital Paid :", number_format($company_loan['total_captal_paid'],2));
//    label_row("Total Interest Paid :", number_format($company_loan['total_interest_paid'],2));
//    label_row("Total Late Interest Paid :", number_format($company_loan['total_late_interest_paid'],2));
//    
//    if(substr($company_loan['last_payment_date'],0,4) == "0000"){
//        label_row("Last Payment Date :", '');
//    }
//    else{
//        label_row("Last Payment Date :", sql2date($company_loan['last_payment_date']));
//    }
//    // label_row("On Hold :", $company_loan['inactive']);
//    // label_row("Completed :", $company_loan['completed']);
//           
//    end_row();
////    end_table();
//    end_outer_table(1);
}
        

function display_loan_installments($company_loan_id)
{
    $result = get_company_loan_installments($company_loan_id);

    display_heading2("Loan Installments");
    
    br();
    
    div_start('price_table');

    if (db_num_rows($result) == 0)
    {
        display_note(_("There are no loan installments."));
    }
    else
    {
        start_table(TABLESTYLE, "width=90%");

        $th = array(_("ID"), _("Installment"), _("Interest"),_("Date"),                            
                    _("Capital Paid"), "Interest Paid", "Late Interest Paid", 
                    _("Capital Outstanding"), _("Days Outstanding"), "Paid",_("Comments"), 
                     "", "");

        table_header($th);

        $k = $j = 0; //row colour counter

        while ($myrow = db_fetch($result))
        {
            alt_table_row_color($k);

            label_cell($myrow["id"], 'align=right');
            label_cell(number_format($myrow["installment_amount"],2), "align=right");
            label_cell(number_format($myrow["interest_amount"],2), "align=right");            
            label_cell(sql2date($myrow["tran_date"]), "align=center");         
                     
     
            label_cell(number_format($myrow["paid_amount"], 2), 'align=right');  
            label_cell(number_format($myrow["total_payment_interest"], 2), 'align=right');  
            label_cell(number_format($myrow["total_late_interest"], 2), 'align=right');  
            
            $outstanding_amount = $myrow["installment_amount"] - $myrow["paid_amount"];
            label_cell(number_format($outstanding_amount, 2),'align=right');
            
            
            if($myrow["paid"] == 0){
                $tran_date = sql2date($myrow["tran_date"]); 
                $today = Today();             

                $days = date_diff2($today, $tran_date, 'd');

                if($days > 0){
                    label_cell($days, 'align=center');
                }else{
                    label_cell("");
                }
            }
            else{
                label_cell("");
            }
            
            label_cell(get_yes_no_name($myrow["paid"]), "align=center");

            label_cell($myrow["comments"]);    
            
            if($myrow["paid"] == 1){
                label_cells(null, null);
                label_cells(null, null);
            }else{
                edit_button_cell("EditEdit".$myrow['id'], _("Edit"));
//                edit_button_cell("EditPay".$myrow['id'], _("Pay"));
//                button_cell("EditPay".$myrow['id'], _("Pay"), "Pay", ICON_DOC);
                delete_button_cell("Delete".$myrow['id'], _("Delete"));
            }
            
            end_row();

            $j++;

       //end of page full new headings
        } //end of while loop

        end_table();
    }
    
    div_end();
}
    
    
function display_loan_installment_edit_controls($company_loan_id, $selected_id)
{
    $rec_id = substr($selected_id,4);
    
    if($rec_id > 0){
        $installment = get_company_loan_installment($rec_id);
      
        $_POST['installment_amount'] = $installment['installment_amount'];
        $_POST['interest_amount'] = $installment['interest_amount'];       
        $_POST['tran_date'] = sql2date($installment['tran_date']);
        $_POST['comments'] = $installment['comments'];  

        $_POST['paid_amount'] = $installment['paid_amount'];
        $_POST['total_payment_interest'] = $installment['total_payment_interest'];     
        $_POST['total_late_interest'] = $installment['total_late_interest'];  
        $_POST['paid'] = $installment['paid'];
    }
    else{
        $company_loan = get_company_loan($company_loan_id);

        $_POST['installment_amount'] = $company_loan['installment_amount'];
        $_POST['interest_amount'] = $company_loan['installment_interest'];        
        $_POST['tran_date'] = today();
        $_POST['comments'] = "";  
        $_POST['paid_amount'] = 0;
        $_POST['total_payment_interest'] = 0;     
        $_POST['total_late_interest'] = 0;
        $_POST['paid'] = 0;
                     
    }
    
    $dec2 = 2;

    br();

    hidden('selected_id', $selected_id);

    start_table(TABLESTYLE2);

        
    date_row("Installment Date:", 'tran_date');
    amount_row(_("Installment Amount:"),'installment_amount', $_POST['installment_amount'], null,null,2); 
    amount_row(_("Interest Amount:"),'interest_amount', $_POST['interest_amount'],null,null,2); 
    
    amount_row(_("Capital Paid:"),'paid_amount', null,null,null,2); 
    amount_row(_("Interest Paid:"),'total_payment_interest', null,null,null,2); 
    amount_row(_("Late Interest Paid:"),'total_late_interest', null,null,null,2); 
    yesno_list_row("Paid:", 'paid');
    text_row("Comments:", "comments", null, 50,200);
    
    end_table(1);

    $selected_id = substr($selected_id,4); 
    if($selected_id > 0){
        submit_center_first('Update_Installment', _("Update Installment"), '', 'default'); 
        submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel'); 
    }else{
        submit_center_first('Add_Installment', _("ADD Installment"), '', 'default');
    }
         
    br();
    
}


//function display_loan_installment_payment_controls($company_loan_id, $selected_id)
//{
//    global $Refs;
//    
//    $rec_id = substr($selected_id,3); 
//    
//    if($rec_id > 0){
//        $installment = get_company_loan_installment($rec_id);
//     
//        $_POST['payment_amount'] = number_format($installment['installment_amount'] - $installment['paid_amount']);       
//        $_POST['payment_interest_amount'] = $installment['interest_amount'];          
//        $_POST['tran_date'] = sql2date($installment['tran_date']);
//        $_POST['comments'] = $installment['comments'];
//          
//        $c_loan_details = get_company_loan($company_loan_id);
//        
//         if($c_loan_details['credit_facility_id'] > 0){
//                $cfb_details = get_credit_facility_bank_account_record($c_loan_details['credit_facility_id']);
//                $_POST['bank_account_id'] = $cfb_details['bank_account_id'];
//         }else{
//                $_POST['bank_account_id'] = $c_loan_details['bank_account_id'];
//         }
//
////            $_POST['bank_account_id'] = $c_loan_details['bank_account_id'];
//         $_POST['interest_account'] = $c_loan_details['bank_account_id'];
//         $_POST['late_interest_account'] = $c_loan_details['bank_account_id'];
//            
//    }
//    
//    $_POST['batch_ref'] = $Refs->get_next(ST_COMP_LOAN_REPAYMENT);
//    
//    $dec2 = 2;
//
//    br();
//
//    hidden('selected_id', $selected_id);
//
//    start_table(TABLESTYLE2);
//
//    //amount_row(_("Total Loan:"),'loan_amount', $_POST['loan_amount'],null,null,2);
//   
//    ref_row("Reference:", 'batch_ref');
//    label_row("Due Date:", $_POST['tran_date']);
//
//    date_row("Payment Date:", "payment_date");
//    amount_row(_("Capital Payment Amount:"),'payment_amount', null,null,null,2);  
//    bank_accounts_list_row("Capital Payment Account :", "bank_account_id", null, false, 'Select a bank account'); 
//    amount_row(_("Interest Payment Amount:"),'payment_interest_amount', null,null,null,2);   
//    bank_accounts_list_row("Interest Payment Account:", 'interest_account', null, false, 'Select a bank account'); 
//    amount_row(_("Late Interest Payment Amount:"),'late_interest_amount',null, null,null,2);
//    bank_accounts_list_row("Late Interest Payment Account:", 'late_interest_account', null, false, 'Select a bank account'); 
//    
//    yesno_list_row("Return", 'is_return', null, "Yes", "No");
//    text_row("Comments:", "comments", null, 50,200);
//    
//    end_table(1);
//
//    if($_POST['is_return'] > 0){
//        submit_center_first('PAY_INSTALLMENT', _("Return"), '', 'default');
//    }
//    else{
//        submit_center_first('PAY_INSTALLMENT', _("Make Payment"), '', 'default');
//    }    
//    
//    br();
//    
//}


//function make_company_loan_payment($selected_id)
//{
//
//    if(can_process_payment(get_post('company_loan_id'), $selected_id)){
//      
//        if(!(input_num('payment_amount') > 0)){
//            $_POST['payment_amount'] = 0;
//            $_POST['bank_account_id'] = 0;
//        }
//        
//        if(!(input_num('payment_interest_amount') > 0)){
//            $_POST['payment_interest_amount'] = 0;
//            $_POST['interest_account'] = 0;
//        }
//        
//        if(!(input_num('late_interest_amount') > 0)){
//            $_POST['late_interest_amount'] = 0;
//            $_POST['late_interest_account'] = 0;
//        }
//        
//        $loan_installment = get_company_loan_installment($selected_id);
//        $company_loan_id = $loan_installment['loan_id'];
//        
//        if($_POST['is_return'] == 0){
//            $payment_amount = input_num('payment_amount');// + $loan_installment['paid_amount'];               
//            $payment_interest_amount = input_num('payment_interest_amount');
//            $late_interest_amount = input_num('late_interest_amount');
//        }else{
//            $payment_amount = -(input_num('payment_amount'));// + $loan_installment['paid_amount']);               
//            $payment_interest_amount = -input_num('payment_interest_amount');
//            $late_interest_amount = -input_num('late_interest_amount');
//        }
//            
//        
//        begin_transaction();
//        
//        $sclp_msg = save_company_loan_payments($selected_id, $_POST['batch_ref'], $company_loan_id,
//                                    date2sql($_POST['payment_date']), $_POST['comments'], $_POST['is_return'],
//                                    $_POST['bank_account_id'], $payment_amount,
//                                    $_POST['interest_account'], $payment_interest_amount, 
//                                    $_POST['late_interest_account'], $late_interest_amount);  
//
//        if($sclp_msg['success'] !== true){
//            cancel_transaction();
//            display_error($sclp_msg['message']);
//        }else{
//            commit_transaction();
//            display_notification("Company loan repayment has been saved.");
//        }
//    
//    }
//}

if (isset($_POST['Add_Installment']) || isset($_POST['Update_Installment'])){

       $selected_id = substr($selected_id, 4);
       
        if(can_commit_installment(get_post('company_loan_id'), $selected_id)){
           
                $installment_amount = input_num('installment_amount');
                $interest_amount = input_num('interest_amount');   
                $capital_paid = input_num('paid_amount');
                $interest_paid = input_num('total_payment_interest');   
                $late_interest_paid = input_num('total_late_interest');
            
                                                           
            save_company_loan_installment($selected_id, $_POST['tran_date'], 
                                            $company_loan_id, $installment_amount, $interest_amount,                               
                                            $_POST['comments'], $capital_paid,
                                            $interest_paid, $late_interest_paid, $_POST['paid']);                       
          
        }
        $Mode = 'RESET';
      
}


if(isset($_POST['PAY_INSTALLMENT'])){
    
    $selected_id = substr($selected_id,3);
    make_company_loan_payment($selected_id);
    
}

//--------------------------------------------------------------------------------------------------

if ($Mode == 'Delete')
{	
    if(can_delete_company_loan_installment($selected_id)){
        delete_company_loan_installment($selected_id);
        display_notification(_("The Selected Company Loan Installment has been sucessfully deleted."));
        $Mode = 'RESET';
    }
}

if (isset($_POST['cancel'])){
   
//    unset($_POST['tran_date']); 
//    unset($_POST['installment_amount']);
//    unset($_POST['interest_amount']);
//    unset($_POST['comments']);
    
//    $Mode == 'RESET';
    $selected_id = -1;
}  

//if ($Mode == 'RESET')
//{
//    $selected_id = -1;
//}

if (isset($_POST['_selected_id_update']))
{
    $selected_id = $_POST['selected_id'];
    $Ajax->activate('_page_body');
}


    $Ajax->activate('loan_installments');
//--------------------------------------------------------------------------------------------------

start_form();

//start_table(TABLESTYLE_NOBORDER);
//    company_loans_list_row(_("Company Loan:"), 'company_loan_id', null,_('Select a loan'), true, check_value('show_inactive'));
//end_table();
        
br();

display_loan_header($company_loan_id);

br();
    
div_start('loan_installments');
display_loan_installments($company_loan_id);
div_end();

br();


//if(substr($selected_id,0,3) == 'Pay'){
//    display_loan_installment_payment_controls($company_loan_id, $selected_id);
//}
//else{
    display_loan_installment_edit_controls($company_loan_id, $selected_id);
//}

//-----------------------------------------------------------------------------------------------
    

if (!@$_GET['popup'])
{
    end_form();
    end_page(@$_GET['popup'], false, false);
}


?>
