<?php

function display_budget_to_budget_transfer_header($bbt_no) {
    global $Refs, $systypes_array;
    
    $type = ST_BUDGET_TO_BUDGET_TRANSFER;
    
    display_heading($systypes_array[$type]." Header");
    
        $trans_no = 0;
        $header = get_budget_to_budget_transfer_header($bbt_no);
            if (is_array($header)) {
                $user_id = $_SESSION['wa_current_user']->user;
                $cap = can_access_project($header['project_id'], $user_id);
                    if ($cap['success'] !== true) {
                        display_error($cap["message"]);
                        set_focus('project_id');
                        display_footer_exit();
                        exit;
                    } 
                
                $_POST['to_jo_id'] = $header['to_jo_id']; hidden('to_jo_id', $header['to_jo_id']);
                $_POST['project_id'] = $header['project_id']; hidden('project_id', $header['project_id']);

                $trans_no = $header['trans_no'];

                if (! isset($_POST['reference'])) {
                    $_POST['reference'] = $header['reference'];
                }
                if (! isset($_POST['comments'])){
                    $_POST['comments'] = $header['comments'];
                }        
                if (! isset($_POST['to_loc_code'])) {
                    $_POST['to_loc_code'] = $header['to_loc_code'];
                }
                if (! isset($_POST['from_loc_code'])) {
                    $_POST['from_loc_code'] = $header['from_loc_code'];
                }
                if (! isset($_POST['tran_date'])) {
                    $_POST['tran_date'] = sql2date($header['tran_date']);
                }
                if (! isset($_POST['to_task_id'])) {
                    $_POST['to_task_id'] = $header['to_task_id'];
                }
                if (! isset($_POST['project_description'])) {
                    $_POST['project_description'] = $header['project_description'];
                }
                if (! isset($_POST['approval_status'])) {
                    $_POST['approval_status'] = $header['approval_status'];
                }
            } else {
                $_POST['reference'] = $Refs->get_next($type);            
                $_POST['approval_status'] = 0;
            }
        
        div_start('nsit_header');
  
            start_outer_table(TABLESTYLE2, "width=65%"); // outer table
                start_table(TABLESTYLE2);  
                    table_section(1, "50%");

                        if (is_array($header)) {
                            label_row("Trans #:", get_trans_view_str($type, $header['trans_no']));  
                            $to_jo_id = $header['to_jo_id'];
                            label_row("To Job Card:", get_service_trans_view_str(ST_JOB_ORDER, $to_jo_id));  
                            
                            $reference = $header['reference'];            
                            text_row("Reference:", 'reference', $reference, null, null);            
                        } else {            
                            amount_cells('To Job Card #:', 'to_jo_id', null, null, null, 0);
                            text_row("Reference:", 'reference', $Refs->get_next($type), null, null);   
                        }
                        
                        if ($bbt_no > 0) {
                            label_row("Project:", $_POST['project_description']);   
                        } else {
                            project_list_row(_("Project:"), 'project_id', null, _('Select a project'), true);                         
                        } 

                    table_section(2, "50%");
                    
                        date_row("Date:", "tran_date");
                        
                        if (is_array($header)) {
                            label_row("From Location:", $header['from_location_name']); 
                            hidden('from_loc_code', $_POST['from_loc_code']);
                        } else {
                            locations_list_row("From Location:", 'from_loc_code', null, '', false); 
                        }
                        
                        if (is_array($header)) {
                            label_row("To Location:", $header['to_location_name']); 
                            hidden('to_loc_code', $_POST['to_loc_code']);
                        } else {
                            locations_list_row("To Location:", 'to_loc_code', null, '', false); 
                        }
                        
                        if (is_array($header)) {
                            label_row("To Budget:", $header['to_task_description']); 
                            hidden('to_task_id', $_POST['to_task_id']);
                        } else {
                            all_budgets_list_row('To Budget:', 'to_task_id', GLOBAL_VOTES, null, _(''));
                        }
                        
                        textarea_row("Comment:", 'comments', null, 35, 2); 

                        global $approval_statuses;
                        $s = get_project_trans_view_str(ST_APPROVAL_LOG, $trans_no."&source_type_id=".$type, "Approval Status");
                        label_row($s, $approval_statuses[$_POST['approval_status']]);

            end_outer_table(2); // outer table
    
        div_end();
}

function display_budget_to_budget_transfer_details($bbt_no, $to_jo_id, $from_loc_code, &$Mode, &$selected_id) { 
    global $Ajax, $daily_item_types_array, $systypes_array;
    
    $type = ST_BUDGET_TO_BUDGET_TRANSFER;
    display_heading($systypes_array[$type]." Details");
    
    $trans_no = 0;
    $hd_row = get_budget_to_budget_transfer_header_record($bbt_no);
        if (is_array($hd_row)) {
            $trans_no = $hd_row['trans_no'];
        } 
        
    $Ajax->activate('btbt_details');
    div_start('btbt_details');
    
        start_table(TABLESTYLE, "width=99%");

            $th = array(_("Id"), _("Item Type"), _("Item"), _("From Job"), _("From Budget"), _('Base Qty'), _('Tran Unit'), _('Tran Qty'), _('Cost'), _('Site'), 
                        _('Line Comment'), _(""), _(""), _(""));  
                
            table_header($th);

            $k = 0; 
                $result = get_budget_to_budget_transfer_details($trans_no, $type);      
                    while ($row = db_fetch($result)) {
                        $id = $row['trans_id'];
                        
                        if ($selected_id != $id || $Mode == 'Delete') {
                            alt_table_row_color($k);

                                label_cell(text_bold($id), 'align=center');
                                label_cell($daily_item_types_array[$row['item_type']]);
                                if ($row['item_type'] == NSIT_NON_STOCK_ITEM || $row['item_type'] == NSIT_STOCK_ITEM) {
                                    label_cell($row["stock_id"]." - ".$row["item_description"]);  
                                } else {
                                    label_cell($row["item_description"]);
                                }
                                $from_jo_id = $row["from_jo_id"];
                                label_cell(get_service_trans_view_str(ST_JOB_ORDER, $from_jo_id), 'align=center');
                                label_cell($row["from_task_description"]);
                                $dec = 4; // get_qty_dec($row["stock_id"]);
                                qty_cell($row["qty"], true, $dec);
                                label_cell($row["unit_name"]);
                                qty_cell($row["tran_qty"], true, $dec);
                                qty_cell($row["standard_cost"], false, 2);

                                label_cell($row["site_description"]);          
                                label_cell(nl2br($row["line_comment"])); 

                                if ($row['stock_control_method'] == SKCM_LOTS) {
                                    $convesion_factor = 1;
                                    get_convertion_factor2($row["stock_id"], $_POST["tran_unit_$id"], $convesion_factor);

                                    display_lot_serial_edit_cells($row['stock_control_method'], $type, $trans_no, $id, $convesion_factor, $dec);
                                } else {
                                    label_cell('');
                                }
                                
                                edit_button_cell("Edit".$row["trans_id"], _("Edit"));    
                                delete_button_cell("Delete".$row["trans_id"], _("Delete"));  

                            end_row();  
                        } else {
                            display_budget_to_budget_transfer_edit_controls($selected_id, $Mode, $to_jo_id, $from_loc_code);
                        }
                    }
                    
                    if (! ($selected_id > 0) || $Mode == 'Delete') {
                        display_budget_to_budget_transfer_edit_controls($selected_id, $Mode, $to_jo_id, $from_loc_code);
                    }

        end_table(2);
    
    div_end();
}

function display_budget_to_budget_transfer_edit_controls($selected_id, &$Mode, $to_jo_id, $from_loc_code) {
    global $Ajax, $daily_item_types_array, $systypes_array;
    
    $b2b_item_types_array = $daily_item_types_array;
    unset($b2b_item_types_array[NSIT_COMMENT]);
    
    $type = ST_BUDGET_TO_BUDGET_TRANSFER;
    $tp_name = $systypes_array[$type];
    $dec = 2;
    
    if ($selected_id > 0 && $Mode != 'Delete') {   
        $row = get_budget_to_budget_transfer_details_record($selected_id); 
            if ($Mode == 'Edit') {
                $_POST['item_type'] = $row["item_type"];
                $_POST['stock_id'] = $row["stock_id"];
                $_POST['item_description'] = $row["item_description"];
                $_POST['from_jo_id'] = $row["from_jo_id"];
                $_POST['from_task_id'] = $row["from_task_id"];
                $_POST['tran_unit'] = $row["tran_unit"];
                $_POST['tran_qty'] = $row["tran_qty"];
                $_POST['project_site_id'] = $row["project_site_id"];
                $_POST['line_comment'] = $row["line_comment"];
                $_POST['item_cost'] = $row["standard_cost"];
            }
            
            if (! (strlen($_POST['stock_id']) > 0)) {
                $_POST['stock_id'] = $row["stock_id"];
            }
            if (! ($_POST['from_jo_id'] > 0)) {
                $_POST['from_jo_id'] = $row["from_jo_id"];
            }
            if (! ($_POST['from_task_id'] > 0)) {
                $_POST['from_task_id'] = $row["from_task_id"];
            }
            if ($_POST['tran_unit'] == -1) {
                $_POST['tran_unit'] = $row["tran_unit"];
            }
            if (! (input_num('tran_qty') > 0)) {
                $_POST['tran_qty'] = $row["tran_qty"];
            }
            if (! (strlen($_POST['line_comment']) > 0)) {
                $_POST['line_comment'] = $row["line_comment"];
            }
            
        hidden('selected_id', $selected_id);
    }
  
    echo "<td colspan=11>";
        $Ajax->activate("control_items");    
        div_start('control_items');
            start_outer_table(TABLESTYLE2);
            
                table_section(1);

                    if ($selected_id > 0 && $Mode != 'Delete') {  
                        label_row('Rec Id:', $selected_id);
                        label_row('Item Type:', $b2b_item_types_array[$row['item_type']]);
                        $_POST['item_type'] = $row['item_type'];
                        hidden('item_type', $row['item_type']);
                    } else {
                        custom_values_list_row('Item Type:', 'item_type', $b2b_item_types_array, null, '', true);
                    }

                        if ($_POST['item_type'] == NSIT_STOCK_ITEM || $_POST['item_type'] == NSIT_NON_STOCK_ITEM) {
                            if ($selected_id > 0 && $Mode != 'Delete') {  
                                label_row('Item:', $_POST['stock_id']);
                                hidden('stock_id', $_POST['stock_id']);
                                text_row_ex('Item Description:', 'item_description', 50, 250, 'Item Description');
                            } else {
                                if ($_POST['item_type'] == NSIT_STOCK_ITEM) {
                                    label_row('Stock Item:', stock_and_manufacture_items_list('stock_id', null, false, true));
                                } 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', '');
                                    }
                            }
                        } elseif ($_POST['item_type'] == NSIT_COMMENT) {
                            text_row_ex('Item Description:', 'item_description', 50, 250, 'Item Description');
                            hidden('stock_id', '');
                        } else {
                            hidden('stock_id', '');
                            hidden('tran_unit', '');
                            hidden('item_description', '');
                        }

                table_section(2);
                
                    if (in_array($_POST['item_type'], array(NSIT_NON_STOCK_ITEM, NSIT_STOCK_ITEM))) {
                        $jobs_remain_array = array();
                        
                        $jobs_array = create_jobs_array_from_stock_moves_by_stock_id($_POST['item_type'], $_POST['stock_id'], $from_loc_code, $to_jo_id, $jobs_remain_array, 
                                                                                     $selected_id);
                        custom_values_list_row('From Job (Stock Moves):', 'from_jo_id', $jobs_array, null, '', true);
                        $from_jo_id = $_POST['from_jo_id'];

                        $from_tasks_array = create_budget_to_budget_transfer_job_tasks_array($_POST['item_type'], $from_jo_id, $_POST['stock_id'], $from_loc_code);
                        custom_values_list_row('From Budget:', 'from_task_id', $from_tasks_array, null, '', true);
                        if (isset($jobs_remain_array[$_POST['from_jo_id']])) {
                            $bs_name = get_item_base_unit_name($_POST['stock_id']);
                            label_row("From Job Remain Qty ($bs_name):", number_format($jobs_remain_array[$_POST['from_jo_id']], 4));
                        }
                    } else {
                        $_POST['task_id'] = 0;
                        hidden('task_id', 0);
                    }
                    
                table_section(3);
                
                    if (in_array($_POST['item_type'], array(NSIT_NON_STOCK_ITEM, NSIT_STOCK_ITEM))) {
                        units_list_row('Unit:', 'tran_unit', $_POST['stock_id'], null, '', true);
                        $dec = get_qty_dec($_POST["stock_id"]);
                        
                        if (list_updated('tran_unit') || ! isset($_POST['tran_qty'])) {
                            $convesion_factor = 1;
                            get_convertion_factor2($_POST['stock_id'], $_POST['tran_unit'], $convesion_factor);
                            if (isset($jobs_remain_array[$_POST['from_jo_id']])) {
                                $tran_qty_ = $jobs_remain_array[$_POST['from_jo_id']] / $convesion_factor;

                                $_POST['tran_qty'] = number_format($tran_qty_, 4);
                            }
                        }
                    } else {
                        $units_array = build_all_item_units_array();
                        custom_values_list_row('Unit:', 'tran_unit', $units_array, null, '');
                    }
                    amount_row("Quantity:", 'tran_qty', null, null, null, 4);
                    if ($_POST['item_type'] == NSIT_NON_STOCK_ITEM) {
                        amount_row("Item Cost:", 'item_cost', null, null, null, 0);
                    } else {
                        $_POST['item_cost'] = 0;
                        hidden('item_cost', 0);
                    }

                table_section(4);
                
                    all_project_sites_list_row("Site:", 'project_site_id', GLOBAL_VOTES, null, '', false); 
                    text_row_ex('Line Comment:', 'line_comment', 30, 400, 'Line Comment');

            end_outer_table(2);
        div_end();
    
    echo "</td>";
    
        if ($selected_id > 0 && $Mode != 'Delete') {
            button_cell('Update_BBT', _("Update"),  _("Update $tp_name"), ICON_UPDATE);
            button_cell('cancel', _("Cancel"), _("Cancel changes"), ICON_CANCEL);
            hidden('selected_id', $selected_id);

        } else {        
            button_cell('Add_BBT', _("ADD"),  _("Add $tp_name"), ICON_ADD);
            button_cell('cancel', _("Cancel"), _("Cancel changes"), ICON_CANCEL);
        }
}

function can_save_budget_to_budget_transfer_header($bbt_no, $type) {
    global $Refs, $systypes_array;
    
    $trans_no = $row_state = 0;
    $header = get_budget_to_budget_transfer_header_record($bbt_no);
        if (is_array($header)) {
            if (! in_array($header['approval_status'], array(AS_NEW, AS_WITH_THE_APPROVER, AS_AWAITING_APPROVAL, AS_BACK_TO_ORIGINATOR))) {
                return array("success" => false, "message" => $systypes_array[$type]." #$bbt_no is not allow to further updating.");
            }
            
            $trans_no = $header['trans_no']; $row_state = $header['row_state'];
        } elseif ($bbt_no > 0 && ! is_array($header)) { 
            return array("success" => false, "message" => $systypes_array[$type]." #$bbt_no has been deleted by another user.");
        } else {
            if (! (input_num('to_jo_id') > 0)) {
                return array("success" => false, "focus_to" => 'to_jo_id', "message" => "Please select to job.");
            }
        }
        
    if (! $Refs->is_valid($_POST['reference'])) {
        return array("success" => false, "focus_to" => 'reference', "message" => "Please enter a reference.");      
    } 
 
    $ref_msg = reference_exists($_POST['reference'], $type, $trans_no);
        if ($ref_msg) {
            return array("success" => false, "focus_to" => 'reference', "message" => $ref_msg);       
        }
    
    if (! ($_POST['project_id'] > 0)) {
        return array("success" => false, "focus_to" => 'project_id', "message" => "Please select a project.");
    }
      
    if (! is_date($_POST['tran_date'])) {
        return array("success" => false, "focus_to" => 'tran_date', "message" => "Date entered is not a valid date.");        
    }
      
    if ($_POST['from_loc_code'] == '') {
        return array("success" => false, "focus_to" => 'from_loc_code', "message" => "From location cannot empty.");
    }
      
    if ($_POST['to_loc_code'] == '') {
        return array("success" => false, "focus_to" => 'to_loc_code', "message" => "To location cannot empty.");
    }
    
    if (! ($_POST['to_task_id'] > 0)) {
        return array("success" => false, "focus_to" => 'to_task_id', "message" => "Please select a to task.");
    }
    
        return array("success" => true, 'row_state' => $row_state, "message" => "", 'trans_no' => $trans_no);    
}

function can_save_budget_to_budget_transfer_line($selected_id, $type, $trans_no, $from_loc_code) {
    global $daily_item_types_array, $systypes_array;
    
    $tp_name = $systypes_array[$type];
    $lt_alo_name = $systypes_array[ST_LOT_ALLOCATION];
    
    if ($selected_id > 0) {
        $line_row = get_budget_to_budget_transfer_details_record($selected_id);
            if (! is_array($line_row)) {
                return array("success" => false, "message" => "$tp_name line #$selected_id has been deleted by another user.");
            }
    }
    
        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.");  
            }
        } else {
            $stk = $daily_item_types_array[NSIT_STOCK_ITEM];
            $non_stk = $daily_item_types_array[NSIT_NON_STOCK_ITEM];
            return array("success" => false, "focus_to" => "stock_id", "message" => "Item type must either $stk or $non_stk.");  
        }
        
        $stock_id = $_POST['stock_id'];

        $item = get_stock_item_edit_info($stock_id);
            if ($_POST['item_type'] == NSIT_NON_STOCK_ITEM){
                if (! ($item['mb_flag'] == "D")) {
                    return array("success" => false, "message" => "Selected item is not non stock item, Please select a non-stock item.", 
                                 "focus_to" => "stock_id");  
                } 
                if (! (input_num('item_cost') > 0)) {
                    return array("success" => false, "message" => "Item cost must be positive value and greater than zero.", 
                                 "focus_to" => "item_cost");  
                } 
            } elseif ($_POST['item_type'] == NSIT_STOCK_ITEM){
                if (! ($item['mb_flag'] == "B" || $item['mb_flag'] == "M")) {
                    return array("success" => false, "message" => "Selected item is not a stock item, Please select a stock item.", 
                                 "focus_to" => "stock_id");  
                } 
            }

        if (! ($_POST['from_jo_id'] > 0)) {
            return array("success" => false, "focus_to" => "from_jo_id", "message" => "Please select a from job.");  
        } 
        
        if ($selected_id > 0) {
            // check already lots have been entered for from job
            $pre_from_jo_id = $line_row['from_jo_id'];
                if ($pre_from_jo_id != $_POST['from_jo_id']) {
                    $lot_recs = get_lot_allocation_records($type, $trans_no, $selected_id);
                        if (db_num_rows($lot_recs) > 0) {
                            return array("success" => false, "focus_to" => "from_jo_id", 
                                         "message" => "Please delete all $lt_alo_name related to line #$selected_id befere changing from job.");  
                        }
                }
        }

        if (! ($_POST['from_task_id'] > 0)) {
            return array("success" => false, "focus_to" => "from_task_id", "message" => "Please select a from budget.");  
        }

        if ($_POST['tran_unit'] == -1) {
            return array("success" => false, "focus_to" => "tran_unit", "message" => "Please select a tran unit.");  
        }

        if (! (input_num('tran_qty') > 0)) {
            return array("success" => false, "focus_to" => "tran_qty", "message" => "Quantity should be greater than zero.");  
        }

        $tran_qty_ = input_num('tran_qty');
        $tran_qty = number_format($tran_qty_, 4);
        
        $convesion_factor = 1;
        get_convertion_factor2($stock_id, $_POST['tran_unit'], $convesion_factor);
        
        $base_remain_qty = get_job_remain_qty_from_stock_moves_and_b_to_b_transfer($_POST['item_type'], $stock_id, $from_loc_code, $_POST['from_jo_id'], $selected_id);
        
        if ($base_remain_qty <= 0) {
            return array("success" => false, "focus_to" => "tran_qty", "message" => "No more remain qty for this line.");  
        }
        
        $remain_tran_qty_ = $base_remain_qty / $convesion_factor;
        $remain_tran_qty = number_format($remain_tran_qty_, 4);
        
            if ($tran_qty > $remain_tran_qty) {
                $exceed_trn_qty = $remain_tran_qty - $tran_qty;
                return array('success' => false, 'message' => "Remain tran qty $remain_tran_qty is exceeded by $exceed_trn_qty in tran unit.", 
                             "focus_to" => "tran_qty");
            }

        return array("success" => true, "focus_to" => "", "message" => ""); 
}

function save_budget_to_budget_transfer_header(&$bbt_no, &$trans_no, $type, $to_jo_id, $reference, $project_id, $loc_code, $to_task_id, $tran_date, $comments, $from_loc_code, 
                                               $row_state) {
    global $systypes_array;
    
    $af_no = write_budget_to_budget_transfer_header($type, $bbt_no, $trans_no, $to_jo_id, $reference, $project_id, $loc_code, $to_task_id, $comments, $tran_date, 
                                                    $from_loc_code, $row_state); 
    
        if ($af_no > 0) {
            return array("success" => true, "message" => $systypes_array[$type]." header record #$bbt_no has been saved.");
        } else {
            return array("success" => false, "message" => "Could not be saved ".$systypes_array[$type].' header.');
        }
}

function save_budget_to_budget_transfer_line($selected_id, $to_jo_id, $type, $trans_no, $from_loc_code, $to_loc_code, $to_task_id, $item_type, $stock_id, $item_description, 
                                             $from_jo_id, $from_task_id, $tran_unit, $tran_qty, $project_site_id, $line_comment, $item_cost) {    
    global $systypes_array;
    
    $standard_cost = $item_cost;
    if ($item_type == NSIT_STOCK_ITEM) {
        $standard_cost = get_standard_cost($stock_id);
    } 

    $conversion_factor = 1;
    get_convertion_factor2($stock_id, $tran_unit, $conversion_factor);

    $qty = $tran_qty * $conversion_factor;

    $id = $selected_id;
        if ($selected_id  > 0) {
            $af_rw = update_budget_to_budget_transfer_line($selected_id, $item_description, $from_jo_id, $from_task_id, $tran_unit, $tran_qty, $qty, $conversion_factor, 
                                                           $standard_cost, $project_site_id, $line_comment);
                if ($af_rw != 1) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not update ".$systypes_array[$type]." line #$selected_id.");
                } 
        } else {
            $in_id = insert_budget_to_budget_transfer_line($to_jo_id, $type, $trans_no, $to_loc_code, $to_task_id, $item_type, $stock_id, $item_description, $from_jo_id, 
                                                           $from_task_id, $tran_unit, $tran_qty, $qty, $conversion_factor, $standard_cost, $project_site_id, $line_comment, 
                                                           $from_loc_code);
                if (! ($in_id > 0)) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not add ".$systypes_array[$type]." new line.");
                } 
            $id = $in_id;
        }

        return array("success" => true, "message" => $systypes_array[$type]." line #$id has been saved.");
}

function save_budget_to_budget_transfer_header_and_line(&$bbt_no, $selected_id=0) {
    global $systypes_array;
    
    $type = ST_BUDGET_TO_BUDGET_TRANSFER;
    
    $cn_sv_hd = can_save_budget_to_budget_transfer_header($bbt_no, $type);   
        if ($cn_sv_hd["success"] !== true) {          
            return $cn_sv_hd;
        }
        
        $row_state = $cn_sv_hd['row_state']; $trans_no = $cn_sv_hd['trans_no']; 
        
    $cn_sv_line = can_save_budget_to_budget_transfer_line($selected_id, $type, $trans_no, $_POST['from_loc_code']);   
        if ($cn_sv_line["success"] !== true) {          
            return $cn_sv_line;
        }
        
    $to_jo_id = input_num('to_jo_id'); $reference = $_POST['reference']; $tran_date = date2sql($_POST['tran_date']); $project_id = $_POST['project_id'];
    $to_loc_code = $_POST['to_loc_code']; $from_loc_code = $_POST['from_loc_code']; $to_task_id = $_POST['to_task_id']; $comments = $_POST['comments'];
       
        begin_transaction();

            $hd_msg = save_budget_to_budget_transfer_header($bbt_no, $trans_no, $type, $to_jo_id, $reference, $project_id, $to_loc_code, $to_task_id, $tran_date, $comments, 
                                                            $from_loc_code, $row_state);
                if ($hd_msg["success"] !== true) {
                    cancel_transaction();
                    return array("success" => false, "message" => $hd_msg['message']);
                }
                
            // save b2b transfer line
            $lmsg = save_budget_to_budget_transfer_line($selected_id, $to_jo_id, $type, $trans_no, $from_loc_code, $to_loc_code, $to_task_id, $_POST['item_type'], 
                                                        $_POST['stock_id'], $_POST['item_description'], $_POST['from_jo_id'], $_POST['from_task_id'], $_POST['tran_unit'], 
                                                        input_num('tran_qty'), $_POST['project_site_id'], $_POST['line_comment'], input_num('item_cost'));
                if ($lmsg['success'] !== true) {
                    cancel_transaction();
                    return array("success" => false, "message" => $lmsg['message']);
                }

        commit_transaction();
            
        return array("success" => true, "message" => $systypes_array[$type]." Trans #$trans_no has been saved.");
}

function process_budget_to_budget_transfer_item($trans_no, $type, $tran_date, $project_id, $row, $reference) {
    $tran_date_ = sql2date($tran_date);
    $standard_cost = $row["standard_cost"];
    
    $qty = abs($row["qty"]);
    $tran_qty = abs($row["tran_qty"]);
    $qty_ = $qty * -1;
    $tran_qty_ = $tran_qty * -1;
    
    // from budget and from location
        if ($row['mb_flag'] == 'B' || $row['mb_flag'] == 'M') {
            $n = add_stock_adjustment_item($trans_no, $row["stock_id"], $row["from_loc_code"], $tran_date_, $reference, $qty_, $standard_cost, '', $row["tran_unit"], 
                                           $tran_qty_, $row["conversion_factor"], $type, $row["from_task_id"], $row["project_site_id"], $row["trans_id"], $project_id);
        } else {
            $n = add_non_stock_move($type, $row["stock_id"], $trans_no, $row["from_loc_code"], $tran_date_, $reference, $qty_, $standard_cost, '', $row["visible"], 
                                    $row["price"], 0, $row["tran_unit"], $tran_qty_, $row["conversion_factor"], $row["from_task_id"], $row["project_site_id"], 
                                    $row["trans_id"], $row["item_description"], $project_id);
        }

            if (! ($n > 0)) {
                return array("success" => false, "message" => "Could not create the movement record for rec id : ".$row["trans_id"]);
            }
    
    // to budget and to location    
        if ($row['mb_flag'] == 'B' || $row['mb_flag'] == 'M') {
            $a = add_stock_adjustment_item($trans_no, $row["stock_id"], $row["to_loc_code"], $tran_date_, $reference, $qty, $standard_cost, '', $row["tran_unit"], $tran_qty, 
                                           $row["conversion_factor"], $type, $row["to_task_id"], $row["project_site_id"], $row["trans_id"], $project_id);
        } else {
            $a = add_non_stock_move($type, $row["stock_id"], $trans_no, $row["to_loc_code"], $tran_date_, $reference, $qty, $standard_cost, '', $row["visible"], 
                                    $row["price"], 0, $row["tran_unit"], $tran_qty, $row["conversion_factor"], $row["to_task_id"], $row["project_site_id"], $row["trans_id"], 
                                    $row["item_description"], $project_id);
        }

            if (! ($a > 0)) {
                return array("success" => false, "message" => "Could not create the movement record for rec id : ".$row["trans_id"]);
            }

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

function process_budget_to_budget_transfer_line($type, $trans_no, $tran_date, $project_id, $line_id, $stock_control_method, $ref) {
    $row = get_budget_to_budget_transfer_details_line_by_type_trans_no_line_no($type, $trans_no, $line_id);
            
        // stock move
        $stk_mv_msg = process_budget_to_budget_transfer_item($trans_no, $type, $tran_date, $project_id, $row, $ref);
            if ($stk_mv_msg['success'] === false) {
                cancel_transaction();
                return $stk_mv_msg;
            }
            
        // lot move
        if ($stock_control_method == SKCM_LOTS) {
            $lot_mv_msg = lot_allocations_to_lot_moves($type, $trans_no, $line_id, $row["from_loc_code"]);
                if ($lot_mv_msg['success'] === false) {
                    cancel_transaction();
                    return $lot_mv_msg;
                }
                
            $lot_loc_array = $lot_mv_msg['lot_loc_array'];
            
            // update lot balances
            $lot_bl_msg = save_lot_balances_from_array($lot_loc_array);
                if ($lot_bl_msg['success'] === false) {
                    cancel_transaction();
                    return $lot_bl_msg;
                }
        }

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

function can_process_budget_to_budget_transfer_lines($bbt_no, $type, $trans_no) {
    global $systypes_array;
    
    $tp_name = $systypes_array[$type];
    $lt_alo_name = $systypes_array[ST_LOT_ALLOCATION];
    
    $result = get_budget_to_budget_transfer_details($trans_no, $type);
        if (! (db_num_rows($result) > 0)) {
            return array("success" => false, "message" => "Could not find any $tp_name details lines.");
        }
        
        while ($row = db_fetch($result)) {
            $line_id = $row['trans_id'];
            $stock_id = $row['stock_id'];
            $loc_code = $row['to_loc_code'];
            $con_fac = $row['conversion_factor'];
            $tran_qty = $row['tran_qty'];
            $tran_unit = $row['tran_unit'];
            
            // check lot allocation exceeded
            if ($row['stock_control_method'] == SKCM_LOTS) {
                $data_arr = array('type' => $type, 'trans_no' => $trans_no, 'line_id' => $line_id, 'stock_id' => $stock_id, 'loc_code' => $loc_code, 
                                  'conversion_factor' => $con_fac, 'tran_qty' => $tran_qty, 'tran_unit' => $tran_unit, 'line_name' => 'Transfer');
                
                $lot_ex_msg = check_total_lot_allocations_item_qty_exceed_allowable_qty($data_arr, false);
                    if ($lot_ex_msg['success'] === false) {
                        if ($lot_ex_msg['exceeded'] === true) {
                            return array("success" => false, "message" => "Lien #$line_id transfer qty cannot smaller than total $lt_alo_name."); 
                        } else {
                            return array("success" => false, "message" => "Lien #$line_id transfer qty cannot greater than total $lt_alo_name."); 
                        }
                    }
            }
        }
                
        return array("success" => true, "message" => ""); 
}

function update_budget_to_budget_transfer_budgets($type, $trans_no) {
    // budget update 
    $bbt_charge_details_array = $bbt_remove_details_array = $b = array();

        $result = get_budget_to_budget_transfer_details($trans_no, $type);      
            while ($row = db_fetch($result)) {
                if ($row['item_type'] != NSIT_COMMENT) {
                    $qty = $row['qty'];
                    $b['row_id'] = $row['trans_id'];
                    $b['stock_id'] = $row['stock_id'];
                    $b['task_id'] = $row['to_task_id'];
                    $b['requested_qty'] = $row['qty'];
                    $b['high_value_item'] = 0;

                    $standard_cost = $row['standard_cost'];
                    $b['reference_cost'] = $standard_cost; 
                    $b['standard_cost'] = $standard_cost;
                    $b['charging_cost'] = $standard_cost;
                    $b['total_issued_qty'] = $qty;
                    $b['qty'] = $qty;

                    // charge budget
                    $bbt_charge_details_array[] = $b;

                    unset($b['task_id']);
                    $b['task_id'] = $row['from_task_id'];
                    // remove budget
                    $bbt_remove_details_array[] = $b;
                }
            }

            $created_by = $_SESSION['wa_current_user']->user;
            $bbt_charge_tasks_summary = calculate_task_remaining_totals($bbt_charge_details_array);
    
            $bbt_cct_msg = charge_cost_to_tasks($type, $trans_no, $bbt_charge_tasks_summary, $created_by);
                if ($bbt_cct_msg['success'] !== true) {
                    cancel_transaction();
                    return array("success" => $bbt_cct_msg['success'], "tran_no" => $trans_no, "message" => $bbt_cct_msg['message']);
                }
                
            $bbt_remove_tasks_summary = calculate_task_remaining_totals($bbt_remove_details_array);
            $bbt_rmv_msg = remove_costs_from_tasks($type, $trans_no, $bbt_remove_tasks_summary, $created_by);
                if ($bbt_rmv_msg['success'] !== true) {
                    cancel_transaction();
                    return array("success" => $bbt_rmv_msg['success'], "tran_no" => $trans_no, "message" => $bbt_rmv_msg['message']);
                }
                
                return array("success" => true, "tran_no" => $trans_no, "message" => '');
}

function save_budget_to_budget_transfer($bbt_no, $process=false) {
    global $systypes_array;
    
    $type = ST_BUDGET_TO_BUDGET_TRANSFER;
    $tp_name = $systypes_array[$type];
    
    $cn_sv_hd = can_save_budget_to_budget_transfer_header($bbt_no, $type);   
        if ($cn_sv_hd["success"] !== true) {          
            return $cn_sv_hd;
        }
        
        $row_state = $cn_sv_hd['row_state']; 
        $trans_no = $cn_sv_hd['trans_no']; 
        
    if ($process === true) {
        $cn_pr_lns = can_process_budget_to_budget_transfer_lines($bbt_no, $type, $trans_no);   
            if ($cn_pr_lns["success"] !== true) {          
                return $cn_pr_lns;
            }
    }
        
    $to_jo_id = input_num('to_jo_id'); $reference = $_POST['reference']; $tran_date = date2sql($_POST['tran_date']); $project_id = $_POST['project_id'];
    $from_loc_code = $_POST['from_loc_code']; $to_loc_code = $_POST['to_loc_code']; $to_task_id = $_POST['to_task_id']; $comments = $_POST['comments'];
        
        begin_transaction();
       
            $hd_msg = save_budget_to_budget_transfer_header($bbt_no, $trans_no, $type, $to_jo_id, $reference, $project_id, $to_loc_code, $to_task_id, $tran_date, $comments, 
                                                            $from_loc_code, $row_state);
                if ($hd_msg["success"] !== true) {
                    cancel_transaction();
                    return array("success" => false, "message" => $hd_msg['message']);
                }
        
                if ($process === false) {
                    commit_transaction();
                    return $hd_msg;
                } 

            $current_user_id = $_SESSION['wa_current_user']->user;
            $task_costs = 0;
            $hd_rw = get_budget_to_budget_transfer_header($bbt_no);
            $new_row_state = $hd_rw['row_state'];
            $ref = $hd_rw['reference'];

            $ap_msg = approve_document($type, $trans_no, $hd_rw['project_id'], $task_costs, $hd_rw['next_approval_group_id'], $current_user_id, $new_row_state, 
                                       $hd_rw['created_by']);
                if ($ap_msg["success"] !== true) {          
                    cancel_transaction();
                    return $ap_msg;
                } 
                    
                $approval_status = $ap_msg['approval_status'];
            
            if ($approval_status == AS_APPROVED) {
                $bd_msg = update_budget_to_budget_transfer_budgets($type, $trans_no);
                    if ($bd_msg["success"] !== true) {
                        cancel_transaction();
                        return $bd_msg;
                    }

                // process b2b transfer lines  
                $result = get_budget_to_budget_transfer_details($trans_no, $type);      
                    while ($row = db_fetch($result)) {
                        if (in_array($row['item_type'], array(NSIT_NON_STOCK_ITEM, NSIT_STOCK_ITEM))) {
                            $id = $row['trans_id'];
                            $stock_control_method = $row['stock_control_method'];

                            $prs_msg = process_budget_to_budget_transfer_line($type, $trans_no, $tran_date, $project_id, $id, $stock_control_method, $ref);
                                if ($prs_msg['success'] !== true) {
                                    cancel_transaction();
                                    return array("success" => false, "message" => $prs_msg['message']);
                                }
                        }
                    }
            }
                
            $new_row_state_2 = db_new_row_state($new_row_state);
                
                $up_rw = update_budget_to_budget_transfer_row_state($type, $trans_no, $new_row_state_2);
                    if ($up_rw != 1) {
                        return array("success" => false, "message" => "Could not update $tp_name trans #$trans_no row state.");
                    }
                
        commit_transaction();
        
            set_session_variable('btbtr_messages', $ap_msg['message']);
            meta_forward($_SERVER['PHP_SELF'], "type=$type&ProcessedID=$trans_no"); 
}

function can_delete_budget_to_budget_transfer_line($bbt_no, $selected_id, $type, $tp_name) {
    global $systypes_array;
    
    $header = get_budget_to_budget_transfer_header_record($bbt_no);
        if (is_array($header)) {
            if (! in_array($header['approval_status'], array(AS_NEW, AS_WITH_THE_APPROVER, AS_AWAITING_APPROVAL, AS_BACK_TO_ORIGINATOR))) {
                return array("success" => false, "message" => "$tp_name header #$bbt_no is not allow to further updating.");
            }
        } else {
            return array("success" => false, "message" => "$tp_name header #$bbt_no has been deleted by another user.");
        }

        $trans_no = $header['trans_no'];
        
    $line = get_budget_to_budget_transfer_details_record($selected_id);
        if (! is_array($line)) { 
            return array("success" => false, "message" => "$tp_name line #$selected_id has been deleted by another user.");
        }

    $lines_count = get_budget_to_budget_transfer_details_lines_count($trans_no, $type);
        if ($lines_count == 1) {
            return array("success" => false, "message" => "Cannot delete line #$selected_id because it is last line of $tp_name.");
        }

    $lot_rows = get_lot_allocation_records($type, $trans_no, $selected_id);
        if (db_num_rows($lot_rows) > 0) {
            $lt_alo_name = $systypes_array[ST_LOT_ALLOCATION];
            return array("success" => false, "message" => "Please delete all $lt_alo_name details in $tp_name line #$selected_id.");
        }
            
        return array("success" => true, "message" => "", 'trans_no' => $header['trans_no'], 'row_state' => $header['row_state']);
}

function handle_delete_budget_to_budget_transfer_line($bbt_no, $selected_id) {
    global $systypes_array;
    
    $type = ST_BUDGET_TO_BUDGET_TRANSFER;
    $tp_name = $systypes_array[$type];
    
        $cnd_msg = can_delete_budget_to_budget_transfer_line($bbt_no, $selected_id, $type, $tp_name);
            if ($cnd_msg['success'] === false) {
                return $cnd_msg;
            }
            
            $trans_no = $cnd_msg['trans_no'];
            $row_state = $cnd_msg['row_state'];
        
            begin_transaction();

                $af_row = delete_budget_to_budget_transfer_detail_line_by_id($selected_id);
                    if ($af_row != 1) {
                        cancel_transaction();
                        return array("success" => false, "message" => "Line #$selected_id could not delete.");
                    }
                    
                $upaf_rw = update_budget_to_budget_transfer_row_state($type, $trans_no, $row_state);
                    if ($upaf_rw != 1) {
                        cancel_transaction();
                        return array("success" => false, "message" => "Could not update $tp_name header row state.");
                    }

            commit_transaction();

        return array("success" => true, "message" => "Line record #$selected_id has been deleted.");
}

function clear_budget_to_budget_transfer_line() {
    unset($_POST['item_type']);
    unset($_POST['stock_id']);
    unset($_POST['item_description']);
    unset($_POST['from_jo_id']);
    unset($_POST['from_task_id']);
    unset($_POST['tran_unit']);
    unset($_POST['tran_qty']);
    unset($_POST['project_site_id']);
    unset($_POST['line_comment']);
}

function view_budget_to_budget_transfer_header($type, $trans_no) {
    global $approval_statuses;
    
    $row = get_budget_to_budget_transfer_header_type_trans_no($type, $trans_no);
    
        start_outer_table(TABLESTYLE2, "width=60%");

            table_section(1, "50%");
                $jo_id = $row['to_jo_id'];
                label_row(_("Job Card #:"), get_service_trans_view_str(ST_JOB_ORDER, $jo_id), "class='tableheader2'");
                label_row(_("Trans #:"), get_trans_view_str($type, $trans_no), "class='tableheader2'");
                label_row(_("Reference:"), $row['reference'], "class='tableheader2'");
                label_row(_("Project:"), $row['project_description'], "class='tableheader2'");

            table_section(2, "50%");
                label_row(_("Date:"), sql2date($row['tran_date']), "class='tableheader2'");
                label_row(_("From Location:"), $row['from_location_name'], "class='tableheader2'");
                label_row(_("To Location:"), $row['to_location_name'], "class='tableheader2'");
                label_row(_("To Budget:"), $row['to_task_description'], "class='tableheader2'");
                $s = get_project_trans_view_str(ST_APPROVAL_LOG, $trans_no."&source_type_id=".$type, "Approval Status");
                label_row($s, $approval_statuses[$row['approval_status']], "class='tableheader2'");

        end_outer_table(2);

        if (strlen($row['comments']) > 0) {
            start_table(TABLESTYLE2);
                label_row(_("Comment:"), nl2br($row['comments']), "class='tableheader2'");
            end_table(2);
        }
}

function view_budget_to_budget_transfer_details($type, $trans_no) {
    global $daily_item_types_array;
    
    $view_tp = ST_LOT_ALLOCATION;
    $hd_row = get_budget_to_budget_transfer_header_record_type_trans_no($type, $trans_no);
        if (in_array($hd_row['approval_status'], array(AS_APPROVED))) {
            $view_tp = ST_LOT_MOVE;
        }
    
    start_table(TABLESTYLE, "width=99%");

        $th = array(_("Id"), _("Item Type"), _("Item"), _("From Job"), _("From Budget"), _('Base Qty'), _('Tran Unit'), _('Tran Qty'), _('Site'), _('Line Comment')); 
        table_header($th);

        $k = 0; //row colour counter
            $result = get_budget_to_budget_transfer_details($trans_no, $type);      
                while ($row = db_fetch($result)) {
                    $dec = 4;
                    
                    alt_table_row_color($k);

                        $trans_id = $row['trans_id'];
                        
                        if ($row['stock_control_method'] == SKCM_LOTS) {
                            $params = "type=".ST_BUDGET_TO_BUDGET_TRANSFER."&trans_no=$trans_no&line_id=$trans_id";
                            label_cell(get_data_view_str($view_tp, $params, $trans_id), 'align=center');
                        } else {
                            label_cell($row['trans_id'], 'align=center');
                        }
                            
                        label_cell($daily_item_types_array[$row['item_type']]);
                        if ($row['item_type'] == NSIT_NON_STOCK_ITEM || $row['item_type'] == NSIT_STOCK_ITEM) {
                            label_cell($row["stock_id"]." - ".$row["item_description"]);  
                            
                            $dec = 4; // get_qty_dec($row["stock_id"]);
                        } else {
                            label_cell($row["item_description"]);
                        }
                        $from_jo_id = $row["from_jo_id"];
                        label_cell(get_service_trans_view_str(ST_JOB_ORDER, $from_jo_id), 'align=center');
                        label_cell($row["from_task_description"]);
                        qty_cell($row["qty"], false, $dec);
                        label_cell($row["unit_name"]);
                        
                        if ($row['stock_control_method'] == SKCM_LOTS) {
                            $params = "type=".ST_BUDGET_TO_BUDGET_TRANSFER."&trans_no=$trans_no&line_id=$trans_id";
                            label_cell(get_data_view_str($view_tp, $params, number_format($row["tran_qty"], $dec)), 'align=right');
                        } else {
                            qty_cell($row["tran_qty"], false, $dec);
                        }
                        
                        label_cell($row["site_description"]);          
                        label_cell(nl2br($row["line_comment"]));          

                    end_row();        
                }

    end_table(2);
}

function view_budget_to_budget_borrowed_headers_by_jo_id($to_jo_id, $width=80) {
    global $systypes_array, $approval_statuses;
    
    display_heading2($systypes_array[ST_BUDGET_TO_BUDGET_TRANSFER]." Borrowed Items");    br();
    
        start_table(TABLESTYLE, "width=$width%");

            $th = array(_("Trans #"), _("Reference"), _("Description"), _("Date"), _("From Location"), _("To Location"), _("Approval Status"));  
            table_header($th);

            $k = 0; 
            $result = get_budget_to_budget_transfer_headers_by_filters($to_jo_id); 
                while ($row = db_fetch($result)) {
                    alt_table_row_color($k);
                        
                        label_cell(get_trans_view_str($row['type'], $row['trans_no']), 'align=center');
                        label_cell($row["reference"]);
                        label_cell($row["comments"]);
                        label_cell(sql2date($row["tran_date"]), 'align=center');
                        label_cell($row['from_location_name']);
                        label_cell($row['to_location_name']);
                        label_cell($approval_statuses[$row['approval_status']], 'align=center');
                        
                    end_row();        
                }

        end_table(2);
}

function view_budget_to_budget_lent_headers_by_jo_id($from_jo_id, $width=70) {
    global $systypes_array;
    
    display_heading2($systypes_array[ST_BUDGET_TO_BUDGET_TRANSFER]." Lent Items");    br();
    
        start_table(TABLESTYLE, "width=$width%");

            $th = array(_("Trans #"), _("To Job"), _("From Location"), _("To Location"), _("Item"), _("Base Unit"), _("Base Qty"));  
            table_header($th);
            
            $select = " type, trans_no, to_jo_id, from_loc_code, to_loc_code, stock_id, SUM(qty) total_qty";
            $group_by = " type, trans_no";
            
            $k = 0; 
            $result = get_budget_to_budget_transfer_details_by_filters(select: $select, from_jo_id: $from_jo_id, group_by: $group_by, fetch: false);
                while ($row = db_fetch($result)) {
                    alt_table_row_color($k);
                        
                        label_cell(get_trans_view_str($row['type'], $row['trans_no']), 'align=center');
                        $to_jo_id = $row["to_jo_id"];
                        label_cell(get_service_trans_view_str(ST_JOB_ORDER, $to_jo_id), 'align=center');
                        if (strlen($row['from_loc_code']) > 0) {
                            label_cell(get_location_name($row['from_loc_code']));
                        } else {
                            label_cell('');
                        }
                        if (strlen($row['to_loc_code']) > 0) {
                            label_cell(get_location_name($row['to_loc_code']));
                        } else {
                            label_cell('');
                        }
                        label_cell(get_stock_item_formatted_name($row['stock_id']));
                        label_cell(get_item_base_unit_name($row['stock_id']));
                        qty_cell($row['total_qty'], false, 4);
                        
                    end_row();        
                }

        end_table(2);
}

?>