<?php

function display_service_complain_header(&$cmp_id) {
    global $Refs;
    
        if ($cmp_id > 0) {
            $cm_row = get_service_complain_record($cmp_id);
                if (is_array($cm_row)) {
                    if (! isset($_POST['ref'])) {
                        $_POST['ref'] = $cm_row['ref'];
                    }
                    if (! isset($_POST['date'])) {
                        $_POST['date'] = sql2date($cm_row['date_']);
                    }
                    if (! isset($_POST['vehicle_id'])) {
                        $_POST['vehicle_id'] = $cm_row['vehicle_id'];
                    }
                    if (! isset($_POST['req_department_id'])) {
                        $_POST['req_department_id'] = $cm_row['req_department_id'];
                    }
                    if (! isset($_POST['customer_name'])) {
                        $_POST['customer_name'] = $cm_row['customer_name'];
                    }
                    if (! isset($_POST['customer_address'])) {
                        $_POST['customer_address'] = $cm_row['customer_address'];
                    }
                    if (! isset($_POST['description'])) {
                        $_POST['description'] = $cm_row['description'];
                    }
                    if (! isset($_POST['booking'])) {
                        $_POST['booking'] = $cm_row['booking'];
                    }
                    if (! isset($_POST['schedule_date'])) {
                        $_POST['schedule_date'] = sql2date($cm_row['schedule_date']);
                    }
                    if (! isset($_POST['close_description'])) {
                        $_POST['close_description'] = $cm_row['close_description'];
                    }
                }
        }
        
        start_outer_table(TABLESTYLE2, "width=85%"); // outer table
            start_table(TABLESTYLE2);  
                table_section(1, "50%");
    
                    if ($cmp_id > 0) {
                        label_row('Complain/ Request #:', get_service_trans_view_str(ST_SERVICE_COMPLAIN, $cmp_id));
                    } 
                    ref_row(_("Reference:"), 'ref', '', $Refs->get_next(ST_SERVICE_COMPLAIN));
                    date_row('Date:', 'date');
                    
                    start_cell("colspan=2");
                        start_table(false, 'align=left');
                            asset_list_row('Vehicle/ Tool/ Job Location:', 'vehicle_id');
                        end_table();
                    end_cell();
                    custom_values_list_row('Request Department:', 'req_department_id', create_request_departmens_array(), null, '', true);
                    
                    two_value_list_row('Booking:', 'booking', null, 'Yes', 'No', '1', '0', true);
                    if ($_POST['booking'] == 1) {
                        date_row('Schedule Date:', 'schedule_date');
                    } else {
                        $_POST['schedule_date'] = Today();
                        hidden('schedule_date', Today());
                    }
                    
                table_section(2, "50%");  
                    
                    text_row('Customer Name:', 'customer_name', null, 50, 300);
                    textarea_row('Customer Address:', 'customer_address', null, 50, 3);
                    textarea_row('Complain/ Request Details:', 'description', null, 50, 3);
                    
                    if ($cmp_id > 0) {
                        textarea_row('Close Details:', 'close_description', null, 50, 3);
                    } else {
                        $_POST['close_description'] = '';
                        hidden('close_description', '');
                    }
                    
                    if (isset($cm_row) && is_array($cm_row)) {
                        $user = get_user($cm_row['created_by']);
                        label_row("Issuing Officer:", $user['real_name']);
                    } else {
                        label_row("Issuing Officer:", $_SESSION['wa_current_user']->name);
                    }
                    
        end_outer_table(2); // outer table
}

function display_service_complain_job_header() {
    start_outer_table(TABLESTYLE2, "width=70%"); // outer table
        start_table(TABLESTYLE2);  
            table_section(1, "50%");

                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);
                    }
                    
                if (! isset($_POST['next_job_owner_id'])) {
                    $user_row = get_user($_SESSION['wa_current_user']->user);
                    $_POST['next_job_owner_id'] = $user_row['employee_code'];
                }
                    
                start_cell("colspan=2");
                    start_table(false, 'align=left');
                        employee_search_list_row(_("Next Job Card Owner:"). spaces(12), 'next_job_owner_id', null, false, true);
                    end_table();
                end_cell();

            table_section(2, "50%");  

                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'"));

    end_outer_table(2); // outer table
}

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 can_save_service_complain_header(&$cmp_id, $create_job=false) {  
    global $Refs, $systypes_array;
    
    $type = ST_SERVICE_COMPLAIN;
    $trn_type_name = $systypes_array[$type];
    
    $row_state = 0;
    $cm_row = get_service_complain_record($cmp_id);
        if (is_array($cm_row)) {
            if ($cm_row['closed'] == 1) {
                return array('success' => false, 'message' => "$trn_type_name #$cmp_id has already closed. Not allow to further update.");
            }
            $job_row = get_job_orders_by_source($type, $cmp_id, true);
                if (is_array($job_row)) {
                    $jo_id = $job_row['id'];
                    return array('success' => false, 'message' => "$trn_type_name #$cmp_id has already created job card #$jo_id. Not allow to create a new job card.");
                }
                
            $row_state = $cm_row['row_state'];
        }
      
    if (! $Refs->is_valid($_POST['ref'], $type)){
        return array("success" => false, "focus_to" => 'ref', "message" => "Please enter a reference.");      
    }    
 
    $ref_msg = is_new_reference($_POST['ref'], $type, $cmp_id);
        if ($ref_msg === false) {
            $next_ref = $Refs->get_next($type);
            return array("success" => false, "focus_to" => 'ref', "message" => "Entered reference is already used. Next reference is $next_ref.");      
        }
              
    if (! is_date($_POST['date'])) {
        return array("success" => false, "focus_to" => 'date', "message" => "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/ job location.");        
            }
    } else {
        return array("success" => false, "focus_to" => 'vehicle_id', "message" => "Please select a vehicle/ tool/ job 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 ($_POST['booking'] == 1) {
        if (! is_date($_POST['schedule_date'])) {
            return array("success" => false, "focus_to" => 'schedule_date', "message" => "Schedule date is not valid date."); 
        }
        if (date1_greater_date2(Today(), $_POST['schedule_date'])) {
            return array("success" => false, "focus_to" => 'schedule_date', "message" => "Schedule date cannot smaller than today."); 
        }
    }
        
    if (! (strlen($_POST['description']) > 5)) {
        return array("success" => false, "focus_to" => 'description', 
                     "message" => "$trn_type_name details should contain more than 15 characters.");        
    }
    
        if ($create_job === true) {
            if (! isset($_POST['department_id']) || ! ($_POST['department_id'] > 0)) {
                return array("success" => false, "focus_to" => 'department_id', "message" => "Please select a department.");        
            }

            if (! isset($_POST['section_id']) || ! ($_POST['section_id'] > 0)) {
                return array("success" => false, "focus_to" => 'section_id', "message" => "Please select a section.");        
            }
            
            if (isset($_POST['next_job_owner_id'])) {
                $emp_row = get_employee($_POST['next_job_owner_id']);
                    if (! is_array($emp_row)) {
                        return array('success' => false, "focus_to" => 'next_job_owner_id', 'message' => _("Please select a next job card owner."));
                    }
            } else {
                return array('success' => false, "focus_to" => 'next_job_owner_id', 'message' => _("Please select a next job card owner."));
            }

            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.");        
            }
        }
            
        return array("success" => true, 'row_state' => $row_state, "message" => "", "cm_row" => $cm_row);    
}

function handle_save_service_complain_header(&$cmp_id, &$row_state=0, $create_job=false) {
    global $systypes_array, $Refs;
    
    $msg = can_save_service_complain_header($cmp_id, $create_job);   
        if ($msg['success'] === false) {
            return $msg;
        }
    
    $row_state = $msg['row_state'];
    
    $type = ST_SERVICE_COMPLAIN;
    $trn_type_name = $systypes_array[$type];
    
    $added_updated = 'added';
    
    $tran_no = $cmp_id;
    
    if ($_POST['booking'] == 0) {
        $_POST['schedule_date'] = sql2date(INFINITE_START_DATE);
    }
    
    begin_transaction();
    
        if ($cmp_id > 0) { 
            $added_updated = 'updated';
            
            $af_rw = update_service_complain($cmp_id, $_POST['ref'], $_POST['date'], $_POST['vehicle_id'], $_POST['req_department_id'], $_POST['customer_name'], 
                                             $_POST['customer_address'], $_POST['description'], $_POST['booking'], $_POST['schedule_date'], $row_state); 
                if ($af_rw != 1) {
                    cancel_transaction();
                    return array('success' => false, 'message' => "Could not update $trn_type_name #$cmp_id.");
                } 

                $row_state = db_new_row_state($row_state);
            
        } else {
            
            $msg = add_service_complain($_POST['ref'], $_POST['date'], $_POST['vehicle_id'], $_POST['req_department_id'], $_POST['customer_name'], $_POST['customer_address'], 
                                        $_POST['description'], $_POST['booking'], $_POST['schedule_date']);
                if ($msg['success'] === false) {
                    cancel_transaction();
                    return array('success' => false, 'message' => "Could not add new $trn_type_name.");
                } 
                
                $tran_no = $msg['cmp_id'];
        }
        
        // create a new job card
        $jo_id = 0;
        if ($create_job === true) {
            $next_ref = $Refs->get_next(ST_JOB_ORDER); 
            
            $ref_msg = is_new_reference($next_ref, ST_JOB_ORDER, $jo_id);
                if ($ref_msg === false) {
                    $next_ref = $Refs->get_next(ST_JOB_ORDER) + 1;
                }
            
            $msg = add_job_order($jo_id, $next_ref, Today(), $_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['description'], 
                                 0, $type, $tran_no, $_POST['next_job_owner_id'], 0, 0);
                if ($msg['success'] === false) {
                    cancel_transaction();
                    return $msg;
                } 

            $text = "This job is created via $trn_type_name #$tran_no.";
            $job_msg = save_job_activity_log($jo_id, 'CUSTOMER_COMPLAIN', $text, 0, 0, 0, 0, '', $type, $tran_no);
                if ($job_msg['success'] === false) {
                    cancel_transaction();
                    return $job_msg;
                } 
                
            $cmp_af_rw = update_service_complain_row_state($tran_no, $row_state);   
                if ($cmp_af_rw  != 1) {
                    cancel_transaction();
                    return array('success' => false, 'message' => "Could not update $trn_type_name #$tran_no row state.");
                } 
                
                commit_transaction();
                
                meta_forward($_SERVER['PHP_SELF'], "JOID=$jo_id&cmp_id=$tran_no"); 
        }
        
        $cmp_id = $tran_no;
        
    commit_transaction();
        
    return array('success' => true, 'message' => "$trn_type_name #$tran_no has been $added_updated.");
}

function handle_close_service_complain_header($cmp_id) {
    global $systypes_array;
    
    $type = ST_SERVICE_COMPLAIN;
    $trn_type_name = $systypes_array[$type];
    
    $row_state = 0;
    
    // can close complain
    $cm_row = get_service_complain_record($cmp_id);
        if (is_array($cm_row)) {
            $job_row = get_job_orders_by_source($type, $cmp_id, true);
                if (is_array($job_row)) {
                    $jo_id = $job_row['id'];
                    return array('success' => false, 'message' => "$trn_type_name #$cmp_id has already created job card #$jo_id. Not allow to close it.");
                }
                
            $row_state = $cm_row['row_state'];
        }
        
        if (! (strlen($_POST['close_description']) > 15)) {
            return array("success" => false, "focus_to" => 'close_description', 
                         "message" => "$trn_type_name close details cannot empty and length should more than 15 letters.");        
        }
    
        // close complain
        $cmp_af_rw = close_service_complain($cmp_id, $_POST['close_description'], $row_state);   
            if ($cmp_af_rw  != 1) {
                cancel_transaction();
                return array('success' => false, 'message' => "Could not close $trn_type_name #$cmp_id.");
            } 

            commit_transaction();

            meta_forward($_SERVER['PHP_SELF'], "CLOSED_ID=$cmp_id"); 
}

function view_service_complain_header($cmp_id) {
    global $systypes_array;
    
    $type = ST_SERVICE_COMPLAIN;
    $tp_name = $systypes_array[$type];
    $row = get_service_complain_details($cmp_id);
    
    if (! is_array($row)) {
        display_note(("Unknown $tp_name #$cmp_id."), 1, 1);
        display_footer_exit();
    }

        start_table(TABLESTYLE2);
            label_row('Reference:', $row['ref'], "class='tableheader2'");
            label_row('Date:', sql2date($row['date_']), "class='tableheader2'");
            label_row('Vehicle/ Tool/ Job Location:', get_asset_formatted_name($row['vehicle_id']), "class='tableheader2'");
            label_row('Request Department:', $row['req_department_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('Customer Name:', $row['customer_name'], "class='tableheader2'");
            label_row('Customer Address:', nl2br($row['customer_address']), "class='tableheader2'");
            label_row(_("Customer Complain/ Request:"), nl2br($row['description']), "class='tableheader2'");
            label_row(_("Closed:"), $row['closed'] == 1 ? 'Yes' : 'No', "class='tableheader2'");
            if ($row['closed'] == 1) {
                label_row(_("Close Details:"), nl2br($row['close_description']), "class='tableheader2'");
            }
            label_row('Booking:', $row['booking'] == 1 ? 'Yes' : 'No', "class='tableheader2'");
            if ($row['booking'] == 1) {
                label_row('Schedule Date:', sql2date($row['schedule_date']), "class='tableheader2'");
            }
        end_table(2);
        
        return $row['closed'];
}

function view_service_complain_job_header($cmp_id) {
    global $systypes_array;
    
    $type = ST_JOB_ORDER;
    $com_req_name = $systypes_array[ST_SERVICE_COMPLAIN];
    
    display_heading($systypes_array[$type]." Details");    br();
    
        $row = get_job_order_details_by_filters(source_type: ST_SERVICE_COMPLAIN, source_trans_no: $cmp_id, fetch: true);
            if (! is_array($row)) {
                display_note(("Job card is not yet created for $com_req_name #$cmp_id."), 1, 1);
                display_footer_exit();
            }
    
        start_table(TABLESTYLE2);
            label_row('Job Card:', get_service_trans_view_str(ST_JOB_ORDER, $row['id']), "class='tableheader2'");
            label_row('Reference:', $row['jo_ref'], "class='tableheader2'");
            label_row('Date:', sql2date($row['date_']), "class='tableheader2'");
            label_row('Vehicle/ Tool/ Job Location:', get_asset_formatted_name($row['vehicle_id']), "class='tableheader2'");
            label_row('Department:', $row['department_name'], "class='tableheader2'");
            label_row('Section:', $row['section_name'], "class='tableheader2'");
            label_row('Current Owner:', get_employee_formatted_long_name($row['next_job_owner_id']), "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'");
        end_table(2);
}

function display_service_complains_view($from_date_=null, $to_date_=null, $vehicle_id=0, $req_department_id=0, $closed=null, $has_job=null, $issuing_officer=0, $id=0, 
                                        $jo_id=0, $reference='', $customer_name='', $customer_address='', $complain='', $booking=null) {
    start_table(TABLESTYLE, "width=99%");
        
        $th = array(_("#"), _("Job Card"), _("Reference"), _("Vehicle/ Tool/ Location"), _("Date"), _("Req.Department"), _("Issuing Officer"), _("Customer"), 
                    _("Customer Address"), _("Complain/ Request Details"), _("Closed"), _("Booking"), _("Schedue Date")); 
        table_header($th);
    
            $k = $total_complains_count = $total_jobs_count = $total_closed_count = $total_booking_count = 0;  
            $result = get_service_complain_details_by_filters($id, $reference, $from_date_, $to_date_, $vehicle_id, $req_department_id, $issuing_officer, $customer_name, 
                                                              $closed, $has_job, $jo_id, $customer_address, $complain, $booking);
                while ($row = db_fetch($result)) {
                    alt_table_row_color($k);

                        $id = $row['id'];
                        label_cell(get_service_trans_view_str(ST_SERVICE_COMPLAIN, $id), 'align=center');
                        if ($row['jo_id'] > 0) {
                            label_cell(get_service_trans_view_str(ST_JOB_ORDER, $row['jo_id']), 'align=center');
                            
                            $total_jobs_count++;
                        } else {
                            label_cell('');
                        }
                        label_cell($row['ref']);
                        label_cell(get_asset_formatted_name($row["vehicle_id"]));
                        label_cell(sql2date($row['date_']), 'align=center');
                        label_cell($row['req_department_name']);
                        if (strlen($row['issuing_officer_emp_code']) > 2) {
                            label_cell(get_employee_formatted_long_name($row['issuing_officer_emp_code']));
                        } else {
                            label_cell($row['issuing_officer']);
                        }
                        label_cell($row['customer_name']);
                        label_cell(nl2br($row['customer_address']));
                        label_cell(nl2br($row['description']));
                        label_cell(get_yes_no_name($row['closed']), 'align=center');
                        label_cell(get_yes_no_name($row['booking']), 'align=center');
                        if ($row['schedule_date'] != INFINITE_START_DATE) {
                            label_cell(sql2date($row['schedule_date']), 'align=center');
                        } else {
                            label_cell('');
                        }
                        
                    end_row();
                    
                    $total_complains_count++;
                    
                    if ($row['closed'] == 1) {
                        $total_closed_count++;
                    }
                    if ($row['booking'] == 1) {
                        $total_booking_count++;
                    }
                }
                
                start_row();
                    label_cell(text_bold($total_complains_count), "align=center");
                    label_cell(text_bold($total_jobs_count), "align=center");
                    label_cell(text_bold('Total Count'), "align=center colspan=8");
                    label_cell(text_bold($total_closed_count), "align=center");
                    label_cell(text_bold($total_booking_count), "align=center");
                end_row();

    end_table(2);
}

?>