<?php
/**********************************************************************
***********************************************************************/
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/ui/items_cart.inc");

//--------------------------------------------------------------------------------

function add_mio_to_cart(&$order, $new_item, $new_item_qty, $required_date, $line_comment)
{
    if ($order->find_cart_item($new_item))
    {
        display_error(_("For Part :") . $new_item . " " . "This item is already on this material requisition.  You can change the quantity requested of the existing line if necessary.");
    }
    else
    {
        $order->add_to_cart(count($order->line_items), $new_item, $new_item_qty, null, null, $required_date, $line_comment);
    }
}

//--------------------------------------------------------------------------------

function display_material_requisition_transfer_header(&$order) {
    global $Refs, $approval_statuses;
    
    if(isset($order->order_id) && $order->order_id > 0){
        $project_id = $order->project_id;
        $user_id = $_SESSION['wa_current_user']->user;
        $cap = can_access_project($project_id, $user_id);
        if($cap['success'] !== true) 
        {
            display_error($cap["message"]);
            set_focus('project_id');
            display_footer_exit();
            exit;
        } 
    }      

    start_outer_table(TABLESTYLE2, "width=80%");

    table_section(1, "33%");
    label_row(_("Issuing Location:"), $order->issuing_location_name, "class='tableheader2'");
    label_row(_("Receiving Location:"), $order->receiving_location_name, "class='tableheader2'");
    label_row(_("Requsting Project:"), $order->project_description, "class='tableheader2'");
//    label_row(_("Approval Path:"), $order->approval_path_description, "class='tableheader2'");

    table_section(2, "33%");
    label_row(_("Requisition No:"), get_inventory_trans_view_str(ST_TRANSFERREQ, $order->order_id), "class='tableheader2'");
    label_row(_("Requisition Reference:"), $order->reference, "class='tableheader2'");
    label_row(_("Required Date:"), sql2date($order->required_date), "class='tableheader2'");
    
    
    table_section(3, "33%");
    label_row(_("Movement Type:"), $order->movement_type_name, "class='tableheader2'");
    $linked_field_values = get_movement_type_linked_field_values($order->linked_field_type, $order->linked_field_id);
    if(strlen($linked_field_values["field_name"]) > 0){
        label_row($linked_field_values["field_name"].':', $linked_field_values['value'], "class='tableheader2'");
    }
    
    label_row(_("Requestor:"), $order->requestor_name, "class='tableheader2'");
//    $s = get_project_trans_view_str(98, "1&source_trans_no=".ST_MATERIAL_REQ, "Approval Status");
    $s = get_project_trans_view_str(ST_APPROVAL_LOG, $order->order_id."&source_type_id=".ST_TRANSFERREQ, "Approval Status");
    label_row($s,$approval_statuses[$order->approval_status], "class='tableheader2'");
    
    end_outer_table(1);
    
    if (strlen($order->memo_) > 0) {
        start_table(TABLESTYLE2);
            label_row(_("MTR Comment:"), nl2br($order->memo_), "class='tableheader2'");
        end_table(1);
    }


    start_outer_table(TABLESTYLE2, "width=50%"); // outer table
        table_section(1, "50%");
            locations_list_row(_("Issuing Location:"), 'issuing_location', $order->issuing_location, false, false);
//            project_list_row(_("Issuing Project:"), 'issuing_project_id', $order->issuing_project_id, FALSE, TRUE);
            locations_list_row(_("Receiving Location:"), 'receiving_location', $order->receiving_location, false, false);
        table_section(2, "50%");
            ref_row(_("Reference:"), 'mrt_reference', '', $Refs->get_next(ST_REQTRANSFER));
            date_row('Date:', 'tran_date');
//            yesno_list_row("Make Requisition Complete:", "mtr_complete",$order->mr_complete);
    
    end_outer_table(2); // outer table
}

//---------------------------------------------------------------------------------

function display_material_requisition_transfer_items($title, &$order)
{
    global $path_to_root, $Ajax;
    display_heading($title);
    div_start('items_table');
	start_table(TABLESTYLE, "width=100%");
	$th = array(_("Line Id"), _("Item Code"), _("Item Description"), _("Req. Unit Qty"), _("Req. Unit"), _("Qty Issued"), _("Issu. Unit"), 
                    _("Issu. Qty"), _("Required Date"), _("Comment"), _("Job"));
    
	if ( count($order->line_items)) $th[] = '';

	table_header($th);
	$total = 0;
	$k = 0;  //row colour counter

	$id = find_submit('Edit');
	foreach ($order->line_items as $line_no=>$stock_item)
	{

		$total += ($stock_item->standard_cost * ($stock_item->quantity * $stock_item->convertion_factor));

		if ($id != $line_no)
		{
                    alt_table_row_color($k);

                    label_cell($stock_item->row_id, 'align=center');
                    view_stock_status_cell($stock_item->stock_id);
                    label_cell($stock_item->item_description);
                    
                    $dec = get_qty_dec($stock_item->stock_id);
//                    qty_cell($stock_item->requested_qty, false, $dec);
//                    label_cell($stock_item->units);
                    qty_cell($stock_item->requested_unit_quantity, false, $dec);
                    label_cell($stock_item->alternate_unit_name);
                    $tran_unit_issued_qty = $stock_item->issued_qty / $stock_item->convertion_factor;
                    qty_cell($tran_unit_issued_qty, false, $dec);
                    
                    if(get_post($stock_item->row_id.'_tran_unit') != ''){
                        $current_tran_unit = get_post($stock_item->row_id.'_tran_unit');
                    }
                    else{
                        $current_tran_unit = $stock_item->tran_unit;
                    }
                    
                    
                    $alternate_unit = get_alternate_unit_info($stock_item->stock_id, $current_tran_unit);
                    if($alternate_unit){
                        $alternate_unit_convertion_factor = $alternate_unit['convertion_factor'];
                    }
                    else{
                        $alternate_unit_convertion_factor = 1;
                    }
//                    units_list_cells(null, $stock_item->row_id.'_tran_unit', $stock_item->stock_id, $alternate_unit['alternate_unit'], false, true);
                    
                    if(list_updated($stock_item->row_id.'_tran_unit') || !isset($_POST[$stock_item->row_id."_tran_qty"] )){
                        $base_unit_req_qty = $stock_item->tran_qty * $stock_item->convertion_factor;
                        $suggested_issu_qty = ( $base_unit_req_qty - $stock_item->issued_qty) / $alternate_unit_convertion_factor;
                        if($suggested_issu_qty < 0){
                            $suggested_issu_qty = 0;
                        }
                        $_POST[$stock_item->row_id."_tran_qty"] = $suggested_issu_qty;
                    }
                    else{
                        $suggested_issu_qty = $_POST[$stock_item->row_id."_tran_qty"];
                    }
                    
//                    qty_cells(null, $stock_item->row_id."_qty", $suggested_issu_qty, null, null, $dec);
                    
                    units_list_cells(null, $stock_item->row_id.'_tran_unit', $stock_item->stock_id, null, false, true);
                    //$unit_of_parent = $_POST['tran_unit'];
                    $unit_of_parent = get_post($stock_item->row_id.'_tran_unit');

                    $item_info = get_item_edit_info($stock_item->stock_id);
                    $_POST['stock_control_method'] = $item_info["stock_control_method"];
                    
                    
                    display_quantity_cells(get_post('guid'), $order->trans_type, $stock_item->line_ref, $stock_item->stock_id, 
                                            $item_info["stock_control_method"], $stock_item->row_id.'_', $suggested_issu_qty, $unit_of_parent, 
                                            $dec = 2, "items_table");
                    
                    label_cell($stock_item->required_date);
                    label_cell($stock_item->line_comment);
                    
//                    tasks_list_cells(null, $stock_item->row_id.'_issuing_task_id', $_POST['issuing_project_id'], null, _('Select a budget'));
                    
                    project_sites_list_cells(null, $stock_item->row_id.'_project_site_id', $order->project_id, $stock_item->project_site_id,'');
                    
                    check_cells('', $stock_item->row_id.'_check', null, false, false, 'align=center');
                    
                    /*
                    edit_button_cell("Edit$line_no", _("Edit"),
                            _('Edit document line'));
                    delete_button_cell("Delete$line_no", _("Delete"),
                            _('Remove line from document'));
                     * 
                     */
                    end_row();
                    
                    $dec = 0;
		}
		else
		{
			//mio_edit_item_controls($order, $line_no);
		}
	}

	if ($id == -1)
		//mio_edit_item_controls($order);

	//label_row(_("Total"), number_format2($total,user_price_dec()), "align=right colspan=5", "align=right", 2);

    end_table();
	div_end();
}

//---------------------------------------------------------------------------------

function mrt_options_controls()
{
	  echo "<br>";
	  start_table();

	  textarea_row(_("Comment:"), 'memo_', null, 50, 3);

	  end_table(1);
}


//---------------------------------------------------------------------------------

function view_requisition_transfer_header($mrt_no, $suppress_view_link=false) {
    $myrow = get_material_requisition_transfer($mrt_no);
    
    start_outer_table(TABLESTYLE2, "width=60%");
        table_section(1, "50%");
            label_row(_("Receiving Location:"), $myrow['receiving_location_name'], "class='tableheader2'");
            label_row(_("Issuing Location:"), $myrow['issuing_location_name'], "class='tableheader2'");
//            label_row(_("Issuing Project:"), $myrow['project_description'], "class='tableheader2'");
            label_row(_("Date:"), sql2date($myrow['tran_date']), "class='tableheader2'");
            label_row(_("Reference:"), $myrow['reference'], "class='tableheader2'");
        table_section(2, "50%");
            label_row(_("Requisition No:"), get_inventory_trans_view_str(ST_TRANSFERREQ, $myrow['source_mtr_no']), "class='tableheader2'");
            
            global $inventory_movement_type_linked_fields;
            
            $mtr_header = get_material_transfer_requisition($myrow['source_mtr_no']);
            label_row(_("Movement Type:"), $mtr_header['movement_type_name'], "class='tableheader2'");
            if ($mtr_header['linked_field_type'] != IMLF_NOT_LINKED) {
                $link_field = get_movement_type_linked_field_values($mtr_header['linked_field_type'], $mtr_header['linked_field_id']);
                label_row(_($inventory_movement_type_linked_fields[$mtr_header['linked_field_type']].":"), $link_field['value'], "class='tableheader2'");
            }
    end_outer_table(2);
    
    if (strlen($myrow['comments']) > 0) {
        start_table(TABLESTYLE2);
            label_row(_("Comment:"), nl2br($myrow['comments']), "class='tableheader2'");
        end_table(3);
    }
}

//---------------------------------------------------------------------------------

function view_material_requisition_transfer_details($mrt_no, $suppress_view_link=false) {
    $result = get_mrt_details($mrt_no);
   	start_table(TABLESTYLE, "width=75%");
            $th = array(_("Line Id"), _("MTR Line"), _("Itemcode"), _("Item Description"), _("Req. Qty"), _("Tran Qty"), _("Tran Unit"), _("Job"));
            table_header($th);
            while ($myrow = db_fetch($result)){
                start_row();
                    label_cell($myrow["id"], 'align=center');
                    label_cell($myrow["ref_line_id"], 'align=center');
                    label_cell($myrow["stock_id"]);
                    label_cell($myrow["description"]);
                    $dec = get_qty_dec($myrow["stock_id"]);
                    
                    $mtr_line = get_mtr_deatails_record_by_id($myrow['ref_line_id']);
                        qty_cell($mtr_line['requested_qty'] / $mtr_line['req_unit_conv_factor'], false, $dec);
                    qty_cell($myrow["tran_qty"], false, $dec);
                    $alternate_unit = get_unit_name($myrow['tran_unit']);
                        label_cell($alternate_unit['name']);
//                    label_cell($myrow["task_description"]);
                    label_cell($myrow["project_site_description"]);
                end_row();
            }
	end_table(2);
}

function close_mtr($mtr_no, $closing_status=AS_COMPLETED) {
    $can_close_mtr = false;
    
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $mtrh = get_mtr_header_record_by_id($mtr_no);
    
        if (! ($mtrh['approval_status'] == AS_APPROVED || $mtrh['approval_status'] == AS_ISSUED || $mtrh['approval_status'] == AS_TRANSFERRED)) {
            $can_close_mtr = false;
            cancel_transaction();
            
            return array("success" => false, "message" => "Material Transfer Requisition $mtr_no status does not allow closing it.");
        }
        
//        $tasks_summary = calculate_mtr_task_remaining_totals($mtr_no);
//        $rta_msg = reallocate_to_tasks(ST_TRANSFERREQ, $mtr_no, $tasks_summary, $current_user_id);// step 1 table trans no
//            if ($rta_msg['success'] !== true) {
//                cancel_transaction();
//                return $rta_msg;
//            } else {
//                $can_close_mtr = true;
//            }
 
    
        if ($can_close_mtr) {
            $mtr_close_msg = direct_update_document_status(ST_TRANSFERREQ, $mtr_no, $closing_status, $mtrh['row_state']);     
                if ($mtr_close_msg['success'] !== true ) {
                    cancel_transaction();
                    return array("success" => false, "message" => $mtr_close_msg['message']);
                }
        }
    
        return array("success" => true, "message" => "");
}

?>