<?php


function can_delete_utility_bill_item($ub_no, &$selected_id)
{
    $ubh = get_utility_bill_header($ub_no);
    $current_user_id = $_SESSION['wa_current_user']->user;
    $ced_msg = can_edit_document(ST_UTILITY_BILLS, $ubh['project_id'], $ubh['next_approval_group_id'] , $current_user_id, $ubh['created_by'], $ub_no);
        if($ced_msg['success'] !== true){
            display_error($ced_msg['message']);
            $selected_id = -1;
            return false;
        }

    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 Utility Bill status does not allow further updating.");
        display_error($message);
        $selected_id = -1;
        return false;
    }
    
    $line_count = get_utility_bill_line_count($ub_no);
    if($line_count == 1){
        $message = "This is the last line. It can not be deleted.";
        display_error($message);
        $selected_id = -1;
        return false;
    }
    
    return true;

}

function can_process_ub_header($ub_no)
{
    global $Refs;
    
    if (! ($_POST['entry_type_id'] > 0)) {
        return array("success" => false, "focus_to" => 'entry_type_id', "message" => "Please select an entry type.");   
    }
    
    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_BILLS, $ub_no);
    if($ref_msg){
        $message = $ref_msg;
        $set_focus = 'reference';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);   
    }
    
    if($ub_no > 0){
        $ubh = get_utility_bill_header($ub_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 Utility Bill status does not allow further updating.");
            return array("success" => false, "focus_to" => '', "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(!($_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(!is_date($_POST['due_date']))
    {
        $message = "Due date entered is not a valid date.";
        $set_focus = 'due_date';
        return array("success" => false, "focus_to" => $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);         
    }
    
        if($ub_no > 0){        
            $current_user_id = $_SESSION['wa_current_user']->user;
            $ced_msg = can_edit_document(ST_UTILITY_BILLS, $ubh['project_id'], $ubh['next_approval_group_id'] , $current_user_id, $ubh['created_by'], $ub_no);
            if($ced_msg['success'] !== true){
                return array("success" => false, "focus_to" => '', "message" => $ced_msg['message']);
        }
    }
      
    return array("success" => true, "message" => "");    
}

 
function can_process_ub_line($ub_no) {
    if (! ($_POST['item_type'] > 0)) {
        return array("success" => false, "focus_to" => "item_type", "message" => "Please select an item type.");  
    }
    
    if (in_array($_POST['item_type'], array(NSIT_NON_STOCK_ITEM, NSIT_STOCK_ITEM))) {
        if (! (strlen($_POST['stock_id']) > 0)) {
            return array("success" => false, "focus_to" => "stock_id", "message" => "Please select an item.");  
        }

        if ($_POST['tran_unit'] == -1) {
            return array("success" => false, "focus_to" => "tran_unit", "message" => "Please select a unit.");  
        }
    } elseif ($_POST['item_type'] == NSIT_COMMENT) {
        if (! (strlen($_POST['item_description']) > 0)) {
            return array("success" => false, "focus_to" => "item_description", "message" => "Item description cannot be empty.");  
        }
    }
    
    $item = get_stock_item_edit_info($_POST['stock_id']);
        if ($_POST['item_type'] == NSIT_NON_STOCK_ITEM){
            if (! ($item['mb_flag'] == "D")) {
                return array("success" => false, "focus_to" => "stock_id", "message" => "Selected item is a stock item, Please select a non-stock item.");  
            } 
        } elseif ($_POST['item_type'] == NSIT_STOCK_ITEM){
            if (! in_array($item['mb_flag'], array("B", "M"))) {
                return array("success" => false, "focus_to" => "stock_id", "message" => "Selected item is not a stock item, Please select a stock item.");  
            } 
        }
    
    if (! (input_num('tran_qty') > 0)) {
        return array("success" => false, "focus_to" => "tran_qty", "message" => "Quantity should be greater than zero.");  
    }
    
    if (! (input_num('tran_unit_price') > 0)) {
        return array("success" => false, "focus_to" => "tran_unit_price", "message" => "Unit price should be greater than zero.");  
    }
    
    if ($_POST['item_type'] != NSIT_COMMENT) {
        if (!(strlen($_POST['loc_code']) > 2)) {
            return array("success" => false, "focus_to" => 'loc_code', "message" => "Please select a location.");
        }
    }
    
    
    if(!($_POST['task_id'] > 0))
    {
        $message = "Please select a Budget.";
        $set_focus = 'task_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
    }
    
    if(!($_POST['expense_category_id'] > 0))
    {
        $message = ( _("Please select an expense category."));
        $set_focus = ('expense_category_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 (isset($_POST['expense_category_id']) &&  $_POST['expense_category_id'] == EC_ASSET_MAINTENANCE) {
            $asset_row = get_asset($_POST['expense_item_id']);
            if ($asset_row['type'] == AT_VEHICLE) {
                $message = "Selected asset is a Vehicle. Only the assets of types Fixed Asset and Tool are allowed under this Expense Category.";
                $set_focus = 'linked_field_id';
                return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
            }
    }
    
    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_header(&$ub_no) {     
    $success = write_utility_bill_header($ub_no, $_POST['reference'], $_POST['project_id'], $_POST['supplier_id'], $_POST['date'], $_POST['rate_include_taxes'],
                                         $_POST['tax_group_id'], $_POST['due_date'], $_POST['entry_type_id']);   
    
        if ($success === true){
            set_session_variable("ST_UTILITY_BILLS_ub_no", $ub_no);
            return array("success" => true, 'trans_no' => $ub_no, "message" => "Utility bill header information have been saved.");
        } else {
            return array("success" => false, 'trans_no' => '', "message" => "Could not save Utility bills header.");
        }
}

function save_utility_bill_detail(&$ub_no, $selected_id) {
    $date = sql2date(INFINITE_START_DATE);
    
    $conversion_factor = 1;
    
    $tran_unit = $_POST['tran_unit'];
    
    if ($tran_unit == 0) {
        $tran_unit = '';
    }    
    
    if (in_array($_POST['item_type'], array(NSIT_STOCK_ITEM, NSIT_NON_STOCK_ITEM))) {
        get_convertion_factor2($_POST['stock_id'], $tran_unit, $conversion_factor);
    }
    
    if (['item_type'] == NSIT_COMMENT) { 
        $_POST['loc_code'] == "";
    }
    
    $tran_unit_price = input_num('tran_unit_price');
    $tran_qty = input_num('tran_qty');
    $qty = $tran_qty * $conversion_factor;
    $line_cost = $tran_unit_price * $tran_qty;
    
    return write_utility_bill_detail($ub_no, $selected_id, $_POST['stock_id'], $_POST['bill_reference'], $_POST['item_description'], $line_cost, $date, $date, 
                                     $_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'], $_POST['item_type'], $tran_unit, $tran_qty, $conversion_factor, $qty, 
                                     $tran_unit_price, $_POST['loc_code']);
    
}


function save_utility_bills(&$ub_no, $selected_id)
{
    $temp_ub_no = $ub_no;
    
    $h_msg = can_process_ub_header($ub_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_line($ub_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_header($ub_no);
            if($msg["success"] !== true){
                cancel_transaction();
                return array("success" => false, 'trans_no' => $ub_no, "message" => $msg["message"]);
            }

        $msg = save_utility_bill_detail($ub_no, $selected_id);
            if($msg["success"] !== true){
                cancel_transaction();
                return array("success" => false, 'trans_no' => $ub_no, "message" => $msg["message"]);
            }

    commit_transaction();
    
        if($temp_ub_no > 0){
            return array("success" => true, 'trans_no' => $ub_no, "message" => $msg["message"]);
        }
        else{
            return array("success" => true, 'trans_no' => $ub_no, "message" => "Utility Bill $ub_no has been created.");
        }
}

function display_utility_bill_header($ub_no)
{
    global $approval_statuses, $Refs;
    
    if($ub_no > 0){
        $ub_header = get_utility_bill_header($ub_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['entry_type_id'])) {
            $_POST['entry_type_id'] = $ub_header['entry_type_id'];
        }
        
        if(!isset($_POST['reference'])){
            $_POST['reference'] = $ub_header['reference'];
        }

        if(!isset($_POST['date'])){
            $_POST['date'] = sql2date($ub_header['date']);
        }
        
        if(!isset($_POST['due_date'])){
            $_POST['due_date'] = sql2date($ub_header['due_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_BILLS);      
        $_POST['approval_status'] = 0;
    }
        
    start_outer_table(TABLESTYLE2, "width=50%"); // outer table
    start_table(TABLESTYLE2);  
        table_section(1, "35%");
        echo "<td>";
            start_table(TABLESTYLE2);  

                if($ub_no > 0){
                    label_row(text_bold("Bill No.:"), text_bold($ub_no));
                    hidden('project_id', $_POST['project_id']);
                }
                value_list_row('Entry Type:', 'entry_type_id', 'UTILITY_BILL_ENTRY_TYPES', null, '', true);
                text_row("Reference:", 'reference', null, null, null);  

                if($ub_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']);
                if (isset($project['project_id']) && $project['project_id'] > 0) {
                    $_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');
                date_row("Due Date:", 'due_date');

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

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

                if (isset($sup_details['tax_group_id']) && $sup_details['tax_group_id'] > 0) {
                    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, $ub_no."&source_type_id=".ST_UTILITY_BILLS, "Approval Status");
                label_row($s,$approval_statuses[$_POST['approval_status']]);

        if($ub_no > 0){
            end_table(0);
        }

    echo "</td>";
    
    if (! ($ub_no > 0)) {
        end_outer_table(1); // outer table
    }
    
    start_row();
        if($ub_no > 0){
            echo "<td>";
            br();
            start_table(TABLESTYLE_NOBORDER);
                submit_center_first('Save_Utility_Bill_Header', _("Save"), '', 'default');
            end_table();
            echo "</td>";
        }
    end_row();
        if($ub_no > 0){
            table_section(3, "35%");
                display_tax_edit_controls($ub_no);
                submit_center_first('Save_Tax', _("Save Taxes"), '', 'default');
        }
    end_table(1);
//    end_outer_table(1); // outer table
    hidden('UBNo', $ub_no);
 
    
}

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

    table_header($th);
        $k = $total_ub = 0; //row colour counter

        $ub_header = get_utility_bill_header($ub_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($ub_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));
        
        $ub_total = $ub_header['total'] + $all_taxes["taxes"];
        
        label_row("Bill Total:", text_bold(number_format($ub_total, 2)));
    
    end_table(1);
}

function display_selected_tax_types($ub_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_tax_type_amount($ub_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']);   
        }
        else{
            $tax_amount = 0;
        }
        
        if($tax_type['suspended'] == 1){
            $staxes_total += $tax_amount;
        }
        else{
            $taxes_total += $tax_amount;
        }
    }
    
    return array("taxes"=>$taxes_total, "staxes"=>$staxes_total);
}


function display_utility_bill_details($ub_no, $selected_id, &$Mode)
{  
    global $daily_item_types_array, $expense_categories;    
          
    $result = get_utility_bill_details($ub_no);  
    
                              
    start_table(TABLESTYLE, "width=99%");
    $th = array(_('Line #'), _('Bill Ref.'), _('Item Type'), _('Item'), _('Unit'), _('Quantity'), _('Unit Price'), _('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["id"], "align=center");
                label_cell($myrow["bill_reference"]);
                label_cell($daily_item_types_array[$myrow["item_type"]]);
                if (in_array($myrow["item_type"], array(NSIT_STOCK_ITEM, NSIT_NON_STOCK_ITEM))) {
                    label_cell($myrow["bill_no"].' - '.$myrow["description"]);
                } else {
                    label_cell(nl2br($myrow["description"]));
                }
                label_cell($myrow["unit_name"]);
                label_cell(number_format($myrow["tran_qty"], 4), "align=right");
                label_cell(number_format($myrow["tran_unit_price"], 2), "align=right");
                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_edit_controls($selected_id, $Mode);
        }
    }
    
    if(!($selected_id > 0)){
        display_utility_bill_edit_controls($selected_id, $Mode);
    }
            
    start_row();
    label_cell("Total", "align=right colspan=7");
    label_cell("<b>".number_format($total_ub, 2)."</b>", "align=right");
    end_row();
    
    end_table();
      
}

function display_utility_bill_edit_controls($selected_id, &$Mode)
{
    global $expense_categories, $daily_item_types_array;
    
    echo "<td colspan=13>";
    
    if ($Mode =='Edit')   
    {
        $myrow = get_utility_bill_line($selected_id); 

        $_POST['item_type'] = $myrow["item_type"];
        $_POST['stock_id'] = $myrow["bill_no"];
        $_POST['item_description'] = $myrow["description"];
        $_POST['tran_unit'] = $myrow["tran_unit"];
        $_POST['tran_qty'] = $myrow["tran_qty"];
        $_POST['tran_unit_price'] = $myrow["tran_unit_price"];
        $_POST['loc_code'] = $myrow["loc_code"];
        
        $_POST['bill_reference'] = $myrow["bill_reference"];    
        $_POST['task_id'] = $myrow["task_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 {
        if (! isset($_POST['item_type']) || ! ($_POST['item_type'] > 0)) {
            $_POST['item_type'] = NSIT_COMMENT;
        }
    }

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

    div_start('billing_items');
        //    start_table(TABLESTYLE2);
        start_outer_table(TABLESTYLE2, "width=80%");
            table_section(1);

                if ($selected_id > 0 && $Mode == 'Edit') {  
                    label_row('Rec Id:', $selected_id);
                    text_row("Bill Reference:", 'bill_reference', null, null, null);
                    label_row('Item Type:', $daily_item_types_array[$myrow['item_type']]);
                    $_POST['item_type'] = $myrow['item_type'];
                    hidden('item_type', $myrow['item_type']);
                } else {
                    text_row("Bill Reference:", 'bill_reference', null, null, null);
                    custom_values_list_row('Item Type:', 'item_type', $daily_item_types_array, null, '', true);
                }

                if ($_POST['item_type'] == NSIT_NON_STOCK_ITEM) {

                    if ($selected_id > 0 && $Mode == 'Edit') {  
                        label_row('Item:', $_POST['stock_id']);
                        hidden('stock_id', $_POST['stock_id']);
                        text_row_ex('Item Description:', 'item_description', 50, 250, 'Item Description');
                    } else {
                        label_row('Stock Item:', non_stock_items_list('stock_id', null, false, true));
                        $itm = get_item($_POST['stock_id']);
                            if (is_array($itm)) {
                                hidden('item_description', $itm['description']);
                            } else {
                                hidden('item_description', '');
                            }
                    }

                    units_list_row('Unit:', 'tran_unit', $_POST['stock_id'], null, '');
                    $dec = get_qty_dec($_POST["stock_id"]);

                } elseif ($_POST['item_type'] == NSIT_STOCK_ITEM) {

                    if ($selected_id > 0 && $Mode == 'Edit') {  
                        label_row('Stock Item:', $_POST['stock_id']);
                        hidden('stock_id', $_POST['stock_id']);
                        text_row_ex('Item Description:', 'item_description', 50, 250, 'Item Description');
                    } else {
                        label_row('Stock Item:', stock_and_manufacture_items_list('stock_id', null, false, true));
                        $itm = get_item($_POST['stock_id']);
                            if (is_array($itm)) {
                                hidden('item_description', $itm['description']);
                            } else {
                                hidden('item_description', '');
                            }
                    }

                    units_list_row('Unit:', 'tran_unit', $_POST['stock_id'], null, '');
                    $dec = get_qty_dec($_POST["stock_id"]);

                } elseif ($_POST['item_type'] == NSIT_COMMENT) {
                    text_row_ex('Item Description:', 'item_description', 50, 250, 'Item Description');
                    hidden('stock_id', '');

                    $units_array = build_all_item_units_array();
                    custom_values_list_row('Unit:', 'tran_unit', $units_array, null, '');
                } else {
                    hidden('stock_id', '');
                    hidden('tran_unit', '');
                    hidden('item_description', '');
                }

            table_section(3);
                $dec = 2;
                amount_row("Quantity:", 'tran_qty', null, null, null, $dec);
                amount_row("Unit Cost:", 'tran_unit_price', null, null, null, 2);
                locations_list_row("Location:", 'loc_code', null, '', false);  

            table_section(4);    
                $available_expense_categories = $expense_categories; 
                unset($available_expense_categories[EC_STOCK_ITEM_RECEIPT]); 

                custom_values_list_row("Expense Category:", "expense_category_id", $available_expense_categories, null, "", 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;
                }

            tasks_list_row("Budget:", 'task_id', $_POST['project_id'], null, '', false);
            utility_expense_types_list_row("Expense Type:", 'expense_type_id', null, '', 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_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_Item', _("Add Item"), "colspan=2 align=center", _('Add new item to document'), true);
    }

}

function can_release_ub($ub_no)
{
    $line_count = get_utility_bill_line_count($ub_no);
    if (!($line_count > 0))
    {
        display_error("There are no lines entered. Can not release this document.");
        return false;
    }
    
    return true;
}


function can_process_tax($tax_group_id, $ub_no)
{
    
    $ubh = get_utility_bill_header($ub_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 Utility Bill status does not allow further updating.");
        return array("success" => false, "focus_to" => '', "message" => $message);
    }
        
    $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 save_utility_bill_taxes($ub_no){
    
    $tax_msg = can_process_tax($_POST['tax_group_id'], $ub_no);
    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_lines_total($ub_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_taxes_manual($ub_no, $taxes_array);
    commit_transaction();
    
    return array("success" => true, "message" => "Taxes have been updated.");

    
}


function release_ub_for_approval($ub_no)
{    
    if(!can_release_ub($ub_no)){
        return;
    }    
            
    $h_msg = can_process_ub_header($ub_no);      
    if($h_msg["success"] !== true) 
    {          
        if(isset($h_msg["focus_to"])){
            set_focus($h_msg["focus_to"]);
        }
        display_error($h_msg["message"]);
        return;
    }
    
    begin_transaction();

        $msg = save_utility_bills_header($ub_no);
            if($msg["success"] !== true){
                cancel_transaction();
                display_error($msg["message"]);
                return;
            }

        $rub_msg = release_utility_bill($ub_no);
            if($rub_msg['success'] !== true){
                cancel_transaction();
                display_error($rub_msg['message']);
                return;
            }

    commit_transaction();
    
    clear_session_variable("ST_UTILITY_BILLS_ub_no");
    set_session_variable('ST_UTILITY_BILLS_messages', $rub_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_UB_No=$ub_no");
}

function process_utility_bill_receipt($ub_no) {
    global $Refs;
    
    $type = ST_UTILITY_BILL_STOCK_RECEIPT;
    $trans_no = 0;
    
    $reference = $Refs->get_next($type);
    $ref_msg = reference_exists($reference, $type, $trans_no);
        if ($ref_msg) {
            $reference = $Refs->get_next($type);
            $ref_msg = reference_exists($reference, $type, $trans_no);
                if ($ref_msg) {
                    cancel_transaction();
                    return array('success' => false, 'message' => $ref_msg);
                }
        }
    
    $tran_date_ = $due_date_ = Today();
    $ubh_row = get_utility_bill_header($ub_no);
        $project_id = $ubh_row['project_id']; 
    
    $hd_inst_id = add_utility_bill_stock_receipt_header($type, $reference, $project_id, $ubh_row['supplier_id'], $tran_date_, $ubh_row['rate_include_taxes'], 
                                                        $ubh_row['tax_group_id'], $due_date_, $trans_no, $ubh_row['taxes'], $ubh_row['staxes'], $ubh_row['total'], 
                                                        ST_UTILITY_BILLS, $ub_no);
        if (! ($hd_inst_id > 0)) {
            cancel_transaction();
            return array('success' => false, 'message' => 'Could not create new utility bill receipt header.');
        }                                          
    
    $result = get_utility_bill_details($ub_no);
        while ($row = db_fetch($result)) {
            $line_id = $row["id"];
            $stock_id = $row["bill_no"];
            $tran_unit_price = $row["tran_unit_price"];
            $conversion_factor = $row["conversion_factor"];
            
            $in_ln = add_utility_bill_stock_receipt_detail($type, $trans_no, $stock_id, $row['bill_reference'], $row['description'], $row['amount'], $row['period_from'], 
                                                           $row['period_to'], $row['task_id'], $row['expense_type_id'], $row['expense_category_id'], $row['expense_item_id'], 
                                                           $row['project_site_id'], $row['item_type'], $row['tran_unit'], $row['tran_qty'], $conversion_factor, $row['qty'], 
                                                           $tran_unit_price, $row['loc_code'], $line_id);
                if (! ($in_ln > 0)) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not create new utility bill receipt detail for line #$line_id");
                }
            
            $qty = abs($row["qty"]);
            $tran_qty = abs($row["tran_qty"]);

            $base_unit_price = $tran_unit_price / $conversion_factor;

                if ($row['mb_flag'] == 'B' || $row['mb_flag'] == 'M') {
                    $n = add_stock_adjustment_item($trans_no, $stock_id, $row["loc_code"], $tran_date_, $reference, $qty, $base_unit_price, '', $row["tran_unit"], $tran_qty, 
                                                   $row["conversion_factor"], $type, $row["task_id"], $row["project_site_id"], $line_id, $project_id);
                } else {
                    $n = add_non_stock_move($type, $stock_id, $trans_no, $row["loc_code"], $tran_date_, $reference, $qty, $base_unit_price, 0, 1, $row["amount"], 0, 
                                            $row["tran_unit"], $tran_qty, $row["conversion_factor"], $row["task_id"], $row["project_site_id"], $line_id, $row["description"], 
                                            $project_id);
                }

                if (! ($n > 0)) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not create the stock movement record against line #$line_id");
                }
        }

        return array("success" => true, 'trans_no' => $trans_no, "message" => "");            
}

function send_ub_back_to_originator($ub_no)
{        
    begin_transaction();
     
    $ubh = get_utility_bill_header($ub_no);

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

    $sbdo_msg = send_back_to_document_originator(ST_UTILITY_BILLS, $ub_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_BILLS_ub_no");
    set_session_variable('ST_UTILITY_BILLS_messages', $sbdo_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_UB_No=$ub_no");
        
}


function reject_ub($ub_no)
{
    begin_transaction();
    $ubh = get_utility_bill_header($ub_no);

    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rj_msg = reject_document(ST_UTILITY_BILLS, $ub_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_BILLS_ub_no");
    set_session_variable('ST_UTILITY_BILLS_messages', $rj_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_UB_No=$ub_no");
    

}