<?php



function can_delete_utility_bill_cn_item($ubcn_no)
{
    $line_count = get_utility_bill_cn_line_count($ubcn_no);
    if(!($line_count > 0)){
        $message = "This is the last line. It can not be deleted.";
        display_error($message);
        return false;
    }
    
    return true;

}

function can_process_ub_cn_header($ubcn_no)
{
    global $Refs;
    
    if(!$Refs->is_valid($_POST['reference'])){
        $message = "Please enter a reference.";
        $set_focus = 'reference';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);   
    }
 
    $ref_msg = reference_exists($_POST['reference'], ST_UTILITY_BILL_CREDIT_NOTE, $ubcn_no);
    if($ref_msg){
        $message = $ref_msg;
        $set_focus = 'reference';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);   
    }
    
    if (!($_POST['project_id'] > 0))
    {
        $message = "Please select a Project.";
        $set_focus = 'project_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    if($ubcn_no > 0){
        $ubh = get_utility_bill_cn_header($ubcn_no);
        if(!($ubh['approval_status'] == AS_NEW || $ubh['approval_status'] == AS_WITH_THE_APPROVER || 
                $ubh['approval_status'] == AS_AWAITING_APPROVAL || $ubh['approval_status'] == AS_BACK_TO_ORIGINATOR)){
            $message = ("This document status does not allow further updating.");
            return array("success" => false, "focus_to" => '', "message" => $message);
        }
        
        $current_user_id = $_SESSION['wa_current_user']->user;
        $ced_msg = can_edit_document(ST_UTILITY_BILL_CREDIT_NOTE, $_POST['project_id'], $ubh['next_approval_group_id'] , $current_user_id, $ubh['created_by'], $ubcn_no);
        if($ced_msg['success'] !== true){
            return array("success" => false, "focus_to" => '', "message" => $ced_msg['message']);
        }
        
    }
    
    
    if(!($_POST['supplier_id'] > 0))
    {
        $message = "Please select a supplier.";
        $set_focus = 'supplier_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }      

    if(!is_date($_POST['date']))
    {
        $message = "Date entered is not a valid date.";
        $set_focus = 'date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
    
    if (!is_date_in_fiscalyear($_POST['date'])) {
        $message = (_("The entered date is not in fiscal year."));
        $set_focus = ('date');
        return array("success"=>false, "set_focus"=>$set_focus, "message"=>$message);
    }
        
    $msg = is_accounting_period_open($_POST['date']);
    if ($msg['success'] !== true)
    {
        $message = ($msg['message']);
        $set_focus = ('date');
        return array("success"=>false, "set_focus"=>$set_focus, "message"=>$message);
    }
    
    if(!($_POST['tax_group_id'] > 0))
    {
        $message = "Please select a tax group.";
        $set_focus = 'tax_group_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);         
    }
      
    return array("success" => true, "message" => "");    
}

 
function can_process_ub_cn_line($ubcn_no)
{
    if($_POST['bill_no'] == '')
    {
        $message = "Bill number cannot be empty.";
        $set_focus = 'bill_no';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }    
    
    if(!($_POST['amount'] > 0))
    {
        $message = "Amount should be greater than zero.";
        $set_focus = 'amount';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    if(!(strlen($_POST['description']) > 0))
    {
        $message = "Description can not be empty.";
        $set_focus = 'description';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);         
    }
    
    if(!is_date($_POST['period_from']))
    {
        $message = "Period from date is not a valid date.";
        $set_focus = 'period_from';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);         
    }
    
    if(!is_date($_POST['period_to']))
    {
        $message = "Period to date is not a valid date.";
        $set_focus = 'period_to';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);         
    }
    
    if(date1_greater_date2($_POST['period_from'], $_POST['period_to']))
    {
        $message = "Period from date cannot be greater than period to date.";
        $set_focus = 'period_to';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
    }
    
    if(!($_POST['task_id'] > 0))
    {
        $message = "Please select a Budget.";
        $set_focus = 'task_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
    }
    
        
    switch ($_POST['expense_category_id']) {
        case EC_VEHICLE_MAINTENANCE:
            if(!($_POST['expense_item_id'] > 0))
            {
                $message = ( _("Please select a vehicle."));
                $set_focus = ('expense_item_id');
                return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
            }
        case EC_ASSET_MAINTENANCE:
            if(!($_POST['expense_item_id'] > 0))
            {    
                $message = ( _("Please select an asset."));
                $set_focus = ('amount');
                return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
            }
        case EC_UTILITY_ITEM:
            if(!($_POST['expense_item_id'] > 0))
            {    
                $message = ( _("Please select an utility item."));
                $set_focus = ('amount');
                return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
            }

        default:
            break;
    }
    
    
    
    if(!($_POST['expense_type_id'] > 0))
    {
        $message = "Please select an expense Type.";
        $set_focus = 'expense_type_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
    }
            
    return array("success" => true, "message" => "");    
}

   

function save_utility_bills_cn_header(&$ubcn_no)
{     
    $ubcn_no = write_utility_bill_cn_header($ubcn_no, $_POST['reference'], $_POST['project_id'],
                                            $_POST['supplier_id'], $_POST['date'],
                                            $_POST['rate_include_taxes'], $_POST['tax_group_id'] );   
    
    if($ubcn_no > 0){
        set_session_variable("ST_UTILITY_BILL_CREDIT_NOTE_ubcn_no", $ubcn_no);
        return array("success" => true, 'trans_no' => $ubcn_no, "message" => "Utility bills credit note header information have been saved.");
    }
    else{
        return array("success" => false, 'trans_no' => '', "message" => "Could not save Utility bills credit note header.");
    }
}



function save_utility_bill_cn_detail(&$ubcn_no, $selected_id)
{
    return write_utility_bill_cn_detail($ubcn_no, $selected_id, $_POST['bill_no'], 
                                $_POST['bill_reference'], $_POST['description'], input_num('amount'),
                                $_POST['period_from'], $_POST['period_to'], $_POST['task_id'], $_POST['expense_type_id'],
                                $_POST['rate_include_taxes'], $_POST['tax_group_id'],
                                $_POST['expense_category_id'], $_POST['expense_item_id'], $_POST['project_site_id']);
    
}


function save_utility_bills_cn(&$ubcn_no, $selected_id)
{
    $temp_ub_no = $ubcn_no;
    
    $h_msg = can_process_ub_cn_header($ubcn_no);   
    
        if($h_msg["success"] !== true) 
        {          
            if(isset($h_msg["focus_to"])){
                set_focus($h_msg["focus_to"]);
            }
            return array("success" => false, "message" => $h_msg["message"]);
        }
        
    $line_msg = can_process_ub_cn_line($ubcn_no);
        if($line_msg['success'] !== true){
            if(isset($line_msg["focus_to"])){
                set_focus($line_msg["focus_to"]);
            }
            return array("success" => false, "message" => $line_msg["message"]);
        }
    
    begin_transaction();
    $msg = save_utility_bills_cn_header($ubcn_no);
    if($msg["success"] !== true){
        cancel_transaction();
        return array("success" => false, 'trans_no' => $ubcn_no, "message" => $msg["message"]);
    }

    $msg = save_utility_bill_cn_detail($ubcn_no, $selected_id);
    if($msg["success"] !== true){
        cancel_transaction();
        return array("success" => false, 'trans_no' => $ubcn_no, "message" => $msg["message"]);
    }
    
    commit_transaction();
    if($temp_ub_no > 0){
        return array("success" => true, 'trans_no' => $ubcn_no, "message" => $msg["message"]);
    }
    else{
        return array("success" => true, 'trans_no' => $ubcn_no, "message" => "Utility Bill Credit Note $ubcn_no has been created.");
    }

}

function display_utility_bill_cn_header($ubcn_no)
{
    global $approval_statuses, $Refs;
    
    if($ubcn_no > 0){
        $ub_header = get_utility_bill_cn_header($ubcn_no);
        
        $project_id = $ub_header['project_id'];
        $user_id = $_SESSION['wa_current_user']->user;
        $cap = can_access_project($project_id, $user_id);
        if($cap['success'] !== true) 
        {
            display_error($cap["message"]);
            set_focus('project_id');
            display_footer_exit();
            exit;
        }  
        
        $_POST['project_id'] = $ub_header['project_id'];
    
        if(!isset($_POST['reference'])){
            $_POST['reference'] = $ub_header['reference'];
        }

        if(!isset($_POST['date'])){
            $_POST['date'] = sql2date($ub_header['date']);
        }
        
        if(!isset($_POST['supplier_id'])){
            $_POST['supplier_id'] = $ub_header['supplier_id'];
        }

        if(!isset($_POST['rate_include_taxes'])){
            $_POST['rate_include_taxes'] = $ub_header['rate_include_taxes'];
        }
        
        if(!isset($_POST['tax_group_id'])){
            $_POST['tax_group_id'] = $ub_header['tax_group_id'];
        }
        
        if(!isset($_POST['project_description'])){
            $_POST['project_description'] = $ub_header['project_description'];
        }
        
        if(!isset($_POST['approval_status'])){
            $_POST['approval_status'] = $ub_header['approval_status'];
        }
    
    }
    else{
        $_POST['reference'] = $Refs->get_next(ST_UTILITY_BILL_CREDIT_NOTE);      
        $_POST['approval_status'] = 0;
    }
        
    start_outer_table(TABLESTYLE2, "width=50%"); // outer table
    start_table(TABLESTYLE2);  
        table_section(1, "35%");
        echo "<td>";
        start_table(TABLESTYLE2); 
            text_row("Reference:", 'reference', null, null, null);  

            if($ubcn_no > 0){
                label_row("Project:", $_POST['project_description']);   
                hidden('project_id', $_POST['project_id']);
            }else{
                project_list_row(_("Project:"), 'project_id', null, _('Select a project'), true); 
            }

            $project = get_project($_POST['project_id']);

            $_POST['customer_name'] = $project['customer_name']; 
            $_POST['customer_id'] = $project['customer_id']; 

            supplier_list_row("Supplier:", 'supplier_id', null, 'Select a Supplier', true);

            date_row("Date", 'date');
        
            if(list_updated('supplier_id')){
                unset($_POST['rate_include_taxes']);
                unset($_POST['tax_group_id']);
            }

            $sup_details = get_supplier($_POST['supplier_id']);

            if(!(isset($_POST['rate_include_taxes']))){            
                $_POST['rate_include_taxes'] = $sup_details['tax_included'];  
            }

            yesno_list_row("Rate Include Taxes:", 'rate_include_taxes', null, "Yes", "No", false);

            if(!(isset($_POST['tax_group_id']) && $_POST['tax_group_id'] > 0)){            
                $_POST['tax_group_id'] = $sup_details['tax_group_id'];   
            }

            tax_groups_list_row("Tax Group:", 'tax_group_id', null, 'Select a Tax Group', true);

            $s = get_project_trans_view_str(ST_APPROVAL_LOG, $ubcn_no."&source_type_id=".ST_UTILITY_BILL_CREDIT_NOTE, "Approval Status");
            label_row($s,$approval_statuses[$_POST['approval_status']]);
     
        end_table(1);
        echo "</td>";
        
        start_row();
        if($ubcn_no > 0){
            echo "<td>";
            br();
            start_table(TABLESTYLE_NOBORDER);
            submit_center_first('Save_Utility_Bill_CN_Header', _("Save"), '', 'default');
            end_table();
            echo "</td>";
        }
    end_row();
    end_row();
        if($ubcn_no > 0){
            table_section(3, "35%");
                display_tax_edit_controls($ubcn_no);
                submit_center_first('Save_Tax', _("Save Taxes"), '', 'default');
        }
    end_table(1);

    end_outer_table(1); // outer table
    hidden('UBCN_No', $ubcn_no);
 
}


function display_selected_tax_types($ubcn_no, $tax_group_id)
{
    $taxes_total = $staxes_total = 0;
    
    $tax_types_array = get_tax_group_items_as_array($tax_group_id);
    foreach ($tax_types_array as $tax_type) {
        if($tax_type['rate'] > 0){
            $tax_amount = get_utility_bill_cn_tax_type_amount($ubcn_no, $tax_type['tax_type_id']);
            $_POST['manual_tax_value_'.$tax_type['tax_type_id']] = $tax_amount;
            amount_row($tax_type['tax_type_name'], 'manual_tax_value_'.$tax_type['tax_type_id']);  
            
            if ($tax_type['suspended'] == 0) {
                $taxes_total += $tax_amount;
            } else {
                $staxes_total += $tax_amount;
            }
        }
        else{
            $tax_amount = 0;
        }
    }
    
    return array("taxes"=>$taxes_total, "staxes"=>$staxes_total);
}


function display_utility_bill_cn_details($ubcn_no, $selected_id, &$Mode)
{  
    global $project_invoice_line_types, $expense_categories;    
          
    $result = get_utility_bill_cn_details($ubcn_no);  
    
                              
    start_table(TABLESTYLE, "width=98%");
    $th = array(_('Bill No.'),_('Bill Ref.'), _('Description'),
                _('Period From'),_('Period To'), _('Amount'), _('Expense Category'), _('Expense Item'),
                _('Budget'), ('Expense Type'), ('Job'), "", "");              

    table_header($th);
    $k = $total_ub = 0; //row colour counter
  
    //$_POST['amount_total'] = 0;    
    while ($myrow = db_fetch($result))
    {
        if($selected_id != $myrow["id"]){
            alt_table_row_color($k);

            label_cell($myrow["bill_no"]);
            label_cell($myrow["bill_reference"]);
            label_cell(nl2br($myrow["description"]));

            label_cell(sql2date($myrow["period_from"]), "align=center");
            label_cell(sql2date($myrow["period_to"]), "align=center");
            label_cell(number_format($myrow["amount"], 2), "align=right");
            
            if($myrow["expense_category_id"] > 0){
                label_cell($expense_categories[$myrow["expense_category_id"]]);
            }
            else{
                label_cell('');
            }
            
            $expense_item_name = '';
            switch ($myrow['expense_category_id']) {
                case EC_PETTY_CASH_EXPENSE:
                    $expense_item_name = '';
                    break;
                case EC_STOCK_ITEM_RECEIPT:
                    $link = get_petty_cash_item_receive_str(ST_I_OWE_YOU_BATCH, $batch_no, $myrow["id"], "Receive items");
                    $expense_item_name = $link;
                    break;
                case EC_VEHICLE_MAINTENANCE:
                    $expense_item_name = get_vehicle_formatted_name($myrow["expense_item_id"]);
                    break;
                case EC_UTILITY_ITEM:
                    $utility_item = get_listvalue_by_id($myrow["expense_item_id"]);
                    $expense_item_name = $utility_item['value_name'];
                    break;
                case EC_ASSET_MAINTENANCE:
                    $expense_item_name = get_asset_formatted_name($myrow["expense_item_id"]);
                    break;

                default:
                    break;
            }

            label_cell($expense_item_name);                  
            
            label_cell($myrow["budget_description"]);
            label_cell($myrow["expense_type"]);
            label_cell($myrow["project_site_description"]);

           // $_POST['amount_total'] += $myrow["amount"];

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

            end_row();        

            $total_ub += $myrow["amount"];
        }
        else{
                display_utility_bill_cn_edit_controls($selected_id, $Mode);
        }
        
    }
    
    if(!($selected_id > 0)){
        display_utility_bill_cn_edit_controls($selected_id, $Mode);
    }
    
    start_row();
    label_cell("Total", "align=right colspan=5");
    label_cell("<b>".number_format($total_ub, 2)."</b>", "align=right");
    end_row();
    
    end_table();
      
}

function display_utility_bill_cn_edit_controls($selected_id, &$Mode)
{
    global $expense_categories;
    
    echo "<td colspan=11>";
    
    if ($Mode =='Edit')   
    {
        $myrow = get_utility_bill_cn_line($selected_id); 

        $_POST['bill_no'] = $myrow['bill_no'];
        $_POST['bill_reference'] = $myrow["bill_reference"];    
        $_POST['description'] = $myrow["description"];
        $_POST['amount'] = $myrow["amount"];    
        $_POST['period_from'] = sql2date($myrow["period_from"]);  
        $_POST['period_to'] = sql2date($myrow["period_to"]); 
        $_POST['task_id'] = $myrow["task_id"]; 
        if($_POST['task_id'] > 0){
            $task = get_task_record($_POST['task_id']);
            if(isset($task['task_group_id']) && $task['task_group_id'] > 0){
                $task_group = get_task_group_details($task['task_group_id']);
                $_POST['task_boq_group_id'] = $task_group['boq_group_id'];
            }    
        }  

        $_POST['expense_type_id'] = $myrow["expense_type_id"]; 
        $_POST['expense_category_id'] = $myrow["expense_category_id"]; 
        $_POST['expense_item_id'] = $myrow["expense_item_id"];
        $_POST['project_site_id'] = $myrow["project_site_id"];  
       
    }
    else{
   
    }

    hidden('selected_id', $selected_id );
    br();

    div_start('billing_items');
//    start_table(TABLESTYLE2);
    start_outer_table(TABLESTYLE2, "width=80%");
    table_section(1);    
        text_row("Bill No:", 'bill_no', null, null, null);
        text_row("Bill Reference:", 'bill_reference', null, null, null);
        textarea_row("Description:", 'description', null, 30, 2);
        
    table_section(2);       
        date_row("Period From:", 'period_from');
        date_row("Period To:", 'period_to');
        amount_row("Amount:", 'amount');
    
    table_section(3); 
        $available_expense_categories = $expense_categories; 
//        unset($available_expense_categories[EC_ASSET_MAINTENANCE]); 
        unset($available_expense_categories[EC_STOCK_ITEM_RECEIPT]); 

        custom_values_list_row("Expense Category:", "expense_category_id", $available_expense_categories, null, "Select Expense Category", true);
    
        switch ($_POST['expense_category_id']) {
            case EC_PETTY_CASH_EXPENSE:
                hidden('expense_item_id', 0);
                break;
            case EC_STOCK_ITEM_RECEIPT:
                label_row('','(Save this record first and then open the items receiving screen)');
                hidden('expense_item_id', 0);
                break;
            case EC_VEHICLE_MAINTENANCE:
                vehicles_list_row("Vehicle", 'expense_item_id', null, '');
                break;
            case EC_UTILITY_ITEM:
                value_list_row("Utility Item", 'expense_item_id', "UTILITY_ITEMS", null, '');
                break;
            case EC_ASSET_MAINTENANCE:
                start_row();
                label_cell('Issuing Tool'); 
                echo "<td>";
                    echo asset_list('expense_item_id', null, false, true);
                echo "</td>";   
                break;

            default:
                break;
        }
        project_boq_item_groups_list_row("BOQ Item Group:", "task_boq_group_id", $_POST['project_id'], null, "No BOQ Item Group", true);
        group_tasks_list_row("Budget :", 'task_id', $_POST['project_id'], $_POST['task_boq_group_id'], null, _('Select a budget')); 
        utility_expense_types_list_row("Expense Type:", 'expense_type_id', null, 'Select an Expense Type', false);
        
        project_sites_list_row("Job:", 'project_site_id', $_POST['project_id'], null,'');

    end_outer_table(1);
    div_end();
    
    echo "</td>";

    if ($selected_id > 0)	{
            button_cell('Utility_bills_CN_Item', _("Update"), _('Confirm changes'), ICON_UPDATE);
            button_cell('cancel', _("Cancel"), _('Cancel changes'), ICON_CANCEL);
            hidden('LineNo', $selected_id);
            set_focus('qty');
    }
    else
    {
            submit_cells('Add_Utility_bills_CN_Item', _("Add Item"), "colspan=2 align=center", _('Add new item to document'), true);
    }
}

function can_release_ub_cn($ubcn_no)
{
    $line_count = get_utility_bill_cn_line_count($ubcn_no);
    if (!($line_count > 0))
    {
        display_error("There are no utiity bill credit notes entered. Can not release this document.");
        return false;
    }
    
    return true;
}


function can_process_tax($tax_group_id)
{
    $tax_types_array = get_tax_group_items_as_array($tax_group_id);
     
    foreach ($tax_types_array as $tax_type){
       
//        if($tax_type['tax_type_id'] == 1 || $tax_type['tax_type_id'] == 2){
        $postname = 'manual_tax_value_'.$tax_type['tax_type_id'];
        if(isset($_POST[$postname])){
           if(!(check_num($postname, 0.00000001))){
                $message = "Entered tax rate should be greater than zero.";
                $set_focus = 'manual_tax_value_'.$tax_type['tax_type_id'];
                return array("success" => false, "focus_to" => $set_focus, "message" => $message);
            }
        }
    }
    
    return array("success" => true, "focus_to" => '', "message" => '');
}

function display_tax_edit_controls($ubcn_no)
{
    start_table(TABLESTYLE, "width=100%");
    $th = array(_('Tax Type'),_('Amount'));              

    table_header($th);
    $k = $total_ub = 0; //row colour counter
    
    $ub_header = get_utility_bill_cn_header($ubcn_no);
            
    label_row("Lines Total:", $ub_header['total']);
          //  amount_row("Total Amount:", 'tax_amount');   
//    $project = get_project($_POST['project_id']);
              
    $all_taxes = display_selected_tax_types($ubcn_no, get_post('tax_group_id')); 
    
    label_row("Taxes Total:", number_format($all_taxes["taxes"], 2));
    label_row("Suspended Taxes Total:", number_format($all_taxes["staxes"], 2));
        
        $ubcn_total = $ub_header['total'] + $all_taxes["taxes"];
           
    label_row("Credit Note Total:", text_bold(number_format($ubcn_total, 2)));
    
    end_table(1);
}

function save_utility_bill_cn_taxes($ubcn_no){
    
    $tax_msg = can_process_tax($_POST['tax_group_id']);
    if($tax_msg["success"] !== true) 
    {          
        if(isset($tax_msg["focus_to"])){
            set_focus($tax_msg["focus_to"]);
        }
        return array("success" => false, "message" => $tax_msg["message"]);
    }
    
    $ub_lines_total = get_ub_cn_lines_total($ubcn_no);
    $taxes_array = calculate_common_item_taxes($ub_lines_total, $_POST['tax_group_id'], $_POST['rate_include_taxes']);    
    
//    $tax_types_array = get_tax_group_items_as_array($_POST['tax_group_id']);
              
    foreach ($taxes_array as &$tax_type){
        $postname = 'manual_tax_value_'.$tax_type['tax_type_id'];
//        if($tax_type['tax_type_id'] == 1 || $tax_type['tax_type_id'] == 2){
        if(isset($_POST[$postname]) && $_POST[$postname] > 0){

            $tax_value = input_num($postname);
            $tax_type['Value'] = $tax_value;          
        }       
//        }    
    }  

    begin_transaction();
    update_utility_bill_cn_taxes_manual($ubcn_no, $taxes_array);
    commit_transaction();
    
    return array("success" => true, "message" => "Taxes have been updated.");
    
}


function release_ub_cn_for_approval($ubcn_no)
{    
    if(!can_release_ub_cn($ubcn_no)){
        return;
    }
    
    $msg = can_process_ub_cn_header($ubcn_no);
    if($msg['success'] !== true){
        display_error($msg['message']);
        return $msg;
    }
    
    $ubcnh = get_utility_bill_cn_header($ubcn_no);
    
    begin_transaction();
    
    update_utility_bill_cn_header($ubcn_no, $_POST['reference'], $ubcnh['project_id'], 
                                    $_POST['supplier_id'], $_POST['date'], 
                                    $_POST['rate_include_taxes'], $_POST['tax_group_id']);
    
    
    $rub_msg = release_utility_bill_cn($ubcn_no);
    if($rub_msg['success'] !== true){
        cancel_transaction();
        display_error($rub_msg['message']);
        return;
    }

    commit_transaction();
    clear_session_variable("ST_UTILITY_BILL_CREDIT_NOTE_ubcn_no");
    set_session_variable('ST_UTILITY_BILL_CREDIT_NOTE_messages', $rub_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_UBCN_No=$ubcn_no");
    
}

function send_ub_cn_back_to_originator($ubcn_no)
{        
    begin_transaction();
     
    $ubh = get_utility_bill_cn_header($ubcn_no);

    $current_user_id = $_SESSION['wa_current_user']->user;

    $sbdo_msg = send_back_to_document_originator(ST_UTILITY_BILL_CREDIT_NOTE, $ubcn_no, $ubh['project_id'],
                                    $ubh['next_approval_group_id'], $current_user_id, $ubh['row_state'], 
                                    $ubh['created_by']);
    
    if($sbdo_msg['success'] !== true){
        display_error_cancel($sbdo_msg['message']);
        return;
    }

    commit_transaction();
    clear_session_variable("ST_UTILITY_BILL_CREDIT_NOTE_ubcn_no");
    set_session_variable('ST_UTILITY_BILL_CREDIT_NOTE_messages', $sbdo_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_UBCN_No=$ubcn_no");
        
}


function reject_ub_cn($ubcn_no)
{
    begin_transaction();
    $ubh = get_utility_bill_cn_header($ubcn_no);

    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rj_msg = reject_document(ST_UTILITY_BILL_CREDIT_NOTE, $ubcn_no, $ubh['project_id'],
                    $ubh['next_approval_group_id'], $current_user_id, $ubh['row_state']);
    
    if($rj_msg['success'] !== true){
        display_error_cancel($rj_msg['message']);
        return;
    }

    commit_transaction();
    clear_session_variable("ST_UTILITY_BILL_CREDIT_NOTE_ubcn_no");
    set_session_variable('ST_UTILITY_BILL_CREDIT_NOTE_messages', $rj_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_UBCN_No=$ubcn_no");
    
}
