<?php

function display_raw_material_return_header($rmi_trans_no, $type, $status=true) {
    global $Refs;
    
        $rmi_header = get_raw_material_issue_header_type_trans_no(ST_RAW_MATERIAL_ISSUE, $rmi_trans_no);
            $user_id = $_SESSION['wa_current_user']->user;
            $cap = can_access_project($rmi_header['project_id'], $user_id);
                if ($cap['success'] !== true) {
                    display_error($cap["message"]);
                    set_focus('project_id');
                    display_footer_exit();
                    exit;
                } 

        div_start('nsit_header');
  
            start_outer_table(TABLESTYLE2, "width=65%"); // outer table
                start_table(TABLESTYLE2);  
                    table_section(1, "50%");
                        label_row("Issue #:", get_manufacturing_trans_view_str(ST_RAW_MATERIAL_ISSUE, $rmi_header['trans_no']), "class='tableheader2'");  
                        label_row("Project:", $rmi_header['project_description'], "class='tableheader2'");   
                        $_POST['project_id'] = $rmi_header['project_id'];
                        hidden('project_id', $rmi_header['project_id']);
                        label_row("Issued Date:", sql2date($rmi_header['tran_date']), "class='tableheader2'");   
                        
                    table_section(2, "50%");
                        label_row("Issue Location:", $rmi_header['location_name'], "class='tableheader2'");   
                        $gc_name = get_group_company_name($rmi_header['company_code']);
                            label_row(_("Group Company:"), $gc_name, "class='tableheader2'");  
                        
                        global $approval_statuses;
                        $s = get_project_trans_view_str(ST_APPROVAL_LOG, $rmi_trans_no."&source_type_id=".ST_RAW_MATERIAL_ISSUE, "Approval Status");
                        label_row($s, $approval_statuses[$rmi_header['approval_status']], "class='tableheader2'");

                end_table();
            end_outer_table(2); // outer table
            
            
            $_POST['reference'] = $Refs->get_next($type);            
            $_POST['approval_status'] = 0;
            
            start_outer_table(TABLESTYLE2, "width=65%"); // outer table
                table_section(1, "40%");
                    text_row("Reference:", 'reference', $Refs->get_next($type), null, null);   
                    
                    if (! isset($_POST['location'])) {
                        $_POST['location'] = $rmi_header['loc_code'];
                    }
                    locations_list_row("Return Location:", 'location', null, '', false);       

                table_section(2, "20%");
                    date_row("Date:", 'tran_date');

                table_section(3, "40%");
                    textarea_row("Comment:", 'comments', null, 35, 2); 
            end_outer_table(2); // outer table
    
        div_end();
}

function display_raw_material_return_details($rmi_trans_no, $status=true) { 
    global $Ajax;
    
    $header = get_raw_material_issue_header_type_trans_no(ST_RAW_MATERIAL_ISSUE, $rmi_trans_no);
    
    display_heading("Details");
    
    $Ajax->activate('dir_details');
    div_start('dir_details');
    
        start_table(TABLESTYLE, "width=99%");

            $th = array(_("ID"), _("Item"), _("Issued Unit"), _("Issued Tran Qty"), _("Issued Qty"), _('Budget'), _('Employee'), _('Returned Qty'), 
                        _('Unit'), _('Return Qty'), _('Site'), _('Line Comment'), _(""));  
            table_header($th);

            $k = 0; //row colour counter
                $result = get_raw_material_issue_and_return_details($rmi_trans_no, 0);      
                    while ($row = db_fetch($result)) {
                        alt_table_row_color($k);
                            $id = $row['id'];
                            $issued_qty = $row["qty"];
                            $returned_quantity = $row["returned_quantity"];
                            $conversion_factor = $row["conversion_factor"];

                            label_cell($id, 'align=center');
                            label_cell($row["stock_id"].' - '.$row["stock_description"]);
                            label_cell($row["unit_name"]);
                            label_cell(number_format($row["tran_qty"], 2), 'align=right');
                            label_cell(number_format($issued_qty, 2), 'align=right');
                            label_cell($row["task_description"]);
                            label_cell(get_group_company_employee_formatted_long_name($header["company_code"], $row["employee_code"]));  
                            label_cell(number_format($returned_quantity, 2), 'align=right');
                            
                            if (! isset($_POST["tran_unit_$id"])) {
                                $_POST["tran_unit_$id"] = $row['tran_unit'];
                            } else {
                                if (! (strlen($_POST["tran_unit_$id"]) > 0)) {
                                    $_POST["tran_unit_$id"] = $row['tran_unit'];
                                }
                            }
                            
                            units_list_cells('', "tran_unit_$id", $row['stock_id'], null, '');
                                $dec = get_qty_dec($row["stock_id"]);
                                
                            get_convertion_factor2($row["stock_id"], $_POST["tran_unit_$id"], $conversion_factor);
                                
                            amount_cells("", "tran_qty_$id", null, null, null, $dec);
                            
                            if (! isset($_POST["site_id_$id"])) {
                                $_POST["site_id_$id"] = $row["site_id"];
                            }
                            project_sites_list_cells("", "site_id_$id", $_POST['project_id'], null, '', false); 
                            text_cells_ex('', "line_comment_$id", 50, 400, null, 'Line Comment');       

                            check_cells('', "checked_$id", null, false, false, 'align=center'); 

                        end_row();        
                    }

        end_table(3);
    
    div_end();
}

function can_process_raw_material_return_header($rmi_trans_no, $type) {
    global $Refs, $systypes_array;
    
    $rmi_header = get_raw_material_issue_header_type_trans_no(ST_RAW_MATERIAL_ISSUE, $rmi_trans_no);
        if (! ($rmi_header['approval_status'] == AS_APPROVED)) {
            $set_focus = '';
            $message = ($systypes_array[ST_RAW_MATERIAL_ISSUE]." record is not approved. Please approve it first.");
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
      
    if (! $Refs->is_valid($_POST['reference'])) {
        $message = ("Please enter a reference.");
        $set_focus = 'reference';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);      
    }    
 
    $ref_msg = reference_exists($_POST['reference'], $type, 0);
        if ($ref_msg) {
            $message = $ref_msg;
            $set_focus = 'reference';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);       
        }
    
    if (! is_date($_POST['tran_date'])) {
        $message = "Date entered is not a valid date.";
        $set_focus = 'tran_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
    
    $issued_date = sql2date($rmi_header['tran_date']);
    $return_date = $_POST['tran_date'];
    if (date1_greater_date2($issued_date, $return_date)) {
        $message = "Date cannot be before the issuing date.";
        $set_focus = 'tran_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
              
    if ($_POST['location'] == '') {
        $message = "Please select a location.";
        $set_focus = 'location';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
        $row_state = $rmi_header['row_state'];
    
    return array("success" => true, 'row_state' => $row_state, "message" => "");    
}

function can_process_raw_material_issue_lines($rmi_trans_no) {
    $selected_lines_count = 0;
        $result = get_raw_material_issue_and_return_details($rmi_trans_no, 0);        
            while ($row = db_fetch($result)) {
                $id = $row['id'];
                $conversion_factor = $row['conversion_factor'];
                $issued_qty = $row['qty'];
                
                if (isset($_POST["checked_$id"]) && $_POST["checked_$id"] == 1) {
                    
                    if ($_POST["tran_unit_$id"] == -1) {
                        $message = "Line #$id unit cannot be empty.";
                        $set_focus = "tran_unit_$id";
                        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
                    }
                    
                    $tran_qty = input_num("tran_qty_$id");

                    if (! ($tran_qty > 0)) {
                        $message = "Line #$id quantity should be greater than zero.";
                        $set_focus = "tran_qty_$id";
                        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
                    }
                    
                    // check max returnable qty
                    
                    get_convertion_factor2($row["stock_id"], $_POST["tran_unit_$id"], $conversion_factor);
                                
                    $returned_quantity = get_raw_material_issue_line_returned_total($id);
                    $balance_qty = ($issued_qty - abs($returned_quantity));
                    $max_returnable_qty = $balance_qty / $conversion_factor;

                        if ($tran_qty > $max_returnable_qty) {
                            $message = "Line #$id exceeds maximum returnable quantity $max_returnable_qty.";
                            $set_focus = "tran_qty_$id";
                            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
                        }
                        
                    if (! ($_POST["site_id_$id"] > 0)) {
                        $message = "Please select a job.";
                        $set_focus = "site_id_$id";
                        return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
                    }
                        
                    $selected_lines_count++;
                }
            }
            
            if (! ($selected_lines_count > 0)) {
                $message = "You should check at least one line before returning.";
                $set_focus = "";
                return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
            }

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

function save_raw_material_return_header($rmi_trans_no, $type) {
    $rmi_hd = get_raw_material_issue_header_type_trans_no(ST_RAW_MATERIAL_ISSUE, $rmi_trans_no);
    
        return write_raw_material_return_header_by_type_trans_no($type, $rmi_trans_no, $_POST['reference'], $rmi_hd['project_id'], $rmi_hd['company_code'], 
                                                                 $_POST['location'], $_POST['comments'], $_POST['tran_date']); 
}

function save_raw_material_return_lines($trans_no, $type, $rmi_trans_no) {    
    global $systypes_array;
        
        $result = get_raw_material_issue_and_return_details($rmi_trans_no, $trans_no);      
            while ($row = db_fetch($result)) {
                $id = $row['id'];
                
                if (isset($_POST["checked_$id"]) && $_POST["checked_$id"] == 1) {
                    
                    $stock_id = $row['stock_id'];
                    $task_id = $row["task_id"];
                    $employee_code = $row["employee_code"];
                    $tran_unit = $_POST["tran_unit_$id"];
                    $tran_qty = -input_num("tran_qty_$id");
                    $site_id = $_POST["site_id_$id"];
                    $line_comment = $_POST["line_comment_$id"];
                    $standard_cost = get_standard_cost($stock_id);
                    $conversion_factor = 1;
                        
                    get_convertion_factor2($stock_id, $tran_unit, $conversion_factor);

                    $qty = $tran_qty * $conversion_factor;
    
                    $af_no = write_raw_material_issue_line($trans_no, 0, $type, $_POST['location'], $stock_id, $tran_unit, $tran_qty, $qty, 
                                                           $conversion_factor, $standard_cost, $employee_code, $site_id, $line_comment, $task_id, $id); 
    
                        if (! ($af_no > 0)) {
                            $ln_ms = $systypes_array[$type]." line #$id could not be saved.";
                            return array("success" => false, 'trans_no' => $trans_no, "message" => $ln_ms);
                        } 
        
                        update_raw_material_issue_line_returned_total($id);
                }
            }

                $ln_ms = $systypes_array[$type]." lines have been saved.";
                
                return array("success" => true, 'trans_no' => $trans_no, "message" => $ln_ms);
}

function save_raw_material_return($rmi_trans_no, $type) {
    global $systypes_array;
    
    $hd_msg = can_process_raw_material_return_header($rmi_trans_no, $type);   
        if ($hd_msg["success"] !== true) {          
            if (isset($hd_msg["focus_to"])) {
                set_focus($hd_msg["focus_to"]);            
            }
            
            return array("success" => false, "message" => $hd_msg["message"]);
        }
    
    $ln_msg = can_process_raw_material_issue_lines($rmi_trans_no);
        if ($ln_msg['success'] !== true) {
            if (isset($ln_msg["focus_to"])) {
                set_focus($ln_msg["focus_to"]);            
            }
            
            return array("success" => false, "message" => $ln_msg['message']);        
        }
       
        begin_transaction();

            $trans_no = save_raw_material_return_header($rmi_trans_no, $type);
                if (! ($trans_no > 0)) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not be saved ".$systypes_array[$type]." header.");
                }

            $line_msg = save_raw_material_return_lines($trans_no, $type, $rmi_trans_no);
                if ($line_msg['success'] !== true) {
                    cancel_transaction();
                    return array("success" => false, 'trans_no' => $trans_no, "message" => $line_msg['message']);
                }
                
            $ap_msg = approve_raw_material_return($trans_no, $type);
                if ($ap_msg['success'] !== true) {
                    cancel_transaction();
                    return array("success" => false, 'trans_no' => $trans_no, "message" => $ap_msg['message']);
                }

        commit_transaction();

        meta_forward($_SERVER['PHP_SELF'], "SavedID=$trans_no"); 
}

function approve_raw_material_return($trans_no, $type) {
    global $systypes_array;
    
        $tran_date = $_POST['tran_date'];
        
        $ap_msg = add_raw_material_retrun_lines($trans_no, $type, $tran_date);
            if ($ap_msg["success"] !== true) {          
                return $ap_msg;
            } 

        $af_row = update_raw_material_return_header_approval_status($trans_no, AS_NEW, AS_APPROVED);
            if (! ($af_row > 0)) {          
                return array("success" => false, 'trans_no' => $trans_no, "message" => "Could not be updated approval status.");
            } 
            
        // budget update 
            $rmr_details_array = array();
            
            $result = get_raw_material_issue_details($trans_no, $type);      
                while ($row = db_fetch($result)) {
                    $qty = abs($row['qty']);
                    
                    $b['row_id'] = $row['id'];
                    $b['stock_id'] = $row['stock_id'];
                    $b['task_id'] = $row['task_id'];
                    $b['requested_qty'] = $qty;
                    $b['high_value_item'] = 0;

                    $standard_cost = get_standard_cost($row["stock_id"]);
                    $b['reference_cost'] = $standard_cost; 
                    $b['standard_cost'] = $standard_cost;
                    $b['charging_cost'] = $standard_cost;
                    $b['total_issued_qty'] = $qty;
                    $b['qty'] = $qty;

                        $rmr_details_array[] = $b;
                }

            $mi_tasks_summary = calculate_task_remaining_totals($rmr_details_array);
            $created_by = $_SESSION['wa_current_user']->user;
    
            $mtrec_msg = remove_costs_from_tasks($type, $trans_no, $mi_tasks_summary, $created_by);
                if ($mtrec_msg['success'] !== true) {
                    return array("success" => $mtrec_msg['success'], "tran_no" => $trans_no, "message" => $mtrec_msg['message']);
                }
                
        return array("success" => true, 'trans_no' => $trans_no, "message" => $systypes_array[$type].' has been approved.');
}

function add_raw_material_retrun_lines($trans_no, $type, $tran_date_) {
    $h = get_raw_material_issue_header_record_type_trans_no($type, $trans_no);
    $result = get_raw_material_issue_details($trans_no, $type);      
        while ($row = db_fetch($result)) {
            $qty = abs($row["qty"]);
            $tran_qty = abs($row["tran_qty"]);
            $standard_cost = get_standard_cost($row["stock_id"]);
            
            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["site_id"], $row["id"],
                                        $h['project_id']);
        }  
        
            return array("success" => true, 'trans_no' => $trans_no, "message" => "");
}

function view_raw_material_return_header($type, $trans_no) {
    global $document_approval_statuses;
    
    $row = get_raw_material_issue_header_type_trans_no($type, $trans_no);
    
        start_outer_table(TABLESTYLE2, "width=60%");

            table_section(1, "50%");
                label_row("Issue #:", get_manufacturing_trans_view_str(ST_RAW_MATERIAL_ISSUE, $row['source_id']), "class='tableheader2'");
                label_row(_("Reference:"), $row['reference'], "class='tableheader2'");
                label_row(_("Porject:"), $row['project_description'], "class='tableheader2'");
                label_row(_("Date:"), sql2date($row['tran_date']), "class='tableheader2'");

            table_section(2, "50%");
                label_row(_("Location:"), $row['location_name'], "class='tableheader2'");
                label_row(_("Company:"), get_group_company_name($row['company_code']), "class='tableheader2'");
                label_row(_("Approval Status:"), $document_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(3);
        }
}

function view_raw_material_return_details($type, $trans_no) {
    start_table(TABLESTYLE, "width=95%");

        $th = array(_("ID"), _("Item"), _("Unit"), _("Qty"), _('Budget'), _('Employee'), _('Job'), _('Comment'));  
        table_header($th);
        
        $header = get_raw_material_issue_header_record_type_trans_no($type, $trans_no);

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

                        label_cell($row['id'], 'align=center');
                        label_cell($row["stock_id"].' - '.$row["stock_description"]);
                        label_cell($row["unit_name"]);
                        label_cell(number_format(abs($row["tran_qty"]), 2), 'align=right');
                        label_cell($row["task_description"]);
                        label_cell(get_group_company_employee_formatted_long_name($header["company_code"], $row["employee_code"]));          
                        label_cell($row["site_description"]);          
                        label_cell(nl2br($row["line_comment"]));          

                    end_row();        
                }

    end_table(3);
}

?>