<?php

function display_job_manual_cost_header($jmc_no) {
    global $Refs;
    
    $trans_no = 0;
    if (isset($_POST['jo_id']) || isset($_POST['ModifyJMC_No'])) {
        $type = ST_JOB_MANUAL_COST;
    } 
    
        if ($jmc_no > 0) {

            $header = get_job_material_issue_header($jmc_no);
            $_POST['project_id'] = $header['project_id'];
            hidden('project_id', $header['project_id']);

            $trans_no = $header['trans_no'];
            $user_id = $_SESSION['wa_current_user']->user;
            $cap = can_access_project($_POST['project_id'], $user_id);
                if($cap['success'] !== true) {
                    display_error($cap["message"]);
                    set_focus('project_id');
                    display_footer_exit();
                    exit;
                }  

            if (! isset($_POST['reference'])) {
                $_POST['reference'] = $header['reference'];
            }
            if (! isset($_POST['comments'])){
                $_POST['comments'] = $header['comments'];
            }        
            if (! isset($_POST['location'])) {
                $_POST['location'] = $header['loc_code'];
            }
            if (! isset($_POST['tran_date'])) {
                $_POST['tran_date'] = sql2date($header['tran_date']);
            }
            if (! isset($_POST['project_description'])) {
                $_POST['project_description'] = $header['project_description'];
            }
            if (! isset($_POST['approval_status'])) {
                $_POST['approval_status'] = $header['approval_status'];
            }
            $_POST['total'] = $header['total'];
        } else {
            $_POST['reference'] = $Refs->get_next($type);            
            $_POST['approval_status'] = 0;
            $_POST['total'] = 0;
        }
        
        div_start('nsit_header');
            start_outer_table(TABLESTYLE2, "width=65%"); // outer table
                start_table(TABLESTYLE2);  
                    table_section(1, "50%");
                    
                        if (isset($_POST['jo_id']) && $_POST['jo_id'] > 0) {
                            $jo_id = $_POST['jo_id'];
                            label_row("Job Card:", get_service_trans_view_str(ST_JOB_ORDER, $jo_id)); 
                        }
                        if ($jmc_no > 0) {
                            $pd_request = get_job_material_issue_header($jmc_no);
                            label_row("Trans #:", get_inventory_trans_view_str($pd_request['type'], $pd_request['trans_no']));  
                            
                            $reference = $pd_request['reference'];            
                            text_row("Reference:", 'reference', $reference, null, null);            
                        } else {            
                            text_row("Reference:", 'reference', $Refs->get_next($type), null, null);   
                        }
                        if ($jmc_no > 0) {
                            label_row("Project:", get_project_formatted_name($_POST['project_id']));   
                        } elseif (isset($_POST['jo_id']) && $_POST['jo_id'] > 0) {
                            $jo_pro = get_job_order_department_approval_project($_POST['jo_id']);
                            $_POST['project_id'] = $jo_pro['project_id'];
                            hidden('project_id', $jo_pro['project_id']);
                            label_row("Project:", get_project_formatted_name($jo_pro['project_id']));   
                        } else {
                            $_POST['project_id'] = 0;
                            hidden('project_id', 0);
                        } 
                        date_row("Date:", "tran_date");
                        
                    table_section(2, "50%");
                    
                        locations_list_row("Location:", 'location', null, '', false);  
                        textarea_row("Comment:", 'comments', null, 35, 2); 
                        label_row('Total:', number_format($_POST['total'], 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_job_manual_cost_details($jmc_no, $selected_id, &$Mode) { 
    global $Ajax, $daily_item_types_array;
    
    display_heading("Details");
    
    $trans_no = $type = -1;
    $header = get_job_material_issue_header_record($jmc_no);
        if (is_array($header)) {
            $trans_no = $header['trans_no'];
            $type = $header['type'];
        } 
    
    $Ajax->activate('nsit_details');
    div_start('nsit_details');
        start_table(TABLESTYLE, "width=98%");

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

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

                                label_cell($row['trans_id'], 'align=center');
                                label_cell($daily_item_types_array[$row['item_type']]);
                                if (in_array($row['item_type'], array(NSIT_NON_STOCK_ITEM, NSIT_STOCK_ITEM))) {
                                    label_cell($row["stock_id"]." - ".$row["item_description"]);  
                                } else {
                                    label_cell($row["item_description"]);
                                }
                                label_cell($row["unit_name"]);
                                $dec = get_qty_dec($row["stock_id"]);
                                qty_cell($row["tran_qty"], false, $dec);

                                if ($row['item_type'] == NSIT_COMMENT) {
                                    label_cell('No budget required');
                                } else {
                                    label_cell($row["task_description"]);
                                }
                                $tran_unit_cost = $row["standard_cost"] * $row["conversion_factor"];
                                    if ($tran_unit_cost > 0) {
                                        qty_cell($tran_unit_cost, false, $dec);
                                    } else {
                                        label_cell('');
                                    }
                                    
                                $line_total = $tran_unit_cost * $row["tran_qty"];
                                    if ($line_total > 0) {
                                        qty_cell($line_total, false, 2);
                                    } else {
                                        label_cell('');
                                    }
                                label_cell($row["site_description"]);          
                                label_cell(nl2br($row["line_comment"]));          
                                edit_button_cell("Edit".$row["trans_id"], _("Edit"));    
                                delete_button_cell("Delete".$row["trans_id"], _("Delete"));  

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

        end_table(2);
    div_end();
}

function display_job_manual_cost_details_edit_controls($selected_id, &$Mode) {
    global $Ajax, $daily_item_types_array;
    $dec = 2;

    if (list_updated('tran_unit')) {
        $_POST['item_cost'] = 0;
    }
    if ($selected_id > 0 && $Mode != 'Delete') {   
        $row = get_job_material_issue_detail_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['tran_unit'] = $row["tran_unit"];
                $_POST['tran_qty'] = $row["tran_qty"];
                $_POST['site_id'] = $row["project_site_id"];
                $_POST['task_id'] = $row["task_id"];
                $_POST['item_cost'] = $row["standard_cost"] * $row["conversion_factor"];
                $_POST['line_comment'] = $row["line_comment"];
            }
            
            if (! (strlen($_POST['stock_id']) > 0)) {
                $_POST['stock_id'] = $row["stock_id"];
            }
            if ($_POST['tran_unit'] == -1) {
                $_POST['tran_unit'] = $row["tran_unit"];
            }
            if (! ($_POST['tran_qty'] > 0)) {
                $_POST['tran_qty'] = $row["tran_qty"];
            }
            if (! ($_POST['task_id'] > 0)) {
                $_POST['task_id'] = $row["task_id"];
            }
            if (! ($_POST['item_cost'] > 0)) {
                $_POST['item_cost'] = $row["standard_cost"] * $row["conversion_factor"];
            }
            
            if (! (strlen($_POST['line_comment']) > 0)) {
                $_POST['line_comment'] = $row["line_comment"];
            }
    }
  
    echo "<td colspan=10>";
        $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:', $daily_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', $daily_item_types_array, null, '', true);
                    }

                    if ($_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 {
                            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 != 'Delete') {  
                            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, '', true);
                        $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', '');
                    }
                    
                amount_row("Quantity:", 'tran_qty', null, null, null, $dec);
                
            table_section(2);

                all_budgets_list_row('Budget:', 'task_id', GLOBAL_VOTES, null, _(''));

                if (in_array($_POST['item_type'], array(NSIT_STOCK_ITEM)) && (! isset($_POST['item_cost']) || ! $_POST['item_cost'] > 0)) {
                    $conversion_factor = 1;
                    $st_cost = get_standard_cost($_POST['stock_id']);
                    get_convertion_factor2($_POST['stock_id'], $_POST['tran_unit'], $conversion_factor);
                    
                    $tran_unit_cost = $st_cost * $conversion_factor;
                    $_POST['item_cost'] = $tran_unit_cost;
                } 
                amount_row("Unit Cost:", 'item_cost', null, null, null, 0);

                all_project_sites_list_row("Site:", 'site_id', GLOBAL_VOTES, null, '', false); 
                text_row_ex('Line Comment:', 'line_comment', 50, 400, 'Line Comment');

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

        } else {        
            button_cell('Add_JMC', _("ADD"),  _('Confirm changes'), ICON_ADD);
            button_cell('cancel', _("Cancel"), _("Cancel changes"), ICON_CANCEL);
        }
}

function create_job_manual_cost_header_array($jmc_no) {
    $hd_array = array();
    
        $hd_array['jo_id'] = $_POST['jo_id'];
        $hd_array['ModifyJMC_No'] = isset($_POST['ModifyJMC_No']) ? $_POST['ModifyJMC_No'] : null;
        $hd_array['project_id'] = $_POST['project_id'];
        $hd_array['jmc_no'] = $jmc_no;
        $hd_array['type'] = ST_JOB_MANUAL_COST;
        $hd_array['trans_no'] = 0;
        $hd_array['approval_status'] = AS_NEW;
        $hd_array['next_approval_group_id'] = 0;
        $hd_array['created_by'] = $_SESSION['wa_current_user']->user;
        $hd_array['row_state'] = 0;
        $hd_row = get_job_material_issue_header_record($jmc_no);
            if (is_array($hd_row)) {
                $hd_array['trans_no'] = $hd_row['trans_no'];
                $hd_array['type'] = $hd_row['type'];
                $hd_array['approval_status'] = $hd_row['approval_status'];
                $hd_array['project_id'] = $hd_row['project_id'];
                $hd_array['next_approval_group_id'] = $hd_row['next_approval_group_id'];
                $hd_array['created_by'] = $hd_row['created_by'];
                $hd_array['row_state'] = $hd_row['row_state'];

                $hd_array['lines_count'] = get_job_material_issue_details_lines_count($hd_array['trans_no'], $hd_array['type']);
            } 
        $hd_array['reference'] = $_POST['reference'];
        $hd_array['tran_date'] = $_POST['tran_date'];
        $hd_array['location'] = $_POST['location'];
        $hd_array['comments'] = $_POST['comments'];
    
        return $hd_array;
}

function can_process_job_manual_cost_header($hd_array) {
    global $Refs, $systypes_array;
    
    if ($hd_array['type'] != ST_JOB_MANUAL_COST) {
        return array("success" => false, "message" => "Invalid transaction type.");
    }
    
    if (! ($hd_array['jo_id'] > 0)) {
        return array("success" => false, "focus_to" => 'jo_id', "message" => "Job Card cannot empty.");
    } else {
        $jo_row = get_job_order_record($hd_array['jo_id']);
        if (! is_array($jo_row)) {
            return array("success" => false, "message" => "Could not find Job Card #".$hd_array['jo_id'].".");
        }
    }
    
    if (! isset($hd_array['jo_id']) && ! isset($hd_array['ModifyJMC_No'])) {
        return array("success" => false, "message" => "Invalid transaction.");
    }
    
    if (! isset($hd_array['type'])) {
        return array("success" => false, "focus_to" => '', "message" => "Invalid transaction type.");
    }
    
    $jmc_no = $hd_array['jmc_no'];
    $trans_no = $hd_array['trans_no'];
    $row_state = $hd_array['row_state'];
    
    if ($jmc_no > 0) {
        if (! isset($trans_no) && ! ($trans_no > 0)) {
            return array("success" => false, "message" => "Could not find ".$systypes_array[$hd_array['type']]." Header Record #$jmc_no.");
        }
        
        if (! in_array($hd_array['approval_status'], array(AS_NEW, AS_WITH_THE_APPROVER, AS_AWAITING_APPROVAL, AS_BACK_TO_ORIGINATOR))) {
            return array("success" => false, "focus_to" => '', "message" => "This document status does not allow further updating.");
        }
        
        $ced_msg = can_edit_document(ST_JOB_MANUAL_COST, $hd_array['project_id'], $hd_array['next_approval_group_id'], $_SESSION['wa_current_user']->user, 
                                     $hd_array['created_by']);
            if ($ced_msg['success'] !== true){
                return array("success" => false, "message" => $ced_msg['message']);
            }
        
        if (! ($hd_array['lines_count'] > 0)) {
            return array("success" => false, "focus_to" => '', "message" => "No any saved detail lines found.");
        }
    } 
    
    if (! $Refs->is_valid($hd_array['reference'])) {
        return array("success" => false, "focus_to" => 'reference', "message" => "Please enter a reference.");      
    }    
 
    $ref_msg = reference_exists($hd_array['reference'], $hd_array['type'], $trans_no);
        if ($ref_msg) {
            return array("success" => false, "focus_to" => 'reference', "message" => $ref_msg);       
        }
      
    if (! ($jmc_no > 0)) {
        if (! ($hd_array['project_id'] > 0)) {
            $jo_pro = get_job_order_department_approval_project($hd_array['jo_id']);
                if ($jo_pro['success'] === false) {
                    return array("success" => false, "focus_to" => '', "message" => $jo_pro['message']);
                }
                
            return array("success" => false, "focus_to" => '', "message" => "Please select a Project.");
        }
    }
    
    if (! is_date($hd_array['tran_date'])) {
        return array("success" => false, "focus_to" => 'tran_date', "message" => "Date entered is not a valid date.");        
    }
              
    if ($hd_array['location'] == '') {
        return array("success" => false, "focus_to" => 'location', "message" => "Please select a location.");
    }
    
    return array("success" => true, 'row_state' => $row_state, "message" => "");     
}

function create_job_manual_cost_line_array($selected_id) {
    $ln_array = array();
    
        $ln_array['selected_id'] = $selected_id;
        $ln_array['item_type'] = $_POST['item_type'];
        $ln_array['stock_id'] = isset($_POST['stock_id']) ? $_POST['stock_id'] : '';
        $ln_array['tran_unit'] = $_POST['tran_unit'];
        $ln_array['tran_qty'] = input_num('tran_qty');
        $ln_array['item_description'] = isset($_POST['item_description']) ? $_POST['item_description'] : '';
        $ln_array['task_id'] = $_POST['task_id'];
        $ln_array['site_id'] = $_POST['site_id'];
        $ln_array['line_comment'] = $_POST['line_comment'];
        $ln_array['item_cost'] = isset($_POST['item_cost']) ? input_num('item_cost') : 0;
        
        $ln_array['tran_date'] = date2sql($_POST['tran_date']);
        $ln_array['location'] = $_POST['location'];

            return $ln_array;
}

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

        if ($ln_array['tran_unit'] == -1) {
            return array("success" => false, "focus_to" => "tran_unit$post", "message" => "$err_text Please select a tran unit.");  
        }
    } elseif ($ln_array['item_type'] == NSIT_COMMENT) {
        if (! (strlen($ln_array['item_description']) > 0)) {
            return array("success" => false, "focus_to" => "item_description$post", "message" => "$err_text Item description cannot be empty.");  
        }
        
        if ($ln_array['tran_unit'] == '0') {
            return array("success" => false, "focus_to" => "tran_unit$post", "message" => "$err_text Please select a tran unit.");  
        }
    }
    
    $item = get_stock_item_edit_info($ln_array['stock_id']);
        if ($ln_array['item_type'] == NSIT_NON_STOCK_ITEM){
            if (! ($item['mb_flag'] == "D")) {
                return array("success" => false, "focus_to" => "stock_id$post", "message" => "$err_text Selected item is a stock item, Please select a non-stock item.");  
            } 
        } elseif ($ln_array['item_type'] == NSIT_STOCK_ITEM){
            if (! in_array($item['mb_flag'], array("B", "M"))) {
                return array("success" => false, "focus_to" => "stock_id$post", "message" => "$err_text Selected item is not a stock item, Please select a stock item.");  
            } 
        }
    
    if (! ($ln_array['tran_qty'] > 0)) {
        return array("success" => false, "focus_to" => "tran_qty$post", "message" => "$err_text Quantity should be greater than zero.");  
    }
    
    if (! ($ln_array['task_id'] > 0)) {
        return array("success" => false, "focus_to" => "task_id$post", "message" => "$err_text Please select a budget.");  
    }
    
    if (in_array($_POST['item_type'], array(NSIT_NON_STOCK_ITEM, NSIT_COMMENT))) {
        if (! ($ln_array['item_cost'] > 0)) {
            return array("success" => false, "focus_to" => "item_cost$post", "message" => "$err_text Unit cost should be greater than zero.");  
        }
    }

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

function can_delete_job_manual_cost_line($jmc_no, $selected_id) {
   $header = get_job_material_issue_header_record($jmc_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))) {
            $message = ("This document status does not allow further updating.");
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
    } 
    
    $ced_msg = can_edit_document(ST_JOB_MANUAL_COST, $header['project_id'], $header['next_approval_group_id'], $_SESSION['wa_current_user']->user, $header['created_by']);
        if ($ced_msg['success'] !== true){
            return array("success" => false, "message" => $ced_msg['message']);
        }
    
    $row = get_job_material_issue_detail_record($selected_id);   
        if (! (isset($row['trans_id']) && $row['trans_id'] > 0)) {
            return array("success" => false, "message" => "Line record #$selected_id is already deleted by another user.");
        }
        
    $lines_count = get_job_material_issue_details_lines_count($header['trans_no'], $header['type']);
        if (! ($lines_count > 1)) {
            $message = ("This is the last line. Can not delete this line.");
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }  
    
        return array("success" => true, "focus_to" => '', "message" => "");       
}

function save_job_manual_cost_header(&$hd_array) {
    global $systypes_array;

    $increse_row_state = false;
    $type = $hd_array['type']; $jmc_no = $hd_array['jmc_no']; $trans_no = $hd_array['trans_no']; $tran_date = date2sql($hd_array['tran_date']); 
    
    if ($trans_no > 0) {
        $increse_row_state = true;
    }
    
    $af_no = write_job_material_issue_header($type, 0, $jmc_no, $trans_no, $hd_array['reference'], $hd_array['project_id'], $hd_array['location'], $hd_array['comments'], 
                                             $tran_date, $hd_array['row_state'], $hd_array['jo_id']); 
    
        if ($af_no > 0) {
            $hd_array['jmc_no'] = $jmc_no; $hd_array['trans_no'] = $trans_no; 
            
            $hd_array['row_state'] = $increse_row_state === true ? db_new_row_state($hd_array['row_state']) : $hd_array['row_state'];
            return array("success" => true, "message" => $systypes_array[$type]." header trans #$trans_no has been saved.");
        } else {
            return array("success" => false, "message" => "Could not save ".$systypes_array[$type].' header.');
        }
}

function save_job_manual_cost_line($ln_array, $err_text='') {    
    global $systypes_array;
    
    $conversion_factor = 1;
    $tran_unit = $ln_array['tran_unit'];
    
    if (in_array($ln_array['item_type'], array(NSIT_STOCK_ITEM, NSIT_NON_STOCK_ITEM))) {
        get_convertion_factor2($ln_array['stock_id'], $tran_unit, $conversion_factor);
    }
    
    $tran_unit_cost = $ln_array['item_cost'];
    $standard_cost = $tran_unit_cost / $conversion_factor;
    
    $qty = $ln_array['tran_qty'] * $conversion_factor;
    
    $type = $ln_array['type'];
    $selected_id = $ln_array['selected_id'];
    
        if ($selected_id > 0) {
            $af_no = update_job_material_issue_line($selected_id, $ln_array['location'], $ln_array['item_type'], $ln_array['stock_id'], $ln_array['item_description'], 
                                                    $tran_unit, $ln_array['tran_qty'], $qty, $conversion_factor, $ln_array['task_id'], $ln_array['site_id'], $standard_cost,  
                                                    $ln_array['line_comment']);
            $ad_up_tp = "updated";
        } else {
            $af_no = insert_job_material_issue_line($ln_array['trans_no'], $type, $ln_array['location'], $ln_array['tran_date'], $ln_array['stock_id'], $ln_array['item_type'],
                                                    $ln_array['item_description'], $tran_unit, $ln_array['tran_qty'], $qty, $conversion_factor, $standard_cost, 
                                                    $ln_array['site_id'], $ln_array['line_comment'], $ln_array['task_id']); 
            $ad_up_tp = "added";
        }
    
            if ($af_no > 0) {
                return array("success" => true, "message" => $systypes_array[$type]." line #$selected_id has been $ad_up_tp.");
            } else {
                if ($selected_id > 0) {
                    $ln_ms = $systypes_array[$type]." #$selected_id line could not be $ad_up_tp.";
                } else {
                    $ln_ms = $err_text.$systypes_array[$type]." line could not be $ad_up_tp.";
                }

                    return array("success" => false, "message" => $ln_ms);
            }
}

function save_job_manual_cost(&$jmc_no, $selected_id) {
    global $systypes_array;
    
    $hd_array = create_job_manual_cost_header_array($jmc_no);
    
    $hd_msg = can_process_job_manual_cost_header($hd_array);   
        if ($hd_msg["success"] !== true) {          
            if (isset($hd_msg["focus_to"])) {
                set_focus($hd_msg["focus_to"]);            
            }
            return $hd_msg;
        } 
        
    $ln_array = create_job_manual_cost_line_array($selected_id);
    
    $ln_msg = can_process_job_manual_cost_line($ln_array);
        if ($ln_msg['success'] !== true) {
            if (isset($ln_msg["focus_to"])) {
                set_focus($ln_msg["focus_to"]);            
            }
            return $ln_msg;        
        }
       
        begin_transaction();

            $header_msg = save_job_manual_cost_header($hd_array);
                if ($header_msg["success"] !== true) {
                    cancel_transaction();
                    return array("success" => false, "message" => $header_msg['message']);
                }
                
                $jmc_no = $ln_array['jmc_no'] = $hd_array['jmc_no']; 
                $ln_array['type'] = $hd_array['type'];
                $ln_array['trans_no'] = $hd_array['trans_no']; 
                $new_row_state = $hd_array['row_state'];
                
            $line_msg = save_job_manual_cost_line($ln_array);
                if ($line_msg['success'] !== true) {
                    cancel_transaction();
                    return array("success" => false, "message" => $line_msg['message']);
                }
                
            $num_af_row = update_job_material_issue_header_totals($ln_array['type'], $ln_array['trans_no'], $new_row_state);
                if (! ($num_af_row == 1)) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not update ".$systypes_array[$ln_array['type']]." header total.");
                }

        commit_transaction();

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

function delete_job_manual_cost_line($jmc_no, $selected_id) {
    $cd_msg = can_delete_job_manual_cost_line($jmc_no, $selected_id);
        if ($cd_msg['success'] !== true) {
            return $cd_msg;
        }
        
        begin_transaction();
            $af_row = delete_job_material_issue_detail_line_by_id($selected_id);
                if ($af_row != 1) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not delete line record #$selected_id.");
                }
        commit_transaction();

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

function save_job_manual_cost_header_only(&$jmc_no, $approve=false) {
    $hd_array = create_job_manual_cost_header_array($jmc_no);
    
    $hd_msg = can_process_job_manual_cost_header($hd_array);   
        if ($hd_msg["success"] !== true) {          
            if (isset($hd_msg["focus_to"])) {
                set_focus($hd_msg["focus_to"]);            
            }
            return $hd_msg;
        } 
        
        begin_transaction();
        
            $msg = save_job_manual_cost_header($hd_array);
                if ($msg["success"] !== true) {          
                    cancel_transaction();

                    return $msg;
                } 

                if ($approve === false) {
                    commit_transaction();

                    return $msg;
                } 

            $header = get_job_material_issue_header_record($jmc_no);
            $ap_msg = approve_job_manual_cost($header);
                if ($ap_msg["success"] !== true) {          
                    cancel_transaction();

                    return $ap_msg;
                } 
                
                if ($ap_msg['approval_status'] == AS_APPROVED) {
                    // process job material issue line 
                    $prs_msg = process_job_manual_cost($hd_array['trans_no'], $hd_array['type'], $hd_array['tran_date'], $hd_array['project_id']);
                        if ($prs_msg['success'] !== true) {
                            cancel_transaction();
                            
                            return array("success" => false, "message" => $prs_msg['message']);
                        }
                }
                
        commit_transaction();

            set_session_variable('jmr_messages', $ap_msg['message']);
            meta_forward($_SERVER['PHP_SELF'], "type=".$header['type']."&ApprovedID=".$header['trans_no']); 
}

function approve_job_manual_cost($header) {
    $current_user_id = $_SESSION['wa_current_user']->user;
    $task_costs = 0;
    
    return approve_document($header['type'], $header['trans_no'], $header['project_id'], $task_costs, $header['next_approval_group_id'], $current_user_id, 
                            $header['row_state'], $header['created_by']);
}

function process_job_manual_cost($trans_no, $type, $tran_date_, $project_id) {
    // stock move and lot move
    $result = get_job_material_issue_details($trans_no, $type);
        while ($row = db_fetch($result)) {
            $stock_control_method = $row['stock_control_method'];

            // stock move
            $stk_mv_msg = process_job_manual_cost_item($trans_no, $type, $tran_date_, $project_id, $row);
                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, $row['trans_id']);
                    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;
                    }
            }
        }

        // budgets update 
        $jmc_details_array = $b = array();
        $result_2 = get_job_material_issue_details($trans_no, $type);
            while ($row = db_fetch($result_2)) {
                $qty = $row['qty'];
                $b['row_id'] = $row['trans_id'];
                $b['stock_id'] = $row['stock_id'];
                $b['task_id'] = $row['task_id'];
                $b['requested_qty'] = $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;

                $jmc_details_array[] = $b;
            }

            $jmc_tasks_summary = calculate_task_remaining_totals($jmc_details_array);
            $created_by = $_SESSION['wa_current_user']->user;

            $mtrec_msg = charge_cost_to_tasks($type, $trans_no, $jmc_tasks_summary, $created_by);
                if ($mtrec_msg['success'] !== true) {
                    cancel_transaction();

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

function process_job_manual_cost_item($trans_no, $type, $tran_date_, $project_id, $row) {
    $qty = abs($row["qty"]);
    $tran_qty = abs($row["tran_qty"]);
    
    if ($type == ST_JOB_MANUAL_COST) {
        $qty *= -1;
        $tran_qty *= -1;
    }
    
    $standard_cost = $row["standard_cost"];
    
        if ($row['mb_flag'] == 'B' || $row['mb_flag'] == 'M') {
            $n = add_stock_adjustment_item($trans_no, $row["stock_id"], $row["loc_code"], $tran_date_, $row["reference"], $qty, $standard_cost, '', $row["tran_unit"], 
                                           $tran_qty, $row["conversion_factor"], $type, $row["task_id"], $row["project_site_id"], $row["trans_id"], $project_id);
        } else {
            $n = add_non_stock_move($type, $row["stock_id"], $trans_no, $row["loc_code"], $tran_date_, $row["reference"], $qty, $standard_cost, 0, $row["visible"], 
                                    $row["price"], $row["discount_percent"], $row["tran_unit"], $tran_qty, $row["conversion_factor"], $row["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 line record #".$row["trans_id"]);
        }

        return array("success" => true, 'trans_no' => $trans_no, "message" => "");            
}
    
function can_reject_back_to_originator_job_manual_cost($jmc_no, $trans_tp_name, $reject) {
    $hd_row = get_job_material_issue_header_record($jmc_no);
        if (! is_array($hd_row)) {
            return array("success" => false, "message" => "Could not find $trans_tp_name #$jmc_no.");
        }

        if (! isset($hd_row['type']) || $hd_row['type'] != ST_JOB_MANUAL_COST) {
            return array("success" => false, "message" => "Invalid transaction type.");
        }
        
        if ($reject === true) {
            if (! in_array($hd_row['approval_status'], array(AS_NEW, AS_AWAITING_APPROVAL, AS_BACK_TO_ORIGINATOR, AS_WITH_THE_APPROVER))) {
                return array("success" => false, "message" => "This document status does not allow to reject. Only unapproved records can be rejected.");
            }
        } else {
            if (! in_array($hd_row['approval_status'], array(AS_AWAITING_APPROVAL, AS_WITH_THE_APPROVER))) {
                return array("success" => false, "message" => "This document status does not allow to back to originator.");
            }
        }
        
        $ced_msg = can_edit_document(ST_JOB_MANUAL_COST, $hd_row['project_id'], $hd_row['next_approval_group_id'], $_SESSION['wa_current_user']->user, $hd_row['created_by']);
            if ($ced_msg['success'] !== true) {
                return array("success" => false, "message" => $ced_msg['message']);
            }
        
        return array("success" => true, "message" => "", "trans_no" => $hd_row["trans_no"], "row_state" => $hd_row["row_state"], "hd_row" => $hd_row);
}

function reject_job_manual_cost($jmc_no) {
    global $systypes_array;
    
    $type = ST_JOB_MANUAL_COST;
    $trans_tp_name = $systypes_array[$type];
    
    $cn_rej = can_reject_back_to_originator_job_manual_cost($jmc_no, $trans_tp_name, true);
        if ($cn_rej["success"] !== true) { 
            return $cn_rej;
        } 
        
        $hd_row = $cn_rej["hd_row"];
        $trans_no = $cn_rej["trans_no"];
        
        begin_transaction();
        
            $rj_msg = reject_document($type, $trans_no, $hd_row['project_id'], $hd_row['next_approval_group_id'], $_SESSION['wa_current_user']->user, $hd_row['row_state']);
                if ($rj_msg['success'] !== true) {
                    cancel_transaction();
                    return array("success" => false, "message" => $rj_msg['message']);
                }
        
        commit_transaction();

            set_session_variable('jmr_rj_messages', $rj_msg['message']);
            meta_forward($_SERVER['PHP_SELF'], "type=$type&RejectedID=$trans_no"); 
}

function back_to_originator_job_manual_cost($jmc_no) {
    global $systypes_array;
    
    $type = ST_JOB_MANUAL_COST;
    $trans_tp_name = $systypes_array[$type];
    
    $cn_rej = can_reject_back_to_originator_job_manual_cost($jmc_no, $trans_tp_name, false);
        if ($cn_rej["success"] !== true) { 
            return $cn_rej;
        } 
        
        $hd_row = $cn_rej["hd_row"];
        $trans_no = $hd_row["trans_no"];
        
        begin_transaction();
        
            $ap_msg = send_back_to_document_originator($type, $trans_no, $hd_row['project_id'], $hd_row['next_approval_group_id'], $_SESSION['wa_current_user']->user, 
                                                       $hd_row['row_state'], $hd_row['created_by']);
                if ($ap_msg['success'] === false ) {
                    cancel_transaction();
                    return array("success" => false, "message" => $ap_msg['message']);
                }
            
        commit_transaction();

            set_session_variable('jmr_bo_messages', $ap_msg['message']);
            meta_forward($_SERVER['PHP_SELF'], "type=$type&BackedOrgID=$trans_no"); 
}

function clear_job_manual_cost_details() {
    unset($_POST['item_type']);
    unset($_POST['stock_id']);
    unset($_POST['item_description']);
    unset($_POST['tran_unit']);
    unset($_POST['tran_qty']);
    unset($_POST['site_id']);
    unset($_POST['line_comment']);
}

function view_job_manual_cost_header($type, $trans_no) {
    global $approval_statuses;
    
    $row = get_job_material_issue_header_type_trans_no($type, $trans_no);
    
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($row['project_id'], $user_id);
        if ($cap['success'] !== true) {
            display_error($cap["message"]);
            display_footer_exit();
            exit;
        }
    
        start_outer_table(TABLESTYLE2, "width=80%");

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

            table_section(2, "50%");
                label_row(_("Date:"), sql2date($row['tran_date']), "class='tableheader2'");
                label_row(_("Location:"), $row['location_name'], "class='tableheader2'");
                label_row(_("Total:"), $row['total'], "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);
        }
        
        return $row['id'];
}

function view_job_manual_cost_details($type, $trans_no) {
    global $daily_item_types_array;
    
    $hd_row = get_job_material_issue_header_type_trans_no($type, $trans_no);
    
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($hd_row['project_id'], $user_id);
        if ($cap['success'] !== true) {
            display_error($cap["message"]);
            display_footer_exit();
            exit;
        }
    
    start_table(TABLESTYLE, "width=95%");

        $th = array(_("ID"), _("Item Type"), _("Description"), _("Tran Unit"), _("Tran Qty"), _('Budget'), _("Unit Cost"), _('Line Cost'), _('Project Site'), _('Comment'));  
        table_header($th);

        $k = $total_cost = 0;
            $result = get_job_material_issue_details($trans_no, $type);      
                while ($row = db_fetch($result)) {
                    alt_table_row_color($k);

                        label_cell($row['trans_id'], 'align=center');
                        label_cell($daily_item_types_array[$row['item_type']]);
                        if (in_array($row['item_type'], array(NSIT_NON_STOCK_ITEM, NSIT_STOCK_ITEM))) {
                            label_cell($row["stock_id"]." - ".$row["item_description"]);  
                        } else {
                            label_cell($row["item_description"]);
                        }
                        label_cell($row["unit_name"]);
                        qty_cell($row["tran_qty"], false, 2);
                        label_cell($row["task_description"]);
                        $tran_unit_cost = $row["conversion_factor"] * $row["standard_cost"];
                            if ($tran_unit_cost > 0) {
                                qty_cell($tran_unit_cost, false, 2);
                            } else {
                                label_cell('');
                            }
                        $line_total = $tran_unit_cost * $row["tran_qty"];
                            if ($line_total > 0) {
                                qty_cell($line_total, false, 2);
                            } else {
                                label_cell('');
                            }
                        label_cell($row["site_description"]);          
                        label_cell(nl2br($row["line_comment"]));          

                    end_row(); 
                    
                    $total_cost += $line_total;
                }
                
                start_row();
                    label_cell(text_bold('Total'), 'align=right colspan=7');
                    if ($total_cost > 0) {
                        qty_cell($total_cost, true, 2);
                    } else {
                        label_cell('');
                    }
                    label_cell('', 'colspan=2');
                end_row();

    end_table(2);
}

function view_job_manual_cost_headers_by_jo_id($jo_id, $type, $width=70) {
    global $approval_statuses, $systypes_array;
    
    $jo_row = get_job_order_project_id($jo_id);
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($jo_row['project_id'], $user_id);
        if ($cap['success'] !== true) {
            display_error($cap["message"]);
            display_footer_exit();
            exit;
        }
    
    display_heading2($systypes_array[$type].'s');    br();
    
    start_table(TABLESTYLE, "width=$width%");

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

        $k = $total_cost = 0; 
            $result = get_job_material_issue_headers_by_filters($jo_id, 0, $type);      
                while ($row = db_fetch($result)) {
                    alt_table_row_color($k);
                        
                        label_cell(get_inventory_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['location_name']);
                        $jmc_total = $row['total'];
                        if ($jmc_total > 0) {
                            qty_cell($jmc_total, false, 2);
                        } else {
                            label_cell('');
                        }
                        label_cell($approval_statuses[$row['approval_status']], 'align=center');

                    end_row();  
                    
                    if ($row['approval_status'] != AS_REJECTED) {
                        $total_cost += $jmc_total;
                    }
                }
                
                start_row();
                    label_cell(text_bold('Total'), 'align=right colspan=5');
                    if ($total_cost > 0) {
                        qty_cell($total_cost, true, 2);
                    } else {
                        label_cell('');
                    }
                    label_cell('', 'colspan=1');
                end_row();

    end_table(2);
}

function view_job_manual_cost_return_headers_by_source($source_type, $source_trans_no, $width=80) {
    global $approval_statuses;
    
    $jmc_row = get_job_material_issue_header_record_type_trans_no($source_type, $source_trans_no);
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($jmc_row['project_id'], $user_id);
        if ($cap['success'] !== true) {
            display_error($cap["message"]);
            display_footer_exit();
            exit;
        }
        
        $jmc_no = $jmc_row['id'];
    
    start_table(TABLESTYLE, "width=$width%");

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

        $k = $total_cost = 0; 
            $result = get_job_material_issue_headers_by_filters(type: ST_JOB_MANUAL_COST_RETURN, source_id: $jmc_no);      
                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['location_name']);
                        $jmc_total = $row['total'];
                        if ($jmc_total > 0) {
                            qty_cell($jmc_total, false, 2);
                        } else {
                            label_cell('');
                        }
                        label_cell($approval_statuses[$row['approval_status']], 'align=center');

                    end_row();  
                    
                    if ($row['approval_status'] != AS_REJECTED) {
                        $total_cost += $jmc_total;
                    }
                }
                
                start_row();
                    label_cell(text_bold('Return Total'), 'align=right colspan=5');
                    if ($total_cost > 0) {
                        qty_cell($total_cost, true, 2);
                    } else {
                        label_cell('');
                    }
                    label_cell('', 'colspan=1');
                end_row();
                
    end_table(2);
}

?>