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

$page_security = 'SA_LETTERS_OF_CREDIT';
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/letters_of_credit_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 = "Letter of Credit"));

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

simple_page_mode(true);

$lc_id = -1;

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


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

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(!($selected_id > 0)){
        if(!(get_post('bank_account_id') > 0))
        {
            display_error( _("Please select a bank account."));
            set_focus('bank_account_id');
            return false;
        }
    }
    
    if (!(input_num('lc_amount') > 0))
    {
        display_error( _("LC amount has to be numeric and positive."));
        set_focus('lc_amount');
        return false;
    }
    
    if (!check_num('bank_charge', 0))
    {
        display_error(_("Installment amount entered was not numeric or possitive."));
        set_focus('bank_charge');
        return false;
    }    
    
    if(!is_date($_POST['start_date']))
    {
        display_error(_("Start date is not a valid date"));
        set_focus('start_date');
        return false;
    }
    
    if(!is_date($_POST['expiry_date']))
    {
        display_error(_("Expiry date is not a valid date"));
        set_focus('expiry_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");
        
        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_lc_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_lc($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"];
        $_POST['bank_id'] = $myrow["bank_id"];
        $_POST['credit_facility_id'] = $myrow["credit_facility_id"];  

        if(!(isset($_POST['supplier_id']) && $_POST['supplier_id'] > 0)){        
            $_POST['supplier_id'] = $myrow["supplier_id"]; 
        }
        
        $_POST['lc_amount'] = $myrow["lc_amount"];
        $_POST['bank_charge'] = $myrow["bank_charge"];

        if(!isset($_POST['start_date'])){
            $_POST['start_date'] = sql2date($myrow["start_date"]);
            $_POST['expiry_date'] = sql2date($myrow["expiry_date"]);
        }
        
        $_POST['payable_type_id'] = $myrow["payable_type_id"];
        $_POST['payable_no_of_days'] = $myrow["payable_no_of_days"];
        $_POST['delivery_type_id'] = $myrow["delivery_type_id"];

        $_POST['inactive'] = $myrow["inactive"];
        $_POST['expired'] = $myrow["expired"];    
        
    }
    else{
//        $_POST['id'] = 0;
//        $_POST['name'] = "";
//        $_POST['description'] = "";
//        $_POST['lc_amount'] = 0;
//        $_POST['bank_charge'] = 0;
//
//        $_POST['start_date'] = "";
//        $_POST['expiry_date'] = "";
//        
//        $_POST['payable_no_of_days'] = 0;
//        
//        $_POST['inactive'] = 0;
//        $_POST['expired'] = 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);
    
    supplier_list_row("Beneficiary", 'supplier_id', null, "Select a Supplier", true);
    $supp_currency = get_supplier_currency(get_post('supplier_id'));
    label_row("Currency : :",$supp_currency);
    
    if($selected_id > 0){
        if($_POST['credit_facility_id'] > 0)
        {
            $credit_facility = get_credit_facility($_POST['credit_facility_id']); 
            $credit_facility_name = $credit_facility['name'];
            
            label_row("Credit Facility :", $credit_facility_name);
        }
        else{
            label_row("Credit Facility :", '');            
        }
        
        label_row("Bank Account :",$_POST['bank_account_number']);
        
        hidden('credit_facility_id', $_POST['credit_facility_id']);
    }
    else{
        credit_facilities_list_row(_("Credit Facility:"), 'credit_facility_id', null, "Select a credit facility", true);
        
        if($_POST['credit_facility_id'] > 0){
            credit_facility_bank_accounts_list_row("Bank Account :", "bank_account_id", null, false, 'Select a bank account');        
        }
        else{
            bank_accounts_list_row("Bank Account :", "bank_account_id", null, false, 'Select a bank account');    
        }
    }
                  
    
    amount_row(_("LC Value :"),'lc_amount', null, null, null, 2);
    amount_row(_("Bank Charge :"),'bank_charge', null,null,null,2);

    date_row("Start Date :", "start_date");
    date_row("Expiry Date :", "expiry_date");
    
    value_list_row("Payable Type", "payable_type_id", 'LC_PAYABLE_TYPES', null, '');
    amount_row(_("Payable No of Days:"),'payable_no_of_days', null, null, null, 0);
    value_list_row("Delivery Type", "delivery_type_id", 'LC_DELIVERY_TYPES', null, '');
    
    yesno_list_row("On Hold :", 'inactive');
    yesno_list_row("Expired :", 'expired');

    end_table(1);

    hidden('lc_id', $selected_id); 

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

}

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


if (($Mode=='ADD_ITEM' || $Mode=='UPDATE_ITEM') && check_data($lc_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';
            add_letter_of_credit($_POST['name'], $_POST['description'], $_POST['supplier_id'], 
                                $credit_facility_id, $_POST['bank_account_id'], 
                                input_num('lc_amount'), input_num('bank_charge'), 
                                date2sql($_POST['start_date']), date2sql($_POST['expiry_date']),
                                $_POST['payable_type_id'], input_num('payable_no_of_days'), 
                                $_POST['delivery_type_id'], $status,  
                                $_POST['inactive'], $_POST['expired']);

            display_notification(_("Company Loan has been added."));
    } 
    if ($Mode == 'UPDATE_ITEM') 
    {
          $status = 'U';
            update_letter_of_credit($lc_id, $_POST['name'], 
                                $_POST['description'], $_POST['supplier_id'], 
                                input_num('lc_amount'), input_num('bank_charge'), 
                                date2sql($_POST['start_date']), date2sql($_POST['expiry_date']),  
                                $_POST['payable_type_id'], input_num('payable_no_of_days'), 
                                $_POST['delivery_type_id'], $status,  
                                $_POST['inactive'], $_POST['expired']);

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

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;
}


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


start_form();

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

//display_company_loans();

display_lc_edit_controls($lc_id);

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


?>
