<?php

function display_material_list_jmr_dpr_header($ml_no, $type) {
    global $Refs;
    
    $trans_no = 0;
    
        $header = get_material_list_header($ml_no);
            $_POST['project_description'] = $header['project_description'];
            $_POST['project_id'] = $header['project_id'];

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

            if (! isset($_POST['location'])) {
                $_POST['location'] = $header['loc_code'];
            }
    
        $_POST['reference'] = $Refs->get_next($type);            
        $_POST['approval_status'] = 0;
        
        div_start('nsit_header');
  
            start_outer_table(TABLESTYLE2, "width=65%"); // outer table
                start_table(TABLESTYLE2);  
                    table_section(1, "50%");

                        label_row("Job Card:", $header['jo_id']); 
                        
                        text_row("Reference:", 'reference', $Refs->get_next($type), null, null);   

                        label_row("Project:", get_project_formatted_name($_POST['project_id']));   

                    table_section(2, "50%");
                        
                        date_row("Date:", "tran_date");
                        
                        locations_list_row("Location:", 'location', null, '', false);  
                        
                        textarea_row("Comment:", 'comments', null, 35, 2); 

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

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

function display_material_list_jmr_dpr_details($ml_no) { 
    global $Ajax;
    
    $header = get_material_list_header_record($ml_no);
        $ml_trans_no = $header['trans_no'];
        $ml_type = $header['type'];
        
    $units_array = build_all_item_units_array();
    
    $Ajax->activate('nsit_details');
    div_start('nsit_details');
    
        start_table(TABLESTYLE, "width=99%");

            $th = array(_("ML Line #"), _("Item Type"), _("Item"), _("Unit"), _("Tran Qty"), _("Base Unit"), _("Base Qty"), _("JMR Qty"), _("DPR Qty"), _('Budget'), 
                        _('Item Cost'), _('Site'), _('Line Comment'), _(""));  
            table_header($th);

            $k = 0; //row colour counter
                $result = get_material_list_details($ml_trans_no, $ml_type);      
                    while ($row = db_fetch($result)) {
                        
                        display_material_list_line($row);
                        
                        alt_table_row_color($k);
                            display_material_list_jmr_dpr_line_edit_controls($row, $units_array);
                        end_row();        
                    }

        end_table(2);
    
    div_end();
}

function display_material_list_line($row) {
    global $daily_item_types_array;
    
        start_row('style=background-color:#abdbda');
            label_cell(text_bold($row['trans_id']), 'align=center');
            
            label_cell($daily_item_types_array[$row['item_type']]);
            if ($row['item_type'] == NSIT_NON_STOCK_ITEM || $row['item_type'] == NSIT_STOCK_ITEM) {
                label_cell($row["stock_id"]." - ".$row["item_description"]);  
            } else {
                label_cell($row["item_description"]);
            }
            label_cell($row["unit_name"]);

            $dec = 4; // get_qty_dec($row["stock_id"]);
            qty_cell($row["tran_qty"], false, $dec);
            label_cell(get_item_base_unit_name($row["stock_id"]));
            qty_cell($row["qty"], false, $dec);
            $conversion_factor = $row['conversion_factor'];
            qty_cell($row["jmr_quantity"] / $conversion_factor, false, $dec);
            qty_cell($row["dpr_quantity"] / $conversion_factor, false, $dec);

            label_cell('');

            $tran_unit_cost = $row["standard_cost"] * $row["conversion_factor"];
                if ($tran_unit_cost > 0) {
                    qty_cell($tran_unit_cost, false, $dec);
                } else {
                    label_cell('');
                }

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

function display_material_list_jmr_dpr_line_edit_controls($row, $units_array) {
    global $daily_item_types_array;
    $dec = 4;
    
    $id = $row['trans_id'];

        label_cell('');
        if (! isset($_POST["item_type_$id"])) {
            $_POST["item_type_$id"] = $row['item_type'];
        } 
        custom_values_list_cells('', "item_type_$id", $daily_item_types_array, null, '', true);

        if (! isset($_POST["stock_id_$id"])) {
            $_POST["stock_id_$id"] = $row['stock_id'];
        } 
        if (! isset($_POST["item_description_$id"])) {
            $_POST["item_description_$id"] = $row['item_description'];
        } 

        if ($_POST["item_type_$id"] == NSIT_NON_STOCK_ITEM) {
            label_cell(non_stock_items_list("stock_id_$id", null, false, true));
            $itm = get_item($_POST["stock_id_$id"]);
                if (is_array($itm)) {
                    hidden("item_description_$id", $itm['description']);
                } else {
                    hidden("item_description_$id", '');
                }
        } elseif ($_POST["item_type_$id"] == NSIT_STOCK_ITEM) {
            label_cell(stock_and_manufacture_items_list("stock_id_$id", null, false, true));
            $itm = get_item($_POST["stock_id_$id"]);
                if (is_array($itm)) {
                    hidden("item_description_$id", $itm['description']);
                } else {
                    hidden("item_description_$id", '');
                }
        } elseif ($_POST["item_type_$id"] == NSIT_COMMENT) {
            text_cells('', "item_description_$id", null, 20, 1000, 'Item Description');
            hidden("stock_id_$id", '');
        } else {
            label_cell(''); 
            hidden("stock_id_$id", '');
            hidden("item_description_$id", '');
        }

        if ($_POST["item_type_$id"] == NSIT_NON_STOCK_ITEM || $_POST["item_type_$id"] == NSIT_STOCK_ITEM) {
            units_list_cells('', "tran_unit_$id", $_POST["stock_id_$id"], null, '', true);
        } else {
            custom_values_list_cells('', "tran_unit_$id", $units_array, null, '', true);   
        }
        
        $tran_unit = $_POST["tran_unit_$id"];

        amount_cells('', "tran_qty_$id", null, null, null, $dec);
        label_cell(get_item_base_unit_name($_POST["stock_id_$id"]));
        $conversion_factor = 1;
        get_convertion_factor2($_POST["stock_id_$id"], $tran_unit, $conversion_factor);
        $tran_qty = (float) $_POST["tran_qty_$id"];
        $base_qty = $tran_qty > 0 ? $tran_qty * $conversion_factor : 0;
        qty_cell($base_qty, false, $dec);
        qty_cell($base_qty, false, $dec);
        label_cell('');

        if ($_POST["item_type_$id"] == NSIT_NON_STOCK_ITEM || $_POST["item_type_$id"] == NSIT_STOCK_ITEM) {
            tasks_list_cells('', "task_id_$id", GLOBAL_VOTES, null, _(''));
        } else {
            $_POST["task_id_$id"] = 0;
            hidden("task_id_$id", 0);
            label_cell('');
        }

        if ($_POST["item_type_$id"] == NSIT_NON_STOCK_ITEM) {
            amount_cells("", "item_cost_$id", null, null, null, 0);
        } else {
            $_POST["item_cost_$id"] = 0;
            hidden("item_cost_$id", 0);
            label_cell('');
        }

        project_sites_list_cells("", "site_id_$id", GLOBAL_VOTES, null, '', false); 
        text_cells_ex('', "line_comment_$id", 20, 1000, null, 'Line Comment');

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

function set_remain_qty($id, $row, $dec=4) {
    $tran_unit = $_POST["tran_unit_$id"];
    $convesion_factor = 1;
    get_convertion_factor2($_POST["stock_id_$id"], $tran_unit, $convesion_factor);

    $remain_tran_qty = ($row["jmr_quantity"] - $row["dpr_quantity"]) / $convesion_factor;

    $_POST["tran_qty_$id"] = number_format($remain_tran_qty, $dec);
}

function create_ml_jmr_dpr_header_array($type, $ml_type, $ml_trans_no, $jo_id, $project_id) {
    $hd_array = array();
    
        $hd_array['jo_id'] = $jo_id;
        $hd_array['ModifyJMR_No'] = isset($_POST['ModifyJMR_No']) ? $_POST['ModifyJMR_No'] : null;
        $hd_array['project_id'] = $project_id;
        if ($type == ST_JOB_MATERIAL_REQ) {
            $hd_array['jmr_no'] = 0;
        } elseif ($type == ST_DIRECT_PURCHASE_REQ) {
            $hd_array['dpr_no'] = 0;
        }
        $hd_array['type'] = $type;
        $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_array['lines_count'] = get_material_list_jmr_dpr_checked_lines_count($ml_trans_no, $ml_type);
        $hd_array['reference'] = $_POST['reference'];
        $hd_array['tran_date'] = $_POST['tran_date'];
        $hd_array['location'] = $_POST['location'];
        $hd_array['comments'] = $_POST['comments'];
        $hd_array['source_type'] = $ml_type;
        $hd_array['source_trans_no'] = $ml_trans_no;
    
        return $hd_array;
}

function get_material_list_jmr_dpr_checked_lines_count($ml_trans_no, $ml_type) {
    $checked_lines_count = 0;
    
    $result = get_material_list_details($ml_trans_no, $ml_type);  
        while ($row = db_fetch($result)) {
            $id = $row['trans_id'];
            
            if (isset($_POST["checked_$id"]) && $_POST["checked_$id"] == 1) {
                $checked_lines_count++; 
            }
        }
        
        return $checked_lines_count;
}

function create_ml_jmr_dpr_line_array($id, $ml_type, $ml_trans_no) {
    $ln_array = array();
    
        $ln_array['selected_id'] = 0;
        $ln_array['item_type'] = $_POST["item_type_$id"];
        $ln_array['stock_id'] = isset($_POST["stock_id_$id"]) ? $_POST["stock_id_$id"] : '';
        $tran_unit = $ln_array['tran_unit'] = $_POST["tran_unit_$id"];
        $ln_array['tran_qty'] = input_num("tran_qty_$id");
        $conversion_factor = 1;
        get_convertion_factor2($ln_array["stock_id"], $tran_unit, $conversion_factor);
        $ln_array['qty'] = $ln_array["tran_qty"] * $conversion_factor;
        $ln_array['conversion_factor'] = $conversion_factor;
        $ln_array['item_description'] = isset($_POST["item_description_$id"]) ? $_POST["item_description_$id"] : '';
        $ln_array['task_id'] = $_POST["task_id_$id"];
        $ln_array['site_id'] = $_POST["site_id_$id"];
        $ln_array['line_comment'] = $_POST["line_comment_$id"];
        $ln_array['item_cost'] = isset($_POST["item_cost_$id"]) ? input_num("item_cost_$id") : 0;
        $ln_array['source_type'] = $ml_type;
        $ln_array['source_trans_no'] = $ml_trans_no;
        $ln_array['source_line_id'] = $id;

            return $ln_array;
}

function save_material_list_jmr_dpr($type, &$hd_array, $lines_array) {
    global $systypes_array;
    
    if ($type == ST_JOB_MATERIAL_REQ) {
        $header_msg = save_job_material_requisition_header($hd_array);
            if ($header_msg["success"] !== true) {
                cancel_transaction();
                return array("success" => false, "message" => $header_msg['message']);
            }
            $new_row_state = $hd_array['row_state'];

        foreach ($lines_array as $key => $ln_array) {
            $ln_array['trans_no'] = $hd_array['trans_no'];
            $ln_array['type'] = $hd_array['type'];

            $line_msg = save_job_material_requisition_line($ln_array, "ML Line #$key ");
                if ($line_msg['success'] !== true) {
                    cancel_transaction();
                    return array("success" => false, "message" => $line_msg['message']);
                }

            $af_row = update_material_list_jmr_quantity($ln_array['source_type'], $ln_array['source_trans_no'], $ln_array['source_line_id']);
                if ($af_row != 1) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not update ".$systypes_array[ST_MATERIAL_LIST]." line #$key total JMR quantity.");
                }
        }

        $num_af_row = update_job_material_requisition_header_totals($type, $hd_array['trans_no'], $new_row_state);
            if (! ($num_af_row == 1)) {
                cancel_transaction();
                return array("success" => false, "message" => "Could not update ".$systypes_array[$type]." header total.");
            }

    } elseif ($type == ST_DIRECT_PURCHASE_REQ) {

        $header_msg = save_direct_purchase_requisition_header($hd_array);
            if ($header_msg["success"] !== true) {
                cancel_transaction();
                return array("success" => false, "message" => $header_msg['message']);
            }
            $new_row_state = $hd_array['row_state'];

        foreach ($lines_array as $key => $ln_array) {
            $ln_array['trans_no'] = $hd_array['trans_no'];
            $ln_array['type'] = $hd_array['type'];

            $line_msg = save_direct_purchase_requisition_line($ln_array, "ML Line #$key ");
                if ($line_msg['success'] !== true) {
                    cancel_transaction();
                    return array("success" => false, "message" => $line_msg['message']);
                }

            $af_row = update_material_list_dpr_quantity($ln_array['source_type'], $ln_array['source_trans_no'], $ln_array['source_line_id']);
                if ($af_row != 1) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not update ".$systypes_array[ST_MATERIAL_LIST]." line #$key total DPR quantity.");
                }
        }

        $num_af_row = update_direct_purchase_requisition_header_totals($type, $hd_array['trans_no'], $new_row_state);
            if (! ($num_af_row == 1)) {
                cancel_transaction();
                return array("success" => false, "message" => "Could not update ".$systypes_array[$type]." header total.");
            }
    }
    
        return array("success" => true, "message" => "");
}

function validate_and_save_material_list_jmr_dpr($ml_no, $type) {
    global $systypes_array;
    
    $tp_name = $systypes_array[$type];
    
    $ml_row = get_material_list_header($ml_no);
        if ($ml_row['approval_status'] != AS_APPROVED) {
            return array('success' => false, 'message' => $systypes_array[ST_MATERIAL_LIST].' approval status has been changed.');
        }
        
        $ml_trans_no = $ml_row['trans_no'];
        $ml_row_state = $ml_row['row_state'];
    
    $hd_array = create_ml_jmr_dpr_header_array($type, $ml_row['type'], $ml_trans_no, $ml_row['jo_id'], $ml_row['project_id']);
    
        if ($type == ST_JOB_MATERIAL_REQ) {
            $hd_msg = can_process_job_material_requisition_header($hd_array);   
        } elseif ($type == ST_DIRECT_PURCHASE_REQ) {
            $hd_msg = can_process_direct_purchase_requisition_header($hd_array);  
        } else {
            return array('success' => false, 'message' => "Wrong transaction type.");
        }
            if ($hd_msg["success"] !== true) {          
                if (isset($hd_msg["focus_to"])) {
                    set_focus($hd_msg["focus_to"]);            
                }
                return $hd_msg;
            } 

        $lines_array = array();
        $result = get_material_list_details($ml_trans_no, $ml_row['type']);  
            while ($row = db_fetch($result)) {
                $id = $row['trans_id'];

                if (isset($_POST["checked_$id"]) && $_POST["checked_$id"] == 1) {
                    $ln_array = create_ml_jmr_dpr_line_array($id, $ml_row['type'], $ml_trans_no);
                    
                    if ($type == ST_JOB_MATERIAL_REQ) {
                        $total_qty = $row['jmr_quantity'] + $ln_array['qty'];
                        
                        $ln_msg = can_process_job_material_requisition_line($ln_array, "ML Line #$id", "_$id");
                    } elseif ($type == ST_DIRECT_PURCHASE_REQ) {
                        $total_qty = $row['dpr_quantity'] + $ln_array['qty'];
                        
                        $ln_msg = can_process_direct_purchase_requisition_line($ln_array, "ML Line #$id", "_$id");
                    }
                        if ($ln_msg['success'] !== true) {
                            if (isset($ln_msg["focus_to"])) {
                                set_focus($ln_msg["focus_to"]);            
                            }
                            return $ln_msg;        
                        }  
                        
                    if (! ($ln_array['task_id'] > 0)) {
                        $ln_array['task_id'] = 0;
                    }
                        
                    // check whether total material list qty is exceeded by this trans type
                    if ($total_qty > $row['qty']) {
                        $ex_tran_qty = ($total_qty - $row['qty']) / $ln_array['conversion_factor'];
                        return array('success' => false, 'message' => "ML line #$id requestable $tp_name qty is exceeded by $ex_tran_qty in tran qty.");
                    }

                    $lines_array[$id] = $ln_array;
                }
            }

            if (! (count($lines_array) > 0)) {
                return array('success' => false, 'message' => "Please select at least one record before saving.");
            } 

            begin_transaction();

                $sv_mes = save_material_list_jmr_dpr($type, $hd_array, $lines_array);
                    if ($sv_mes['success'] !== true) {
                        return $sv_mes;        
                    } 
                    
                $ml_tp_name = $systypes_array[ST_MATERIAL_LIST];
                $ml_rs = update_material_list_row_state($ml_no, $ml_row_state);
                    if ($ml_rs != 1) {
                        return array('success' => false, 'message' => "Could not update $ml_tp_name trans #$ml_trans_no row state.");
                    }

                $ck_st = check_all_material_list_lines_fully_purchase_requisted($ml_row['type'], $ml_trans_no);
                    if ($ck_st === true) {
                        $ml_row_state = db_new_row_state($ml_row_state);
                        $af_rw = update_material_list_header_approval_status($ml_no, AS_APPROVED, AS_COMPLETED, $ml_row_state);
                            if ($af_rw != 1) {
                                return array('success' => false, 'message' => "Could not update $ml_tp_name trans #$ml_trans_no approval status.");
                            }
                    }

            commit_transaction();

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

?>