<?php

function display_job_order_header(&$jo_id, $p_jo_id=0) {
    global $Refs, $systypes_array;
    
    $user_id = $_SESSION['wa_current_user']->user;

        if ($jo_id > 0) {
            $jo_hd_row = get_job_order_record($jo_id);
                if (is_array($jo_hd_row)) {
                    if (! isset($_POST['parent_jo_id'])) {
                        $_POST['parent_jo_id'] = $jo_hd_row['parent_jo_id'];
                    }
                    if (! isset($_POST['jo_ref'])) {
                        $_POST['jo_ref'] = $jo_hd_row['jo_ref'];
                    }
                    if (! isset($_POST['date'])) {
                        $_POST['date'] = sql2date($jo_hd_row['date_']);
                    }
                    if (! isset($_POST['vehicle_id'])) {
                        $_POST['vehicle_id'] = $jo_hd_row['vehicle_id'];
                    }
                    if (! isset($_POST['req_department_id'])) {
                        $_POST['req_department_id'] = $jo_hd_row['req_department_id'];
                    }
                    if (! (isset($_POST['department_id']) && $_POST['department_id'] > 0)) {
                        $_POST['department_id'] = $jo_hd_row['department_id'];
                    }
                    if (! (isset($_POST['section_id']) && $_POST['section_id'] > 0)) {
                        $_POST['section_id'] = $jo_hd_row['section_id'];
                    }
                    if (! isset($_POST['engineer_code'])) {
                        $_POST['engineer_code'] = $jo_hd_row['engineer_code'];
                    }
                    if (! isset($_POST['tech_officer_code'])) {
                        $_POST['tech_officer_code'] = $jo_hd_row['tech_officer_code'];
                    }
                    if (! isset($_POST['customer_name'])) {
                        $_POST['customer_name'] = $jo_hd_row['customer_name'];
                    }
                    if (! isset($_POST['customer_address'])) {
                        $_POST['customer_address'] = $jo_hd_row['customer_address'];
                    }
                    if (! isset($_POST['next_job_owner_id'])) {
                        $_POST['next_job_owner_id'] = $jo_hd_row['next_job_owner_id'];
                    }
                    if (! (isset($_POST['next_job_owner_id']) && strlen($_POST['next_job_owner_id']) > 1)) {
                        $user_row = get_user($user_id);
                            if (isset($user_row['employee_code']) && strlen($user_row['employee_code']) > 1) {
                                $_POST['next_job_owner_id'] = $user_row['employee_code'];
                            }
                    }
                    if (! isset($_POST['instruction_id'])) {
                        $_POST['instruction_id'] = $jo_hd_row['instruction_id'];
                    }
                    if (! isset($_POST['job_accepted'])) {
                        $_POST['job_accepted'] = $jo_hd_row['job_accepted'];
                    }
                    if (! isset($_POST['job_completed'])) {
                        $_POST['job_completed'] = $jo_hd_row['job_completed'];
                    }
                    if (! isset($_POST['approval_status'])) {
                        $_POST['approval_status'] = $jo_hd_row['approval_status'];
                    }
                    if (! isset($_POST['hd_description'])) {
                        $_POST['hd_description'] = $jo_hd_row['description'];
                    }
                    if (! isset($_POST['service'])) {
                        $_POST['service'] = $jo_hd_row['service'];
                    }
                    
                    $p_jo_id = $jo_hd_row['parent_jo_id'];
                }
        }
        
        start_outer_table(TABLESTYLE2, "width=80%"); // outer table
            start_table(TABLESTYLE2);  
                table_section(1, "50%");
    
                    if (isset($jo_hd_row) && is_array($jo_hd_row) && $jo_hd_row['source_type'] == ST_SERVICE_COMPLAIN && $jo_hd_row['source_trans_no'] > 0) {
                        label_row($systypes_array[ST_SERVICE_COMPLAIN].' #:', get_service_trans_view_str(ST_SERVICE_COMPLAIN, $jo_hd_row['source_trans_no']));
                    }
                
                    if ($jo_id > 0) {
                        label_row('Job Card #:', get_service_trans_view_str(ST_JOB_ORDER, $jo_id));
                    } 
                    if ($p_jo_id > 0) {
                        label_row('Parent Job Card #:', get_service_trans_view_str(ST_JOB_ORDER, $p_jo_id));
                    }
                    ref_row(_("Reference:"), 'jo_ref', '', $Refs->get_next(ST_JOB_ORDER));
                    date_row('Job Date:', 'date');
                    
                    if ($p_jo_id > 0) {
                        $p_jo_hd = get_job_order_record($p_jo_id);
                            label_row('Vehicle/ Tool/ Project Location:', get_asset_formatted_name($p_jo_hd['vehicle_id']));
                            hidden('vehicle_id', $p_jo_hd['vehicle_id']);
                            label_row('Request Department:', get_listvalue_name_by_id($p_jo_hd['req_department_id']));
                            hidden('req_department_id', $p_jo_hd['req_department_id']);
                            
                            if (! (isset($_POST['customer_name']) && strlen($_POST['customer_name']) > 0)) {
                                $_POST['customer_name'] = $p_jo_hd['customer_name'];
                            }
                            if (! (isset($_POST['customer_address']) && strlen($_POST['customer_address']) > 0)) {
                                $_POST['customer_address'] = $p_jo_hd['customer_address'];
                            }
                            if (! (isset($_POST['hd_description']) && strlen($_POST['hd_description']) > 0)) {
                                $_POST['hd_description'] = $p_jo_hd['description'];
                            }
                    } else {
                        start_cell("colspan=2");
                            start_table();
                                asset_list_row('Vehicle/ Tool/ Job Location:'. spaces(23), 'vehicle_id');
                            end_table();
                        end_cell();
                        custom_values_list_row('Request Department:', 'req_department_id', create_request_departmens_array(), null, '', true);
                    }
                    
                    value_list_row('Department:', 'department_id', 'DEPARTMENTS', null, '', true);
                
                    $dep_row = get_listvalue_by_id($_POST['department_id']);
                        if (is_array($dep_row)) {
                            $section_list_code = $dep_row['value_code'];
                            value_list_row('Section:', 'section_id', "VMS_$section_list_code", null, '', true);
                        } else {
                            $_POST['section_id'] = 0;
                            hidden('section_id', 0);
                        }
                        
                    if (isset($jo_hd_row) && is_array($jo_hd_row)) {
                        $user = get_user($jo_hd_row['created_by']);
                        label_row("Issuing Officer (Job Office):", $user['real_name']);
                    } else {
                        label_row("Issuing Officer (Job Office):", $_SESSION['wa_current_user']->name);
                    } 
                    
                    employees_simple_list_row_2(_("Sectional Engineer:"), 'engineer_code', null, _(''), false, array("'ENGINEER'"));
                    employees_simple_list_row_2(_("Technical Officer:"), 'tech_officer_code', null, _(''), false, array("'TECHNICAL_OFFICER'", "'WORK_FIELD_SUPERVISO'"));
                    
                    if (isset($jo_hd_row) && is_array($jo_hd_row)) { 
                        check_row('Job Acceptance:', 'job_accepted', null);
                    }
                    
                table_section(2, "50%");  
                
                    text_row('Customer Name:', 'customer_name', null, 50, 300);
                    textarea_row('Customer Address:', 'customer_address', null, 50, 2);
                    textarea_row('Customer Complain/ Request:', 'hd_description', null, 50, 3);
                
                    if (isset($jo_hd_row) && is_array($jo_hd_row)) {
                        $style = '';
                        if ($jo_hd_row['next_job_owner_id'] != '') {
                            $aprv_row = get_users_by_filters($user_id, 0, $jo_hd_row['next_job_owner_id'], true);
                                if (! is_array($aprv_row)) {
                                    $style = "style=color:red";
                                }
                        }
                            
                        $current_owner_name = $current_instruction_name = '';    
                        if ($jo_hd_row['next_job_owner_id'] != 0 || strlen($jo_hd_row['next_job_owner_id']) > 2) {
                            $current_owner_name = get_employee_formatted_long_name($jo_hd_row['next_job_owner_id']);
                        }
                        label_row('Current Owner:', $current_owner_name, $style);
                        
                        start_cell("colspan=2");
                            start_table(false, 'align=left');
                                employee_search_list_row(_("Next Owner:"). spaces(23), 'next_job_owner_id', null, false, true);
                            end_table();
                        end_cell();
                        
                        if ($jo_hd_row['instruction_id'] > 0) {
                            $current_instruction_name = get_listvalue_name_by_id($jo_hd_row['instruction_id']);
                        }
                        label_row('Current Instruction:', $current_instruction_name);
                        value_list_row('Next Instruction:', 'instruction_id', 'JOB_INSTRUCTIONS', null, '', true);
                        custom_values_list_row("Approval Status:", "approval_status", job_order_approval_status_array(), null, false);
                        
                    } else {
                        hidden('next_job_owner_id', 0); $_POST['next_job_owner_id'] = 0;
                        hidden('instruction_id', 0);  $_POST['instruction_id'] = 0;
                        hidden('job_accepted', 0); $_POST['job_accepted'] = 0;
                        hidden('approval_status', 0); $_POST['approval_status'] = 0;
                    }
                    
                    check_row('Service:', 'service', null);
                    
                    if (isset($jo_hd_row) && is_array($jo_hd_row)) {
                        check_row('Work Complete:', 'job_completed', null);
                    } else {
                        hidden('job_completed', 0);
                    }
                    
        end_outer_table(2); // outer table
        
        start_table();
            submit_center_first('SAVE_JO_HEADER', 'Save Header', 'Save Job Card Header', false, ICON_SUBMIT);
            submit_center_last('Refresh', 'Refresh', 'Save Job Card Header', false, ICON_SUBMIT);        
        end_table(1);
}

function create_request_departmens_array() {
    $request_departmens_array = array();
    
        $result = get_all_list_values('REQ_DEPARTMENTS');
            while ($row = db_fetch($result)) {
                $request_departmens_array[$row['id']] = $row['value_name'];
            }
            
        $result_2 = get_all_list_values('DEPARTMENTS');
            while ($row = db_fetch($result_2)) {
                $request_departmens_array[$row['id']] = $row['value_name'];
            }
            
            return $request_departmens_array;
}

function job_order_approval_status_array($with_empty=false) {
    global $approval_statuses;
    
    $values_array = array();
    
        if ($with_empty === true) {
            $values_array[-1] = '';
        }
    
        $values_array[AS_NEW] = $approval_statuses[AS_NEW];
        $values_array[AS_AWAITING_APPROVAL] = $approval_statuses[AS_AWAITING_APPROVAL];
        $values_array[AS_APPROVED] = $approval_statuses[AS_APPROVED];
        $values_array[AS_CLOSED] = $approval_statuses[AS_CLOSED];
        $values_array[AS_ON_HOLD] = $approval_statuses[AS_ON_HOLD]; 
        $values_array[AS_RELEASED] = $approval_statuses[AS_RELEASED];
        $values_array[AS_AWAIT_FOR_MATERIAL] = $approval_statuses[AS_AWAIT_FOR_MATERIAL];
        $values_array[AS_AWAIT_FOR_LABOUR] = $approval_statuses[AS_AWAIT_FOR_LABOUR];
        $values_array[AS_AWAIT_FOR_LABOUR] = $approval_statuses[AS_AWAIT_FOR_LABOUR];
            
            return $values_array;
}

function display_job_order_tabs(&$Mode, &$selected_id, &$jo_id, $path_to_root, $state=true) {
    $jo_hd_row = get_job_order_record($jo_id);

    if (! is_array($jo_hd_row)){
        unset($_POST['_tabs_sel']); 
    }

        tabbed_content_start('tabs', array (
            'jo_activity' => array(_('&Activity'), $jo_hd_row),
            'jo_repair' => array(_('&Repair'), $jo_hd_row),
            'jo_material' => array(_('&Material Requisitions'), $jo_hd_row),
            'jo_personal_material' => array(_('&Personal Material'), $jo_hd_row),
            'jo_outside_material' => array(_('&Outside Material'), $jo_hd_row),
            'jo_direct_purchase_req' => array(_('&Purchase'), $jo_hd_row),
            'jo_material_list' => array(_('&Material List/ Estimate'), $jo_hd_row),
            'jo_labour' => array(_('&Labour'), $jo_hd_row),
            'jo_sub_job' => array(_('&Sub Job'), $jo_hd_row),
            'jo_salvage' => array(_('&Salvage Return'), $jo_hd_row),  
            'jo_manual_cost' => array(_('&Manual Cost'), $jo_hd_row) 
        ));
        
	switch (get_post('_tabs_sel')) {
            case 'jo_repair':    
                include_once($path_to_root."/services/includes/db/job_order_repairs_db.inc"); 
                include_once($path_to_root."/services/includes/ui/job_order_repairs_ui.inc"); 
                
                job_order_repairs($Mode, $selected_id, $jo_id, $state); 
                break;
            
            case 'jo_material_list':    
                include_once($path_to_root."/inventory/includes/db/material_lists_db.inc"); 
                include_once($path_to_root."/inventory/includes/ui/material_lists_ui.inc"); 
                include_once($path_to_root."/includes/ui/db_pager_view.inc"); 
                
                job_material_lists($jo_id); 
                break;
            
            case 'jo_material':
                include_once($path_to_root."/inventory/includes/db/job_material_requisitions_db.inc"); 
                include_once($path_to_root."/services/includes/ui/job_order_materials_ui.inc"); 
                include_once($path_to_root."/includes/common_functions.inc"); 
                
                job_order_materials($jo_id); 
                break;
            
            case 'jo_personal_material':
                include_once($path_to_root."/inventory/includes/db/job_material_issues_db.inc"); 
                include_once($path_to_root."/inventory/includes/ui/personal_material_issues_ui.inc"); 
                include_once($path_to_root."/includes/common_functions.inc"); 
                
                job_order_personal_materials($jo_id); 
                break;
            
            case 'jo_outside_material':
                include_once($path_to_root."/inventory/includes/db/outside_material_requisitions_db.inc"); 
                include_once($path_to_root."/inventory/includes/ui/outside_material_requisitions_ui.inc"); 
                include_once($path_to_root."/includes/common_functions.inc"); 
                
                job_order_outside_materials($jo_id); 
                break;
            
            case 'jo_direct_purchase_req':
                include_once($path_to_root."/purchasing/includes/db/direct_purchase_requisitions_db.inc"); 
                include_once($path_to_root."/purchasing/includes/ui/direct_purchase_requisitions_ui.inc"); 
                
                job_direct_purchase_requisitions($jo_id); 
                break;
            
            case 'jo_labour':
                include_once($path_to_root."/services/includes/db/job_order_labours_db.inc"); 
                include_once($path_to_root."/services/includes/ui/job_order_labours_ui.inc"); 
                include_once($path_to_root."/includes/common_functions.inc"); 
                include_once($path_to_root . "/payroll/includes/db/employee_rate_categories_db.inc");
                
                job_order_labours($Mode, $selected_id, $jo_id, $state); 
                break;
            
            case 'jo_sub_job':
                include_once($path_to_root."/services/includes/ui/job_order_sub_jobs_ui.inc"); 
                
                job_order_sub_jobs($jo_id); 
                break;
            
            case 'jo_activity':
                include_once($path_to_root."/services/includes/db/job_activities_db.inc"); 
                include_once($path_to_root."/services/includes/ui/job_activities_ui.inc"); 
                include_once($path_to_root."/includes/db_pager.inc");
                
                job_activities($jo_id, 95);
                break;
            
            case 'jo_salvage':
                include_once($path_to_root."/inventory/includes/db/job_material_issues_db.inc"); 
                include_once($path_to_root."/services/includes/ui/job_order_salvage_returns_ui.inc"); 
                
                job_order_salvages($jo_id); 
                break;
            
            case 'jo_manual_cost':
                include_once($path_to_root."/inventory/includes/db/job_material_issues_db.inc"); 
                include_once($path_to_root."/services/includes/ui/job_order_manual_costs_ui.inc"); 
                
                job_order_manual_costs($jo_id); 
                break;
	}
        
    br();
    tabbed_content_end();
}

function can_save_job_order_header(&$jo_id, $p_jo_id=0) {  
    global $Refs, $systypes_array, $asset_statuses;
    
    $trn_type_name = $systypes_array[ST_JOB_ORDER];
    $user_id = $_SESSION['wa_current_user']->user;
    
    $p_row_state = $row_state = 0;
    if ($p_jo_id > 0) {
        $p_jo_hd = get_job_order_record($p_jo_id);
            if (! is_array($p_jo_hd)) {
                return array('success' => false, 'message' => "Could not find parent $trn_type_name #$jo_id.");
            } elseif ($p_jo_hd['parent_jo_id'] > 0) {
                return array('success' => false, 'message' => "$trn_type_name #$p_jo_id is a sub job. Sub job cannot create any sub job.");
            } elseif ($p_jo_hd['closed'] == 1) {
                return array('success' => false, 'message' => "Parent $trn_type_name #$jo_id is already closed. Not allow to further update.");
            } elseif ($p_jo_hd['released'] == 1) {
                return array('success' => false, 'message' => "Parent $trn_type_name #$jo_id is already released. Not allow to further update.");
            }
            
            $p_row_state = $p_jo_hd['row_state'];   
    }
    
    $jo_hd_row = get_job_order_record($jo_id);
        if (is_array($jo_hd_row)) {
            if ($jo_hd_row['closed'] == 1) {
                return array('success' => false, 'message' => "$trn_type_name header #$jo_id is already closed. Not allow to further update.");
            } elseif ($jo_hd_row['released'] == 1) {
                return array('success' => false, 'message' => "$trn_type_name header #$jo_id is already released. Not allow to further update.");
            }
            
            // current job owner permission check before saving
            if (strlen($jo_hd_row['next_job_owner_id']) > 0) {
                $user_row = get_user($user_id);
                    if ($user_row['employee_code'] == '') {
                        $system_user = $user_row['real_name'];
                        return array('success' => false, 
                                     'message' => "Loged in system user $system_user is not assigned to any employee in the company. Please contact system administrator.");
                    }
                $owner_row = get_users_by_filters($user_id, 0, $jo_hd_row['next_job_owner_id'], true);
                    if (! is_array($owner_row)) {
                        return array('success' => false, 'message' => "Not allow to update job #$jo_id because you are not the current owner of the job.");
                    }
            }
            
            $row_state = $jo_hd_row['row_state'];
        }
      
    if (! $Refs->is_valid($_POST['jo_ref'], ST_JOB_ORDER)){
        return array("success" => false, "focus_to" => 'jo_ref', "message" => "Please enter a reference.");      
    }    
 
    $ref_msg = reference_exists($_POST['jo_ref'], ST_JOB_ORDER, $jo_id);
        if ($ref_msg) {
            return array("success" => false, "focus_to" => 'jo_ref', "message" => $ref_msg);
        }
              
    if (! is_date($_POST['date'])) {
        return array("success" => false, "focus_to" => 'date', "message" => "Job date entered is not a valid date.");        
    }
    
    if (isset($_POST['vehicle_id'])) {
        $asset_row = get_asset($_POST['vehicle_id']);
            if (! is_array($asset_row)) {
                return array("success" => false, "focus_to" => 'vehicle_id', "message" => "Please select a vehicle/ tool/ project location.");        
            } elseif (in_array($asset_row['type'], array(AT_TOOL, AT_VEHICLE)) && $asset_row['status'] != AST_SERVICEABLE) {
                $asset_status = $asset_statuses[$asset_row['status']];
                return array("success" => false, "focus_to" => 'vehicle_id', 
                             "message" => "Cannot create a job card for $asset_status vehicle/ tool. Please contact system administrator.");        
            }
    } else {
        return array("success" => false, "focus_to" => 'vehicle_id', "message" => "Please select a vehicle/ tool/ project location.");        
    }
        
    if (! isset($_POST['req_department_id']) || ! ($_POST['req_department_id'] > 0)) {
        return array("success" => false, "focus_to" => 'req_department_id', "message" => "Please select a request department.");        
    }
        
    if (! isset($_POST['department_id']) || ! ($_POST['department_id'] > 0)) {
        return array("success" => false, "focus_to" => 'department_id', "message" => "Please select a department.");        
    }
    
    if (isset($jo_hd_row['id']) && $jo_hd_row['id'] > 0 && $jo_hd_row['department_id'] != $_POST['department_id']) {
        $has_trans = check_job_order_has_transactions($jo_id);
            if ($has_trans['has_trans'] === true) {
                return array("success" => false, "focus_to" => 'department_id', "message" => $has_trans['message']);  
            }
    }
        
    if (! isset($_POST['section_id']) || ! ($_POST['section_id'] > 0)) {
        return array("success" => false, "focus_to" => 'section_id', "message" => "Please select a section.");        
    }
        
    if ($_POST['engineer_code'] == 0) {
        return array("success" => false, "focus_to" => 'engineer_code', "message" => "Please select a sectional engineer.");        
    }
        
    if ($_POST['tech_officer_code'] == 0) {
        return array("success" => false, "focus_to" => 'tech_officer_code', "message" => "Please select a technical officer.");        
    }
    
    if (! (strlen($_POST['hd_description']) > 10)) {
        return array("success" => false, "focus_to" => 'hd_description', "message" => "Customer Complain/ Request Cannot empty and length should more than 10 letters.");        
    }
    
    if (is_array($jo_hd_row) && strlen($jo_hd_row['next_job_owner_id']) > 2) {
        if (! isset($_POST['next_job_owner_id']) || $_POST['next_job_owner_id'] == 0) {
            return array("success" => false, "focus_to" => 'next_job_owner_id', "message" => "Please select a next owner.");        
        }
    }
            
    return array("success" => true, 'row_state' => $row_state, "message" => "", "jo_hd_row" => $jo_hd_row, 'p_row_state' => $p_row_state);    
}

function save_next_job_owner($jo_id, $new_nx_jb_ow_id, $row_state, $editable=0, $instruction_id=0) {
    $new_ow_name = get_employee_formatted_long_name($new_nx_jb_ow_id);
        
        $description = "Job owner is changed to '$new_ow_name'.";
        
    $instruct = '';
    if ($instruction_id > 0) {
        $instruct = get_listvalue_name_by_id($instruction_id);
        $description .= "\n Instruction: $instruct.";
    }

        $jat_row = get_listvalue_by_code('JOB_ACTIVITY_TYPES', 'NEXT_JOB_OWNER');
        $activity_type_id = $jat_row['id'];

            $msg = add_job_activity($jo_id, $row_state, $activity_type_id, Today(), $description, $editable, $new_nx_jb_ow_id, ST_JOB_ORDER, $jo_id);
                if ($msg['success'] === false) {
                    return array("success" => false, "message" => "Could not add job activity: next owner log record.");    
                } 

            $new_row_state = db_new_row_state($row_state);
            $af_row = update_job_order_next_approval_state($jo_id, $new_nx_jb_ow_id, $new_row_state);
                if (! ($af_row > 0)) {
                    return array("success" => false, "message" => "Could not update job next owner state.");    
                } 
                
            $nw_rw_state = db_new_row_state($new_row_state);

            return array("success" => true, "message" => "New job next owner log record has been added.", 'row_state' => $nw_rw_state);    
}

function save_job_acceptance($jo_id, $job_accepted, $row_state, $editable=0) {
    $description = "System generated log record: job #$jo_id is not accepted.";
        if ($job_accepted == 1) {
            $description = "System generated log record: job #$jo_id is accepted.";
        } 

        $jat_row = get_listvalue_by_code('JOB_ACTIVITY_TYPES', 'JOB_ACCEPTANCE');
        $activity_type_id = $jat_row['id'];

            $msg = add_job_activity($jo_id, $row_state, $activity_type_id, Today(), $description, $editable, '', -1, 0);
                if ($msg['success'] === false) {
                    return array("success" => false, "message" => "Could not add job activity: job acceptance log record.");    
                } 

            $new_row_state = db_new_row_state($row_state);
            $af_row = update_job_order_job_acceptance_state($jo_id, $job_accepted, $new_row_state);
                if (! ($af_row > 0)) {
                    return array("success" => false, "message" => "Could not update job acceptance state.");    
                } 
                
            $nw_rw_state = db_new_row_state($new_row_state);

            return array("success" => true, "message" => "New job acceptance log record has been added.", 'row_state' => $nw_rw_state);    
}

function save_job_complete($jo_id, $job_completed, $row_state, $editable=0) {
    $description = "System generated log record: job #$jo_id is not completed.";
        if ($job_completed == 1) {
            $description = "System generated log record: job #$jo_id is completed.";
        } 

        $jat_row = get_listvalue_by_code('JOB_ACTIVITY_TYPES', 'JOB_COMPLETE');
        $activity_type_id = $jat_row['id'];

            $msg = add_job_activity($jo_id, $row_state, $activity_type_id, Today(), $description, $editable, '', -1, 0);
                if ($msg['success'] === false) {
                    return array("success" => false, "message" => "Could not add job activity: job complete log record.");    
                } 

            $new_row_state = db_new_row_state($row_state);
            $af_row = update_job_order_job_complete_state($jo_id, $job_completed, $new_row_state);
                if (! ($af_row > 0)) {
                    return array("success" => false, "message" => "Could not update job complete state.");    
                } 

            $nw_rw_state = db_new_row_state($new_row_state);
            
            return array("success" => true, "message" => "New job complete log record has been added.", 'row_state' => $nw_rw_state); 
}

function handle_save_job_order_header(&$jo_id, &$row_state=0, $p_jo_id=0, $recommend=0) {
    global $path_to_root, $approval_statuses;
    
    $msg = can_save_job_order_header($jo_id, $p_jo_id);   
        if ($msg['success'] === false) {
            return $msg;
        }
    
    $p_row_state = $msg['p_row_state'];
    $row_state = $msg['row_state'];
    $old_jo_hd_row = $msg['jo_hd_row'];
    
    include_once($path_to_root."/services/includes/db/job_activities_db.inc"); 
    include_once($path_to_root."/services/includes/ui/job_activities_ui.inc"); 
    
    if (! isset($_POST['service']) || $_POST['service'] == '') {
        $_POST['service'] = 0;
    }
    
    begin_transaction();
    
        if ($jo_id > 0) { 
            $instruction_id = $_POST['instruction_id']; 
            $msg = update_job_order($jo_id, $_POST['jo_ref'], $_POST['date'], $_POST['vehicle_id'], $_POST['req_department_id'], $_POST['department_id'], $_POST['section_id'], 
                                    $_POST['engineer_code'], $_POST['tech_officer_code'], $_POST['customer_name'], $_POST['customer_address'], $instruction_id, 
                                    $_POST['hd_description'], $_POST['approval_status'], $_POST['service'], $row_state); 
                if ($msg['success'] === false) {
                    cancel_transaction();
                    return $msg;
                } 
                
            $rdp_msg = update_all_sub_job_orders_request_department($jo_id, $_POST['req_department_id']); 
                if ($rdp_msg['success'] === false) {
                    cancel_transaction();
                    return $rdp_msg;
                } 
                
            $next_job_owner_id = isset($_POST['next_job_owner_id']) ? $_POST['next_job_owner_id'] : '';
            $emp_row = get_employee($next_job_owner_id);
            if (is_array($emp_row)) {
                if ($old_jo_hd_row['next_job_owner_id'] != $next_job_owner_id) {
                    $jc_msg = save_next_job_owner($jo_id, $next_job_owner_id, $row_state, 0, $instruction_id);
                        if ($jc_msg['success'] === false) {
                            cancel_transaction();
                            return $jc_msg;
                        } 

                        $row_state = $jc_msg['row_state'];
                }
            }
                
            $job_accepted = get_boolean_post_value('job_accepted');
            
            if ($old_jo_hd_row['job_accepted'] != $job_accepted) {
                $jc_msg = save_job_acceptance($jo_id, $job_accepted, $row_state, 0);
                    if ($jc_msg['success'] === false) {
                        cancel_transaction();
                        return $jc_msg;
                    } 
                    
                    $row_state = $jc_msg['row_state'];
            }
                  
            $job_completed = get_boolean_post_value('job_completed');
            
            if ($old_jo_hd_row['job_completed'] != $job_completed) {
                $jc_msg = save_job_complete($jo_id, $job_completed, $row_state, 0);
                    if ($jc_msg['success'] === false) {
                        cancel_transaction();
                        return $jc_msg;
                    } 
                    
                    $row_state = $jc_msg['row_state'];
            }
            
            if ($old_jo_hd_row['approval_status'] != $_POST['approval_status']) {
                $pre_ap_st = $approval_statuses[$old_jo_hd_row['approval_status']];
                $new_ap_st = $approval_statuses[$_POST['approval_status']];
                $text = "Job card approval status changed from $pre_ap_st to $new_ap_st.";
                $ap_msg = save_job_activity_log($jo_id, 'CHANGE_APPROVAL_STAT', $text, $row_state, 0);
                    if ($ap_msg['success'] === false) {
                        cancel_transaction();
                        return $ap_msg;
                    } 
            }
            
            $message = "Job card header record #$jo_id has been updated.";
                
        } else {
            
            $next_job_owner_id = '';
            $user_id = $_SESSION['wa_current_user']->user;
            $aprv_row = get_users_by_filters($user_id, 0, 0, true);
                if (strlen($aprv_row['employee_code']) > 1) {
                    $next_job_owner_id = $aprv_row['employee_code'];
                } else {
                    return array('success' => false, 'message' => "Employee not defined for the current logon user.");
                }
            $msg = add_job_order($jo_id, $_POST['jo_ref'], $_POST['date'], $_POST['vehicle_id'], $_POST['req_department_id'], $_POST['department_id'], $_POST['section_id'], 
                                 $_POST['engineer_code'], $_POST['tech_officer_code'], $_POST['customer_name'], $_POST['customer_address'], $_POST['hd_description'], $p_jo_id, 
                                 -1, 0, $next_job_owner_id, 0, $_POST['service']);
                if ($msg['success'] === false) {
                    cancel_transaction();
                    return $msg;
                } 
                
            $sub = '';   
            if ($p_jo_id > 0) {    
                $sub_msg = save_job_activity_log($jo_id, 'SUB_JOB', "Sub job #$jo_id is created.", $row_state, 0, $p_jo_id, $p_row_state);
                    if ($sub_msg['success'] === false) {
                        cancel_transaction();
                        $jo_id = -1;
                        return $sub_msg;
                    } 
                    
                $sub = 'sub';
            }
            
            $message = "New $sub job card header record #$jo_id has been added.";
        }

            $last_srvc_row = get_job_order_vehicle_tool_last_service($_POST['vehicle_id'], 0, 0, null, 'date_ DESC', 1, true);
                if (is_array($last_srvc_row)) {
                    if ($_POST['service'] == 1 && date1_greater_date2($_POST['date'], sql2date($last_srvc_row['date_']))) {
                        $last_service_date = $_POST['date'];
                    } else {
                        $last_service_date = sql2date($last_srvc_row['date_']);
                    }
                } else {
                    $last_service_date = sql2date(INFINITE_START_DATE);
                }

            update_asset_last_service_date($_POST['vehicle_id'], $last_service_date);

            commit_transaction();

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

function clear_job_order_inputs(&$selected_id) {
    $input_array = array('description', 'stock_id', 'employee_code', 'num_days_worked');
    
        foreach ($input_array as $input) {
            unset($_POST["$input"]);
        }
        
        $_POST["from_date"] = $_POST["to_date"] = $_POST["act_date"] = Today();

        $selected_id = -1;
        unset($_POST['selected_id']);
        hidden('selected_id', -1);
}

function view_job_order_header($jo_id) {
    global $approval_statuses, $systypes_array;
    
    $row = get_job_order_details($jo_id);
    
    if (! (isset($row['id']) && $row['id'] > 0)) {
        display_note(("Unknown Job Card #$jo_id."), 1, 1);
        display_footer_exit();
    }

        start_outer_table(TABLESTYLE2);

            table_section(1, "50%");
                if ($row['source_type'] == ST_SERVICE_COMPLAIN && $row['source_trans_no'] > 0) {
                    label_row($systypes_array[ST_SERVICE_COMPLAIN].':', get_service_trans_view_str(ST_SERVICE_COMPLAIN, $row['source_trans_no']), "class='tableheader2'");
                }
                if ($row['parent_jo_id'] > 0) {
                    label_row('Parent Job Card #:', get_service_trans_view_str(ST_JOB_ORDER, $row['parent_jo_id']), "class='tableheader2'");
                }
                label_row('Reference:', $row['jo_ref'], "class='tableheader2'");
                label_row('Date:', sql2date($row['date_']), "class='tableheader2'");
                label_row('Vehicle/ Tool/ Project Location:', get_asset_formatted_name($row['vehicle_id']), "class='tableheader2'");
                label_row('Request Department:', $row['req_department_name'], "class='tableheader2'");
                label_row('Department:', $row['department_name'], "class='tableheader2'");
                label_row('Section:', $row['section_name'], "class='tableheader2'");
                if (strlen($row['issuing_officer_emp_code']) > 2) {
                    label_row('Issuing Officer (Job Office):', get_employee_formatted_long_name($row['issuing_officer_emp_code']), "class='tableheader2'");
                } else {
                    label_row('Issuing Officer (Job Office):', $row['issuing_officer'], "class='tableheader2'");
                }
                label_row('Sectional Engineer:', get_employee_formatted_long_name($row['engineer_code']), "class='tableheader2'");
                label_row('Technical Officer:', get_employee_formatted_long_name($row['tech_officer_code']), "class='tableheader2'");

            table_section(2, "50%");
                label_row('Customer Name:', $row['customer_name'], "class='tableheader2'");
                label_row('Customer Address:', $row['customer_address'], "class='tableheader2'");
                label_row('Current Owner:', get_employee_formatted_long_name($row['next_job_owner_id']), "class='tableheader2'");
                label_row('Instruction:', $row['instruction_name'], "class='tableheader2'");
                label_row('Job Accepted:', $row['job_accepted'] == 1 ? 'Yes' : 'No', "class='tableheader2'");
                label_row('Approval Status:', $approval_statuses[$row['approval_status']], "class='tableheader2'");
                label_row('Work Completed:', $row['job_completed'] == 1 ? 'Yes' : 'No', "class='tableheader2'");
                label_row('Service:', $row['service'] == 1 ? 'Yes' : 'No', "class='tableheader2'");
                if ($row['service'] == 1) {
                    label_row('Last Service Date:', sql2date($row['last_service_date']), "class='tableheader2'");
                }

        end_outer_table(2);
    
        if (strlen($row['description']) > 0) {
            start_table(TABLESTYLE2);
                label_row(_("Customer Complain/ Request:"), nl2br($row['description']), "class='tableheader2'");
            end_table(2);
        }
}

function display_job_orders_view($from_date_=null, $to_date_=null, $vehicle_id=0, $req_department_id=0, $department_id=0, $section_id=0, $engineer_code=0, 
                                 $tech_officer_code=0, $next_job_owner_id=0, $job_completed=null, $approval_status=-1) {
    global $approval_statuses;
    
    start_table(TABLESTYLE, "width=99%");
        
        $th = array(_("Job #"), _("Comp./Req.#"), _("Complain/<br>Request"), _("Parent"), _("Reference"), _("Vehicle/ Tool/ Location"), _("Date"), _("Request<br>Department"), 
                    _("Department"), _("Section"), _("Sectional<br>Engineer"), _("Current<br>Owner"), _("Job Cost"), _("Work Complete"), _("Approval Status"));
        table_header($th);
    
            $k = $jobs_total = $total_jobs_count = $total_completed_jobs_count = 0;  
            $result = get_job_order_details_by_filters(from_date_: $from_date_, to_date_: $to_date_, vehicle_id: $vehicle_id, req_department_id: $req_department_id, 
                                                       department_id: $department_id, section_id: $section_id, engineer_code: $engineer_code, 
                                                       tech_officer_code: $tech_officer_code, next_job_owner_id: $next_job_owner_id, job_completed: $job_completed, 
                                                       approval_status: $approval_status);
                while ($row = db_fetch($result)) {
                    alt_table_row_color($k);

                        $jo_id = $row['id'];
                        label_cell(get_service_trans_view_str(ST_JOB_ORDER, $jo_id), 'align=center');
                        if ($row['source_type'] == ST_SERVICE_COMPLAIN && $row['source_trans_no'] > 0) {
                            label_cell(get_service_trans_view_str(ST_SERVICE_COMPLAIN, $row['source_trans_no']), 'align=center');
                        } else {
                            label_cell('');
                        }
                        label_cell(nl2br($row['description']));
                        if ($row['parent_jo_id'] > 0) {
                            label_cell(get_service_trans_view_str(ST_JOB_ORDER, $row['parent_jo_id']), 'align=center');
                        } else {
                            label_cell('');
                        }
                        label_cell($row['jo_ref']);
                        label_cell(get_asset_formatted_name($row["vehicle_id"]));
                        label_cell(sql2date($row['date_']), 'align=center');
                        label_cell($row['req_department_name']);
                        label_cell($row['department_name']);
                        label_cell($row['section_name']);
                        label_cell(get_employee_formatted_long_name($row['engineer_code']));
                        label_cell(get_employee_formatted_long_name($row['next_job_owner_id']));
                        $job_cost = get_job_order_cost($jo_id);
                        qty_cell($job_cost, false, 2);
                        label_cell(get_yes_no_name($row['job_completed']), 'align=center');
                        label_cell($approval_statuses[$row['approval_status']], 'align=center');

                    end_row();
                    
                    if ($row['job_completed'] == 1) {
                        $total_completed_jobs_count++;
                    }
                    
                    $jobs_total += $job_cost;
                    $total_jobs_count++;
                }
                
                start_row();
                    label_cell(text_bold($total_jobs_count), "align=center");
                    label_cell(text_bold('Total Count'), "align=center colspan=12");
                    label_cell(text_bold($total_completed_jobs_count), "align=center");
                end_row();

    end_table(2);
}

?>