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

$page_security = 'SA_COMPANY_LOANS';
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_loans_db.inc");
include_once($path_to_root . "/finance/includes/db/credit_facilities_db.inc");
include_once($path_to_root . "/finance/includes/db/company_loan_installments_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 Loans"));

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

simple_page_mode(true);

$loan_id = -1;

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


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


if (isset($_GET['AddedID'])) 
{
	//return;
        
    $trans_no = $_GET['AddedID'];
//	$trans_type = ST_MATERIAL_REQ;

    $msg = get_session_variable('loan_messages');
    clear_session_variable('loan_messages');
        
	display_notification($msg);
	
//    display_note(get_trans_view_str($trans_type, $trans_no, _("&View this Material Requisition")));
//    
//    hyperlink_params("$path_to_root/inventory/material_requisitions.php", _("Edit this Material Requisition"), "ModifyMRNumber=$trans_no");
//        
////    br();
//
////	display_note(print_document_link($trans_no, _("&Print this Material Requisition"), true, $trans_type), 0, 0);
//
//	hyperlink_no_params($_SERVER['PHP_SELF'], _("Enter &another Material Requisition"));
//
////	hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$trans_no");
//        
//    clear_session_variable('mr_messages');

	display_footer_exit();
}


function check_data($selected_id)
{	
    if(!(strlen($_POST['name']) > 0))
    {
        display_error( _("Loan Reference can not be empty."));
        set_focus('bank_account_id');
        return false;
    }
    
    if(!($_POST['loan_type_id'] > 0))
    {
        display_error( _("Please select a loan type."));
        set_focus('loan_type_id');
        return false;
    }

    if($_POST['credit_facility_id'] > 0)
    {
        if(!($_POST['cf_sublimit_id'] > 0))
        {
            display_error( _("Please select a bank account for the credit facility."));
            set_focus('cf_sublimit_id');
            return false;
        }
    }
    
    
    if(!($_POST['bank_account_id'] > 0))
    {
        display_error( _("Please select a bank account."));
        set_focus('bank_account_id');
        return false;
    }
    
    if (!(input_num('loan_amount') > 0))
    {
        display_error( _("Loan amount has to be numeric and positive."));
        set_focus('loan_amount');
        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(!is_date($_POST['start_date']))
    {
        display_error(_("Loan Start date is not a valid date"));
        set_focus('start_date');
        return false;
    }
    

    if($_POST['credit_facility_id'] > 0){
//        $total_to_be_paid = get_total_values_of_bonds_lc_and_company_loans($_POST['credit_facility_id']);
//        $cf_amount = get_credit_facility_amount_total($_POST['credit_facility_id']);
//        $cf_total_amount = $cf_amount['amount_total'];
//
//        $total_balance = $cf_total_amount - $total_to_be_paid;
//                         // 200000              50000
//
//        if(_($_POST['loan_amount']) >= $total_balance){
//            display_error(_("Loan amount can not be greater than the credit facility balance of $cf_total_amount"));
//            set_focus('loan_amount');
//            return false;     
//        }
    
    }       
    return true;    
}

function can_delete_company_loan($selected_id)
{
    $result = get_company_loan_installments($selected_id);
    if(db_num_rows($result) > 0){
        display_error(_("This loan has loan payments. It can not be deleted."));
        set_focus('loan_description');
        return false;
    }
    
    return true;
}


function display_company_loans()
{
    $result = get_company_loans();
    
    div_start('price_table');
    
    if (db_num_rows($result) == 0)
    {
    	display_note(_("There are no active loans."));
        return;
    }

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

    $th = array(_("id"),_("Credit Facility"),_("Bank"),_("Branch"),
                _("Loan Description"), _("Total Loan"),
                _("Installment"), _("Interest"),_("Start Date"), 
                _("Capital paid"), _("Interest Paid"), _("Last Pay. Date"), 
                _("On Hold"), _("Completed"), "", "");

    table_header($th);

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

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

        if($myrow['credit_facility_id'] > 0){
            $credit_facility = get_credit_facility($myrow['credit_facility_id']); 
            $credit_facility_name = $credit_facility['name'];
            $banck_name = $credit_facility['bank_name'];
            $branch_name = $credit_facility['branch_name'];
        }
        else{
            $credit_facility_name = '';
            $banck_name = $myrow['bank_name'];
            $branch_name = $myrow['branch_name'];
        }
    
    
        label_cell($myrow["id"]);
        label_cell($credit_facility_name);
        label_cell($banck_name);
        label_cell($branch_name);           
        label_cell($myrow["loan_description"]);                      
        label_cell(number_format($myrow["loan_amount"], 2), "align=right");
        label_cell(number_format($myrow["installment_amount"], 2), "align=right");
        label_cell(number_format($myrow["interest"], 2), "align=right");
        label_cell(sql2date($myrow["start_date"]), "align=center");
        label_cell(number_format($myrow["total_captal_paid"], 2), "align=right");
        label_cell(number_format($myrow["total_interest_paid"], 2), "align=right");
        label_cell(number_format($myrow["total_late_interest_paid"], 2), "align=right");
        
        if(substr($myrow["last_payment_date"], 0, 4) == "0000"){
            label_cell('');      
        }
        else{
            label_cell(sql2date($myrow["last_payment_date"]), "align=center");
        }

        if($myrow["inactive"] == 1)
            label_cell("Yes", "align=center");
        else {
            label_cell("No", "align=center");
        }

        if($myrow["completed"] == 1)
            label_cell("Yes", "align=center");
        else {
            label_cell("No", "align=center");
        }

        edit_button_cell("Edit".$myrow['id'], _("Edit"));
        delete_button_cell("Delete".$myrow['id'], _("Delete"));
        end_row();

        $j++;
        If ($j == 12)
        {
            $j = 1;
            table_header($th);
        } //end of page full new headings
    } //end of while loop

    end_table();
    
    div_end();
    
}

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

function display_company_loan_extend_edit_controls($loan_id)
{
    if(!($loan_id>0)){
        return;
    }
    start_table(TABLESTYLE2);
    
    text_row(_("Reference :"), 'extend_loan_reference', get_post('name'), 25, 50);   
    text_row("Description :", "extend_loan_description", get_post('description'), 50,200);        
    //amount_row(_("Bank Account :"), 'extend_loan_bank_account', null, null, null, 2);  
    
    $myrow = get_company_loan($loan_id);
    
    $_POST['loan_amount'] = $myrow['loan_amount']; 
    $_POST['total_captal_paid'] = $myrow['total_captal_paid'];
    
    $balance_amount = $_POST['loan_amount'] - $_POST['total_captal_paid'];
    
    amount_row(_("Total Loan :"),'extend_loan_amount', number_format($balance_amount, 2), null, null, 2);
    amount_row(_("Interest :"),'extend_interest', get_post('interest'), null,null,2);
    amount_row(_("Installment Amount :"),'extend_installment_amount', get_post('installment_amount'), null,null,2);
    amount_row(_("Installment Interest :"),'extend_installment_interest', get_post('interest'), null,null,2);
    amount_row("Bank Charge:", 'extend_bank_charge');
    date_row("Loan Start Date :", "extend_start_date");    
    
    end_table(1);
    
    submit_center_first('EXTEND_LOAN', _("Extend Loan"), '', 'default');
    
}

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

function can_extend_loan($selected_id)
{
    $loan = get_loan_record($selected_id);
    if($loan['completed'] == 1){
        display_error( _("The original loan is already completed. It can not be extended."));
        set_focus('loan_amount');
        return false;
    }
    
    $loan = get_extended_id($selected_id);
    $original_loan_id = $loan['original_loan_id'];
    
    if($original_loan_id > 0){
        display_error("This Loan is already extended to Loan ".$loan['id']);        
        return false;
    }    
        
    return true;
}

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

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

    if (list_updated('credit_facility_id')){
        $Ajax->activate('price_table');
    }

    start_table(TABLESTYLE_NOBORDER);
    start_row();
    
    
    if($selected_id > 0)
    {
        $myrow = get_company_loan($selected_id);

        $_POST['id'] = $myrow["id"];
        $_POST['name'] = $myrow["name"];
        $_POST['description'] = $myrow["description"];
        $_POST['bank_id'] = $myrow["bank_id"];
        $_POST['bank_name'] = $myrow["bank_name"];
        $_POST['bank_account_number'] = $myrow["bank_account_number"];
        
        if(!(isset($_POST['credit_facility_id']) && $_POST['credit_facility_id']) > 0){
            $_POST['credit_facility_id'] = $myrow["credit_facility_id"];
        } 

        if(!(isset($_POST['bank_account_id']) && $_POST['bank_account_id']) > 0){
            $_POST['bank_account_id'] = $myrow["bank_account_id"];
        } 
      
        if($_POST['credit_facility_id']> 0){
            if(!(isset($_POST['cf_sublimit_id']) && $_POST['cf_sublimit_id']) > 0){
                $cf_sublimit = get_credit_facility_sub_limit_record_by_bank_account($_POST['credit_facility_id'], $_POST['bank_account_id']);
                $_POST['cf_sublimit_id'] = $cf_sublimit["id"];
            }
        }
        
        $_POST['loan_amount'] = $myrow["loan_amount"];
        $_POST['interest'] = $myrow["interest"];
        $_POST['installment_amount'] = $myrow["installment_amount"];
        $_POST['installment_interest'] = $myrow["installment_interest"];
        $_POST['start_date'] = sql2date($myrow["start_date"]);
        $_POST['inactive'] = $myrow["inactive"];
        $_POST['completed'] = $myrow["completed"]; 
        $_POST['bank_charge'] = $myrow["bank_charge"]; 
        
        if(!(isset($_POST['loan_type_id']) && $_POST['loan_type_id']) > 0){
            $_POST['loan_type_id'] = $myrow["loan_type_id"]; 
        }
        
        if(!(isset($_POST['loan_account']) && $_POST['loan_account']) > 0){
            $_POST['loan_account'] = $myrow["loan_account"]; 
        } 
        
        if(!(isset($_POST['interest_account']) && $_POST['interest_account']) > 0){
            $_POST['interest_account'] = $myrow["interest_account"]; 
        } 
        
        if(!(isset($_POST['late_interest_account']) && $_POST['late_interest_account']) > 0){
            $_POST['late_interest_account'] = $myrow["late_interest_account"]; 
        } 
             
    }
    else{
        $_POST['id'] = 0;
        $_POST['name'] = "";
        $_POST['description'] = "";
        $_POST['loan_type_id'] = 0;
        $_POST['loan_amount'] = 0;
        $_POST['interest'] = 0;
        $_POST['installment_amount'] = 0;
        $_POST['installment_interest'] = 0;
        $_POST['start_date'] = "";
        $_POST['inactive'] = 0;
        $_POST['completed'] = 0;
        
        if(!(isset($_POST['credit_facility_id']) && $_POST['credit_facility_id'] > 0)){
            $_POST['credit_facility_id'] = 0;
        }
    }
     
    text_row("Reference :", "name", null, 50,100);
    text_row("Description :", "description", null, 50,200);

    value_list_row("Type :", 'loan_type_id', "COMPANY_LOAN_TYPES", null, "Select a type");
    
    if($selected_id > 0){

//            $credit_facility = get_credit_facility($_POST['credit_facility_id']); 
//            $credit_facility_name = $credit_facility['name'];
             
            credit_facilities_list_row(_("Credit Facility:"), 'credit_facility_id', null, "", true);
                hidden('loan_id', $_POST['loan_id']);
            
        if($_POST['credit_facility_id'] > 0)
        {
            credit_facility_bank_accounts_list_row("Bank Account :", "cf_sublimit_id", $_POST['credit_facility_id'], null, true, 'Select a bank account');        
            $cf_sublimit = get_credit_facility_sub_limit_record($_POST['cf_sublimit_id']);
            hidden('bank_account_id', $cf_sublimit['bank_account_id']);
            
        }
        else{
            bank_accounts_list_row("Bank Account :", "bank_account_id", null, false, 'Select a bank account');    
        }
    }
    else{
        credit_facilities_list_row(_("Credit Facility:"), 'credit_facility_id', null, "", true);
        
        if($_POST['credit_facility_id'] > 0)
        {
            credit_facility_bank_accounts_list_row("Bank Account :", "cf_sublimit_id", $_POST['credit_facility_id'], null, true, 'Select a bank account');        
            $cf_sublimit = get_credit_facility_sub_limit_record($_POST['cf_sublimit_id']);
            hidden('bank_account_id', $cf_sublimit['bank_account_id']);
            
        }
        else{
            bank_accounts_list_row("Bank Account :", "bank_account_id", null, false, 'Select a bank account');    
        } 
    }            
    
    gl_all_accounts_list_row("Loan Account:", 'loan_account');
    gl_all_accounts_list_row("Interest Account:", 'interest_account');
    gl_all_accounts_list_row("Late Interest Account:", 'late_interest_account');
    amount_row(_("Loan Capital Amount:"),'loan_amount', $_POST['loan_amount'], null, null, 2);
    amount_row(_("Loan Interest:"),'interest', $_POST['interest'],null,null,2);
    amount_row(_("Installment Amount:"),'installment_amount', $_POST['installment_amount'],null,null,2);
    amount_row(_("Installment Interest:"),'installment_interest', $_POST['interest'],null,null,2);
    amount_row("Bank Charge:", 'bank_charge');
    date_row("Loan Start Date :", "start_date", $_POST['start_date']);
    
    if($selected_id > 0){
        if(substr($myrow["last_payment_date"],0,4) == "0000"){
            label_row("Last Paid Date :", "No repayments yet");
        }
        else{
            label_row("Last Paid Date :", sql2date($myrow["last_payment_date"]));
        }
        label_row("Total Capital Paid :", number_format($myrow["total_captal_paid"],2));
        label_row("Total Interest Paid :", number_format($myrow["total_interest_paid"],2));
        label_row("Total Late Interest Paid :", number_format($myrow["total_late_interest_paid"],2));
    }
    yesno_list_row("On Hold :", 'inactive', $_POST['inactive'] );
    yesno_list_row("Completed :", 'completed', $_POST['completed'] );

    end_table(1);

    hidden('selected_id', $selected_id); 

    submit_add_or_update_center($selected_id == -1, '', 'both');

}

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


if (($Mode=='ADD_ITEM' || $Mode=='UPDATE_ITEM') && check_data($selected_id))
{
    if ($Mode == 'ADD_ITEM') 
    {
        if($_POST['credit_facility_id'] > 0){
            $credit_facility_id = $_POST['credit_facility_id'];
        }
        else{
            $credit_facility_id = 0;
        }
        $status = 'N';
            $loan_id = add_company_loan($_POST['name'], $_POST['description'], $_POST['loan_type_id'], 
                                $credit_facility_id, $_POST['bank_account_id'], 
                                input_num('loan_amount'), input_num('interest'), input_num('installment_amount'), 
                                input_num('installment_interest'), input_num('bank_charge'), $_POST['start_date'], $status,  
                                $_POST['inactive'], $_POST['completed'], 0,
                                $_POST['loan_account'], $_POST['interest_account'], $_POST['late_interest_account']);

            display_notification(_("Company Loan has been added."));
            
       
    } 
    
    if ($Mode == 'UPDATE_ITEM') 
    {
        if($_POST['credit_facility_id'] > 0){
            $credit_facility_id = $_POST['credit_facility_id'];
        }
        else{
            $credit_facility_id = 0;
        }
        
          $status = 'U';
            update_company_loan($selected_id, $_POST['name'], $_POST['description'],
                                $_POST['loan_type_id'], $credit_facility_id,
                                input_num('loan_amount'), input_num('interest'), input_num('installment_amount'), 
                                input_num('installment_interest'), input_num('bank_charge'), date2sql($_POST['start_date']), $status, 
                                $_POST['inactive'], $_POST['completed'],
                                $_POST['loan_account'], $_POST['interest_account'], $_POST['late_interest_account'],
                                $_POST['bank_account_id'] );

            $selected_id = -1;
            display_notification(_("Company Loan has been updated."));
    }    
    $Mode = 'RESET';
}

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

if(isset($_POST['EXTEND_LOAN']) && can_extend_loan($selected_id))
{
    $el_msg = extend_loan($selected_id, $_POST['extend_loan_reference'], $_POST['extend_loan_description'], 
                            input_num('extend_loan_amount'), input_num('extend_interest'), input_num('extend_installment_amount'),
                            input_num('extend_installment_interest'), input_num('extend_bank_charge'), $_POST['extend_start_date'] );  
                         
    
    if($el_msg['success'] !== true){
        display_error($el_msg['message']);
    }
    else{
        $selected_id = -1;
        $Mode = 'RESET';

        set_session_variable('loan_messages', $el_msg['message']);
        meta_forward($_SERVER['PHP_SELF'], "AddedID=".$el_msg['trans_no']);
    }
}

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

if ($Mode == 'Delete' && can_delete_company_loan($selected_id))
{    
    delete_company_loan($selected_id);
	display_notification(_("The Selected Company Loan has been deleted."));
	$Mode = 'RESET';
}

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

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

start_form();

//start_table(TABLESTYLE2);
//company_loans_list_row("Company Loan :", 'compay_loan_id');
//end_table();

//display_company_loans();

display_company_loan_edit_controls($loan_id);

br();

display_company_loan_extend_edit_controls($loan_id);

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


?>
