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





function check_bond_data($selected_id)
{	
    $bond = get_bond_record($selected_id);
    if($bond['expired'] == 1){
        display_error( _("Selected bond is already expired. It can not be edited."));
        set_focus('loan_amount');
        return false;
    }

        
    if(!(strlen(get_post('bond_name')) > 0)){
        display_error( _("Bond name can not be empty."));
        set_focus('bond_name');
        return false;
    }
    
    if(!($selected_id > 0)){
        if(!(get_post('bond_type') > 0)){
            display_error( _("Please select a Bond Type."));
            set_focus('bond_type');
            return false;
        }
    
        if(get_post('payable') == 1){
            if(!(get_post('customer_id') > 0)){
                display_error( _("Please select a Beneficiary."));
                set_focus('customer_id');
                return false;
            }

            if(!(get_post('credit_facility_id') > 0)){
                if(!(get_post('bank_account_id') > 0)){
                    display_error( _("Please select a Bank Account."));
                    set_focus('bank_account_id');
                    return false;
                }
            }
        }
        else{
            if(!(get_post('supplier_id') > 0)){
                display_error( _("Please select a Guarantor."));
                set_focus('customer_id');
                return false;
            }
            if(!(get_post('bank_id') > 0)){
                display_error( _("Please select a Bank."));
                set_focus('bank_id');
                return false;
            }

            if(!(get_post('branch_id') > 0)){
                display_error( _("Please select a Bank Branch."));
                set_focus('branch_id');
                return false;
            }
        }    

        if(!(get_post('project_id') > 0)){
            display_error( _("Please select a Project."));
            set_focus('project_id');
            return false;
        }
        
        if (!(input_num('bond_value') > 0))
        {
            display_error(_("Bond value has to be a positive value."));
            set_focus('loan_amount');
            return false;
        }

        if (!check_num('bank_charge', 0))
        {
            display_error(_("Bank charge entered is not numeric or possitive."));
            set_focus('bank_charge');
            return false;
        } 
    }
    
    if(!is_date($_POST['start_date']))
    {
        display_error(_("Bond Effective date is not a valid date"));
        set_focus('start_date');
        return false;
    }
    
    if(!is_date($_POST['expiry_date']))
    {
        display_error(_("Bond Expiry date is not a valid date"));
        set_focus('start_date');
        return false;
    }
         
    return true;    
}


function can_extend_bond($selected_id)
{
    $bond = get_bond_record($selected_id);
    if($bond['expired'] == 1){
        display_error( _("The original bond is already expired. It can not be extended."));
        set_focus('loan_amount');
        return false;
    }
        
    $extended_bond = get_original_bond($selected_id);
    $original_bond_id = $extended_bond['original_bond_id'];
    
    if($original_bond_id > 0){
        display_error("This Bond is already extended to Bond ".$extended_bond['id']);        
        return false;
    }    
    
    return true;
}


function display_bonds()
{
    $result = get_bonds();
    
    div_start('price_table');
    
    if (db_num_rows($result) == 0)
    {
    	display_note(_("There are no Bonds defined."));
        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_bond_edit_controls($selected_id)
{   
    if($selected_id > 0)
    {
        $myrow = get_bond($selected_id);

        $_POST['id'] = $myrow["id"];
//        $_POST['bond_name'] = $myrow["name"];        
        set_post_not_set_string('bond_name', $myrow["name"]);
        
//        $_POST['bond_description'] = $myrow["description"];
        set_post_not_set_string('bond_description', $myrow["description"]);
        
        $_POST['bond_type_name'] = $myrow["bond_type_name"];
        $_POST['payable'] = $myrow["payable"];
        
//        $_POST['customer_id'] = $myrow["customer_id"];
        set_post_not_set_numeric('customer_id', $myrow["customer_id"]);
        
        $_POST['supplier_id'] = $myrow["supplier_id"];
        set_post_not_set_numeric('supplier_id', $myrow["supplier_id"]);
        
//        $_POST['credit_facility_id'] = $myrow["credit_facility_id"];
//        set_post_not_set_numeric('credit_facility_id', $myrow["credit_facility_id"]);
        if(!(isset($_POST['credit_facility_id']))){
            $_POST['credit_facility_id'] = $myrow["credit_facility_id"];
        }
//        $_POST['project_id'] = $myrow["project_id"];
        set_post_not_set_numeric('project_id', $myrow["project_id"]);
        
//        $_POST['bond_value'] = $myrow["value"];
        set_post_not_set_numeric('bond_value', $myrow["value"]);
        
//        $_POST['bank_charge'] = $myrow["bank_charge"];
        set_post_not_set_numeric('bank_charge', $myrow["bank_charge"]);
        
//        $_POST['start_date'] = sql2date($myrow["start_date"]);
        set_post_not_set_string('start_date', sql2date($myrow["start_date"]));
        
//        $_POST['expiry_date'] = sql2date($myrow["expiry_date"]);
        set_post_not_set_string('expiry_date', sql2date($myrow["expiry_date"]));
        
//        $_POST['expired'] = $myrow["expired"];
        set_post_not_set_numeric('expired', $myrow["expired"]);
        
        $_POST['original_bond_id'] = $myrow["original_bond_id"];   
        $_POST['comment'] = $myrow["comments"];
        
    }
    else{
//        $_POST['id'] = 0;
////        $_POST['bond_name'] = "";
////        $_POST['bond_description'] = "";
//        $_POST['bond_type_name'] = 0;
////        $_POST['payable'] = 0;
//        $_POST['credit_facility_id'] = 0;
////        $_POST['project_id'] = 0;
////        $_POST['bond_value'] = 0;
////        $_POST['bank_charge'] = 0;
////        $_POST['start_date'] = '';
////        $_POST['expiry_date'] = '';
////        $_POST['expired'] = 0;
//        $_POST['original_bond_id'] = 0;   
        
//        if(!(isset($_POST['credit_facility_id']) && $_POST['credit_facility_id'] > 0)){
//            $_POST['credit_facility_id'] = 0;
//        }
    }
     
    div_start('bond_edit_controls');

    start_table(TABLESTYLE2);
    start_row();
    
    if(isset($_POST['payable']) && $_POST['payable'] > 0){
        hidden('payable', $_POST['payable']);
    }
    else{
        hidden('payable', 0);
    }
    
    if($selected_id > 0){
        label_row("Type :",$_POST['bond_type_name']);     
        label_row("Payable :", get_yes_no_name($_POST['payable']));
        text_row(_("Name :"), 'bond_name', null, 25, 50);   
        text_row("Description :", "bond_description", null, 50,500);
        
    }
    else{
        text_row(_("Name :"), 'bond_name', null, 25, 50);   
        text_row("Description :", "bond_description", null, 50,500);
        value_list_row(_("Type :"), 'bond_type', "BOND_TYPES", null, 'Select a Type');  
        yesno_list_row("Payable:", 'payable', null, 'yes', 'no', true);
    }

    if($_POST['payable'] > 0){
        customer_list_row("Beneficiary :", 'customer_id', null, 'Select a Customer', false);
        $_POST['supplier_id'] = 0;
    }
    else{
        supplier_list_row("Guarantor :", 'supplier_id', null, 'Select a Supplier', false);
        $_POST['customer_id'] = 0;
        $_POST['credit_facility_id']  = 0;
    }
        
    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'];
//            $banck_name = $credit_facility['bank_name'];
//            $branch_name = $credit_facility['branch_name']; 
//            
//            label_row("Credit Facility :", $credit_facility_name);
//            label_row("Bank Name :",$banck_name);
//            label_row("Bank Branch :",$branch_name);     
//            label_row("Bank Account :",'');
//        }
//        else{
//            label_row("Credit Facility :", '');
//            label_row("Bank Name :",$myrow['bank_name']);
//            label_row("Bank Branch :",$myrow['branch_name']);
//            label_row("Bank Account :",$myrow['bank_account_number']);
//        }
//        
//        hidden('credit_facility_id', $_POST['credit_facility_id']);
        
//        label_row("Project :",$myrow["project_description"]);
        
        if($_POST['payable'] > 0){
            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 an account');
                $credit_facility = get_credit_facility($_POST['credit_facility_id']);
                hidden('bank_id', $credit_facility['bank_id']); 
                hidden('branch_id', $credit_facility['branch_id']); 
            }
            else{
                bank_accounts_list_row("Bank Account :", 'bank_account_id', null, false, 'Select a bank account');
                hidden('bank_id', 0); 
                hidden('branch_id', 0); 
            }
            
        }
        else{
            hidden('credit_facility_id', 0); 
            value_list_row(_("Bank Name :"), 'bank_id', "BANKS", null, 'Select a Bank', true);     
            bank_branch_list_row("Bank Branch :", 'branch_id', $_POST['bank_id'], null, 'Select a Bank Branch', false);
            hidden('bank_account_id', 0);            
        }
        
        project_list_row("Project :", 'project_id', null, ''); 
//        label_row("Bond Value :", number_format($_POST['bond_value'],2));
//        label_row("Bank Charge :", number_format($_POST['bank_charge'],2));
    }
    else{
        if($_POST['payable'] > 0){
            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 an account');
                $credit_facility = get_credit_facility($_POST['credit_facility_id']);
                hidden('bank_id', $credit_facility['bank_id']); 
                hidden('branch_id', $credit_facility['branch_id']); 
            }
            else{
                bank_accounts_list_row("Bank Account :", 'bank_account_id', null, false, 'Select a bank account');
                hidden('bank_id', 0); 
                hidden('branch_id', 0); 
            }
            
        }
        else{
            hidden('credit_facility_id', 0); 
            value_list_row(_("Bank Name :"), 'bank_id', "BANKS", null, 'Select a Bank', true);     
            bank_branch_list_row("Bank Branch :", 'branch_id', $_POST['bank_id'], null, 'Select a Bank Branch', false);
            hidden('bank_account_id', 0);            
        }
        
        project_list_row("Project :", 'project_id', null, ''); 

    }
    
    amount_row(_("Bond Value :"), 'bond_value', null, null, null, 2);  
    amount_row(_("Bank Charge :"), 'bank_charge', null, null, null, 2);              

                  
    date_row("Effective Date :", 'start_date');
    date_row("Expiry Date :", 'expiry_date');
    if($selected_id > 0){
        yesno_list_row("Expired :", 'expired' );
    }
    else{
        hidden('expired', 0);
    }
    textarea_row(_('Comment :'), 'comment', null, 31, 3);
    
    end_table(1);

    hidden('selected_id', $selected_id); 
    hidden('bond_id', $_POST['bond_id']); 

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

}


function display_bond_extend_edit_controls()
{
    start_table(TABLESTYLE2);
    
    text_row(_("Name :"), 'extend_bond_name', get_post('bond_name'), 25, 50);   
    text_row("Description :", "extend_bond_description", get_post('bond_description'), 50,200);
        
    $_POST['extend_bond_value'] = $_POST['bond_value'];
    $_POST['extend_bank_charge'] = $_POST['bank_charge'];
    amount_row(_("Bond Value :"), 'extend_bond_value', null, null, null, 2);  
    amount_row(_("Bank Charge :"), 'extend_bank_charge', null, null, null, 2); 
        
    $_POST['extend_start_date'] = $_POST['start_date'];
    $_POST['extend_expiry_date'] = $_POST['expiry_date'];
    date_row("Effective Date :", 'extend_start_date');
    date_row("Expiry Date :", 'extend_expiry_date');
    
    textarea_row(_('Comment :'), 'extend_comment', get_post('comment'), 31, 3);
    
    end_table(1);
    
    submit_center_first('EXTEND_BOND', _("Extend Bond"), '', 'default');
    
}


function handle_new_bond(&$Mode, &$selected_id)
{

    if(!check_bond_data($selected_id)){
        return;    
    }

    
    if(get_post('payable') == 1){
        $customer_id = get_post('customer_id');
        if($_POST['credit_facility_id'] > 0){
            $credit_facility_id = $_POST['credit_facility_id'];
        }
        else{
            $credit_facility_id = 0; 
        }
        
        $bank_account_id = get_post('bank_account_id');
        $bank_account = get_bank_account($bank_account_id);
        $bank_id = $bank_account['bank_id'];
        $branch_id = $bank_account['branch_id'];
        
        $supplier_id = 0;
    }
    else{
        $credit_facility_id = 0;
        $bank_account_id = 0;
        $bank_id = $_POST['bank_id'];
        $branch_id = $_POST['branch_id'];
        
        $customer_id = 0;
        $supplier_id = get_post('supplier_id');
    }

    $ab_msg = add_bond($_POST['bond_name'], $_POST['bond_description'], $credit_facility_id, 
                $_POST['bond_type'], $_POST['payable'], $customer_id, $supplier_id, 
                $bank_id, $branch_id, $bank_account_id, 
                input_num('bond_value'), input_num('bank_charge'), 
                $_POST['start_date'], $_POST['expiry_date'], 
                $_POST['project_id'], $_POST['comment'], $_POST['expired']);          

    if($ab_msg['success'] !== true){
        display_error($ab_msg['message']);
    }
    else{
        $selected_id = -1;
        $Mode = 'RESET';

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


function handle_update_bond(&$Mode, &$selected_id)
{
    if(!check_bond_data($selected_id)){
        return;    
    }

    
    if(get_post('payable') == 1){
        $customer_id = get_post('customer_id');
        if($_POST['credit_facility_id'] > 0){
            $credit_facility_id = $_POST['credit_facility_id'];
        }
        else{
            $credit_facility_id = 0; 
        }
        
        $bank_account_id = get_post('bank_account_id');
        $bank_account = get_bank_account($bank_account_id);
        $bank_id = $bank_account['bank_id'];
        $branch_id = $bank_account['branch_id'];
        
        $supplier_id = 0;
    }
    else{
        $credit_facility_id = 0;
        $bank_account_id = 0;
        $bank_id = $_POST['bank_id'];
        $branch_id = $_POST['branch_id'];
        
        $customer_id = 0;
        $supplier_id = get_post('supplier_id');
    }
//    $ub_msg = update_bond($selected_id, $_POST['bond_name'], $_POST['bond_description'],                    
//                $_POST['start_date'], $_POST['expiry_date'], 
//                $customer_id, $supplier_id, $_POST['project_id'],
//                $_POST['comment'], $_POST['expired']);   
    
    $ub_msg = update_bond($selected_id, $_POST['bond_name'], $_POST['bond_description'], $credit_facility_id, 
                $customer_id, $supplier_id, 
                $bank_id, $branch_id, $bank_account_id, 
                input_num('bond_value'), input_num('bank_charge'), 
                $_POST['start_date'], $_POST['expiry_date'], 
                $_POST['project_id'], $_POST['comment'], $_POST['expired']);   

    if($ub_msg['success'] !== true){
        display_error($ub_msg['message']);
    }
    else{
        $selected_id = -1;
        $Mode = 'RESET';

//        set_session_variable('bond_messages', $ub_msg['message']);
//        meta_forward($_SERVER['PHP_SELF'], "AddedID=".$ub_msg['trans_no']);
    }
}

function handle_extend_bond(&$Mode, &$selected_id)
{
    if(!can_extend_bond($selected_id)){
        return;    
    }

    $eb_msg = extend_bond($selected_id, $_POST['extend_bond_name'], $_POST['extend_bond_description'], 
                input_num('extend_bond_value'), input_num('extend_bank_charge'),
                $_POST['extend_start_date'], $_POST['extend_expiry_date'], $_POST['extend_comment']);  
    
    if($eb_msg['success'] !== true){
        display_error($eb_msg['message']);
    }
    else{
        $selected_id = -1;
        $Mode = 'RESET';

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