<?php
/**********************************************************************
***********************************************************************/
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/ui/items_cart.inc");
include_once($path_to_root . "/includes/db/approval_functions_db.inc");
include_once($path_to_root . "/projects/includes/db/projects_db.inc");
//--------------------------------------------------------------------------------

function add_line_item_to_cart(&$order, $new_item, $new_item_qty, $standard_cost, $required_date, $line_comment, $tran_unit, $tran_qty, $convertion_factor)
{
//    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, $standard_cost , null, null, $required_date, $line_comment, 
                                            0, 0, 0, 0, 0, null, 0,null, null,null, null, null,$tran_unit, $tran_qty, $convertion_factor);
    }
}

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

function display_mr_header(&$order)
{
	global $Refs, $approval_statuses, $Ajax;
    
    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;
        }   
    }
            
    div_start('header_tbl');
	start_outer_table(TABLESTYLE2, "width=80%"); // outer table
	table_section(1);
        
        if($order->order_id > 0)
        {
            $mr_cart = $_SESSION['mr_items'];                
            
            if(isset($_POST['issuing_location'])){
                $mr_cart->issuing_location  = $_POST['issuing_location'];
            }
            locations_list_row(_("Issuing Location:"), 'issuing_location', $order->issuing_location);            
            
            if(isset($_POST['project_id'])){
                $mr_cart->project_id  = $_POST["project_id"];
            }
//            if(isset($_POST['approval_path_id'])){
//            $mr_cart->approval_path_id  = $_POST["approval_path_id"];
//            }

            
            if($order->count_items() > 0){
                hidden("project_id", $order->project_id);
                $_POST['project_id'] = $order->project_id;
                $job_ref = get_job_ref($_POST['project_id']);
                $order->job_reference = $job_ref['description'];
                label_row(_("Job Reference:"), $order->job_reference);
            }
            else{
                project_list_row(_("Project:"), 'project_id', $order->project_id,FALSE,TRUE);
            }

            if(list_updated('project_id') && $_POST['project_id'] != -1)
            {
                $job_ref = get_job_ref($_POST['project_id']);
                $order->job_reference = $job_ref['description'];
                label_row(_("Job Reference:"), $order->job_reference);
            }
            //tasks_list_row(_("Budget:"), 'task_id', $order->project_id, $order->task_id,FALSE,TRUE);
//            approval_path_list_row(_("Select Approval Path:"), 'approval_path_id', $order->approval_path_id,FALSE,TRUE);
            if ($_POST['project_id'] > 0)
            {
//                $result = get_project_approval_path($_POST['project_id']);
//                label_row(_("Approval Path:"), $result['approval_path_name']);
                label_row(_("Approval Path:"),"");
            }
            else {
                label_row(_("Approval Path:"),"");
            }
            
            $_POST['mr_date'] = sql2date($order->required_date);
            date_row(_("Date:"), 'mr_date', $_POST['mr_date']);
//            label_row("Approval Path:", $mr_cart->approval_path_description);
            //approval_path_list_row(_("Select Path Approval:"), 'approval_path_id', $order->approval_path_id,FALSE,TRUE);
            table_section(2, "33%");
            text_row(_("Reference:"), 'mr_reference', $order->reference, 10, 20);
//            label_row(_("Reference:"), $order->reference);
            

            if($order->sample_items == 1)
            {
                label_row(_("Sample Items:"), 'Yes');
            }
            else{
                label_row(_("Sample Items:"), 'No');
            }
            
            
            //yesno_list_row("Make Requisition Complete:", "mr_complete", $order->mr_complete);
            //yesno_list_row("Use Future Budgets:", "use_future_budget", $order->use_future_budget);
            table_section(3, "33%");
            movement_types_list_row(_("Movement Type:"), 'movement_type', ST_MATERIAL_REQ, $_POST['movement_type'], '', true);
            
            if (list_updated('movement_type')) {
                unset($_POST['linked_field_id']);
            }
            
            $movement_type = get_movement_type($_POST['movement_type']);
            switch ($movement_type['linked_field']) {
                case IMLF_CUSTOMER:
                    customer_list_row(_("Customer:"), 'linked_field_id', null, '');
                    break;
                case IMLF_SUPPLIER:
                    supplier_list_row(_("Supplier:"), 'linked_field_id', null, '');
                    break;
                case IMLF_EMPLOYEE:
                    employees_simple_list_row("Employee:", 'linked_field_id', null, '');
                    break;
                case IMLF_VEHICLE:
                    vehicles_list_row('Vehicle:', 'linked_field_id', null, '', true);
                    break;
                case IMLF_ASSET:
                    label_row(_("Asset:"), asset_list('linked_field_id', null, ''));
                    break;
                default:
                    hidden('linked_field_id', 0);
                    break;
            }
            
            hidden('linked_field_type', $movement_type['linked_field']);
             
            label_row(_("Requestor:"), $order->requestor_name);
//            label_row(_("Approval Status"), $approval_statuses[$order->approval_status]);
            $s = get_project_trans_view_str(ST_APPROVAL_LOG, $order->order_id."&source_type_id=".ST_MATERIAL_REQ, "Approval Status");
            //label_cell($s);
            label_row("$s:", $approval_statuses[$order->approval_status]);
        }
        else
        {
            //locations_list_row(_("Requesting Location:"), 'requesting_location', null);
            locations_list_row(_("Issuing Location:"), 'issuing_location', null,'', false);
          
            if($order->count_items() > 0){
                hidden("project_id", $order->project_id);
            }
            else{
                project_list_row(_("Project:"), 'project_id', null, _('Select a job'), true);
            }
            
            if(isset($order->job_reference) && !list_updated('project_id')){
                label_row(_("Job Reference:"), $order->job_reference);
            }

            if(list_updated('project_id') && $_POST['project_id'] != -1)
            {
                $job_ref = get_job_ref($_POST['project_id']);
                $order->job_reference = $job_ref['description'];
                label_row(_("Job Reference:"), $order->job_reference);
            }  
            //tasks_list_row(_("Budget:"), 'task_id', $_POST['project_id'], null, _('Select a budget'), true);
//            if ($_POST['project_id'] != -1)
//            {
//                $result = get_project_approval_path($_POST['project_id']);
//                label_row(_("Approval Path:"), $result['approval_path_name']);
//            }
//            else {
//                label_row(_("Approval Path:"),"");
//            }
            date_row(_("Date:"), 'mr_date', '', false);
            
            table_section(2, "33%");
            ref_row(_("Reference:"), 'mr_reference', '', $Refs->get_next(ST_MATERIAL_REQ));
            
            
            if(count($order->line_items) > 0 && isset($order->sample_items)){
                $Ajax->activate('header_tbl');
                if($order->sample_items == 1){
                    label_row(_("Sample Items:"), 'Yes');
                }
                else{
                    label_row(_("Sample Items:"), 'No');
                }
            }
            else{
                $Ajax->activate('header_tbl');
                yesno_list_row(_("Sample Items:"), 'sample_items');
            }
            
            //yesno_list_row("Make Requisition Complete:", "mr_complete");
            //yesno_list_row("Use Future Budgets:", "use_future_budget");
            
            
            table_section(3, "33%");
            movement_types_list_row(_("Movement Type:"), 'movement_type', ST_MATERIAL_REQ, null, '', true);
            
            if (list_updated('movement_type')) {
                unset($_POST['linked_field_id']);
            }
            
            if($_POST['movement_type'] > 0){
                $movement_type = get_movement_type($_POST['movement_type']);
                switch ($movement_type['linked_field']) {
                    case IMLF_CUSTOMER:
                        customer_list_row(_("Customer:"), 'linked_field_id', null, '');
                        break;
                    case IMLF_SUPPLIER:
                        supplier_list_row(_("Supplier:"), 'linked_field_id', null, '');
                        break;
                    case IMLF_EMPLOYEE:
                         employees_simple_list_row("Employee:", 'linked_field_id', null, '');
                        break;
                    case IMLF_VEHICLE:
                        vehicles_list_row('Vehicle:', 'linked_field_id', null, '', true);
                        break;
                    case IMLF_ASSET:
                        label_row(_("Asset:"), asset_list('linked_field_id', null, ''));
                        break;
                    default:
                        hidden('linked_field_id', 0);
                        break;
                }
                hidden('linked_field_type', $movement_type['linked_field']);
            }else{
                label_row(_("Linked Field:"),"");
                hidden('linked_field_type', -1);
            }
                    
            
            //emoplyees_list_row("Employee", 'employee_code', null, '');
            $id_user = $_SESSION['wa_current_user']->user;
            $user = get_requestor($id_user);
            label_row(_("Requestor:"), $user['real_name']);
            label_row(_("Approval Status:"), $approval_statuses[0]);
            
        }
	
        
//    if (!isset($_POST['Increase']))
//    	$_POST['Increase'] = 1;
//    yesno_list_row(_("Type:"), 'Increase', $_POST['Increase'],
//    	_("Positive Adjustment"), _("Negative Adjustment"));

	end_outer_table(1); // outer table
    div_end();
    $Ajax->activate('header_tbl');
//    if(list_updated('movement_type')){
//        $Ajax->activate('header_tbl');
//    }
}

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

function display_mr_items($title, &$order)
{
	global $path_to_root;

	display_heading($title);
    div_start('items_table');
	start_table(TABLESTYLE, "width=100%");
	$th = array(_("Item Code"), _("Item Description"), _("Quantity"),
		_("Unit"), _("Issued Qty"), _("Required Date"),_("Comment"), "Budget", "Site", "");
	if ( count($order->line_items)) $th[] = '';

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

//	$id = find_submit('Edit');
        
//        if(isset($_POST['LineNo']) && $_POST['LineNo'] >= 0){
//            $id = $_POST['LineNo'];
//        }
//        else{
            $id = find_submit('Edit');
//        }
        
	foreach ($order->line_items as $line_no=>$stock_item)
	{

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

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

                    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->tran_qty, false, get_qty_dec($stock_item->stock_id));
                    label_cell($stock_item->alternate_unit_name);
                    qty_cell($stock_item->issued_qty, false, $dec);
                    label_cell($stock_item->required_date);
                    label_cell($stock_item->line_comment);
                    label_cell($stock_item->task_description);
                    label_cell($stock_item->project_site_description);

                    edit_button_cell("Edit$line_no", _("Edit"),
                            _('Edit document line'));
                    delete_button_cell("Delete$line_no", _("Delete"),
                            _('Remove line from document'));
                    end_row();
		}
		else
		{
			mtr_edit_item_controls($order, $line_no);
		}
	}

	if ($id == -1)
		mtr_edit_item_controls($order);

//	$total = calculate_mr_remaining_total($order->line_items);
        $total = calculate_mr_remaining_total($order->line_items);
        $order->total = $total;
         label_cells(_("Total ".number_format($total,2)), "", "colspan=7 align=right","align=right");
    end_table();
   
	div_end();
}

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

function mtr_edit_item_controls(&$order, $line_no=-1)
{
	global $Ajax;
	start_row();

	$dec2 = 0;
//	$id = find_submit('Edit');
//        if(isset($_POST['LineNo']) && $_POST['LineNo'] >= 0){
//            $id = $_POST['LineNo'];
//        }
//        else{
            $id = find_submit('Edit');
//        }
        
	if ($line_no != -1 && $line_no == $id)
	{
            $_POST['stock_id'] = $order->line_items[$id]->stock_id;
            $_POST['qty'] = qty_format($order->line_items[$id]->requested_qty, $order->line_items[$id]->stock_id, $dec);
            $_POST['units'] = $order->line_items[$id]->units;
            $_POST['issued_qty'] = $order->line_items[$id]->issued_qty;
            $_POST['line_required_date'] = $order->line_items[$id]->required_date;
            $_POST['line_comment'] = $order->line_items[$id]->line_comment;
            $_POST['tran_qty'] = qty_format($order->line_items[$id]->tran_qty, $order->line_items[$id]->stock_id, $dec);

            $_POST['task_id'] = $order->line_items[$id]->task_id;
            $_POST['project_site_id'] = $order->line_items[$id]->project_site_id;

            hidden('stock_id', $_POST['stock_id']);
            label_cell($_POST['stock_id']);
            label_cell($order->line_items[$id]->item_description, 'nowrap');
	    $Ajax->activate('items_table');
	}
	else
	{
            stock_costable_items_list_cells(null, 'stock_id', null, false, true);
            if (list_updated('stock_id')) {
                $Ajax->activate('units');
                $Ajax->activate('qty');
                $Ajax->activate('issued_qty');
                $Ajax->activate('tran_unit');
                $Ajax->activate('tran_qty');
            }
            
            if($_POST['stock_id'] > 0){
                    $item_info = get_item_edit_info($_POST['stock_id']);
                    $dec = $item_info['decimals'];
                    $_POST['qty'] = number_format2(0, $dec);
                    //$_POST['std_cost'] = price_format($item_info["standard_cost"]);
                    $_POST['units'] = $item_info["units"];
                    $_POST['issued_qty'] = number_format2(0, $dec);
                    $_POST['line_required_date'] = $_POST['mr_date'];
                    $_POST['line_comment'] = "";
            }else{
                    $dec = 2;
                    $_POST['qty'] = number_format2(0, $dec);
                    //$_POST['std_cost'] = price_format($item_info["standard_cost"]);
                    $_POST['units'] = "";
                    $_POST['issued_qty'] = number_format2(0, $dec);
                    $_POST['line_required_date'] = "";
                    $_POST['line_comment'] = "";
            }

            hidden('qty', $_POST['qty']);
            hidden('units', $_POST['units']);
	}

	qty_cells(null, 'tran_qty', null, null, null, $dec);
	if ($line_no != -1 && $line_no == $id)
    {
        label_cell($order->line_items[$id]->alternate_unit_name);
    }
    else{
        units_list_cells(null, 'tran_unit', $_POST['stock_id'], null, false, true);
    }
    qty_cell($_POST['issued_qty'], false, $dec);

    date_cells('', 'line_required_date');

    text_cells('', 'line_comment',null,30);
    tasks_list_cells(null, 'task_id', $_POST['project_id'], null, _('Select a budget'));
    project_sites_list_cells(null, 'project_site_id', $_POST['project_id'], null,'');
	//label_cell("&nbsp;");

	if ($id != -1)
	{
		button_cell('UpdateItem', _("Update"),
				_('Confirm changes'), ICON_UPDATE);
		button_cell('CancelItemChanges', _("Cancel"),
				_('Cancel changes'), ICON_CANCEL);
		hidden('LineNo', $line_no);
 		set_focus('qty');
	}
	else
	{
		submit_cells('AddItem', _("Add Item"), "colspan=2",
		    _('Add new item to document'), true);
	}

	end_row();
}


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

function mr_options_controls($mr_cart)
{
	  echo "<br>";
	  start_table();

      if(isset($mr_cart->memo_)){
          $memo = $mr_cart->memo_;
      }
      else{
          $memo = "";
      }
	  textarea_row(_("Memo:"), 'memo_', $memo, 50, 3);

	  end_table(1);
}

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

function handle_new_item()
{
//    if(!isset($_SESSION['sample_item'])){
////        $_SESSION['sample_item'] = check_value('sample_item');
//        set_session_variable('sample_item', check_value('sample_item'));
//    }
    
	if (!check_item_data($_SESSION['mr_items']))
		return false;
        
        $item_info = get_stock_item_edit_info($_POST['stock_id']);
        $alternate_unit = get_convertion_factor($_POST['tran_unit'], $_POST['stock_id']);
        $convertion_factor = $alternate_unit['convertion_factor'];    
        
	add_line_item_to_cart($_SESSION['mr_items'], $_POST['stock_id'],input_num('qty'), 
                                $item_info['standard_cost'], $_POST['line_required_date'], $_POST['line_comment'], 
                                $_POST['tran_unit'], input_num('tran_qty'), $convertion_factor);
        
    $adj = &$_SESSION['mr_items'];
    $current_element = (count($adj->line_items)-1);
//    $adj->line_items[$current_element]->requested_qty = $_POST['qty'];
    $adj->line_items[$current_element]->row_id = get_post('row_id');
    $adj->line_items[$current_element]->high_value_item = $item_info["high_value_item"];
    $adj->line_items[$current_element]->sample_item = $item_info["sample_item"];
    $adj->line_items[$current_element]->reference_cost = $item_info["reference_cost"];

    if(count($adj->line_items) > 0 && !isset($adj->sample_items)){
        $adj->sample_items = $_POST['sample_items'];
    }
    elseif(isset($_POST['sample_items']) && $adj->sample_items != $_POST['sample_items']){
        $adj->sample_items = $_POST['sample_items'];
    }
    
    $task_id = 0;
    $task_description = '';
    if($_POST['task_id'] != -1){
        $project_task = get_task_details($_POST['task_id']);
        $task_id = $project_task['task_id'];
        $task_description = $project_task['description'];
    }
    $adj->line_items[$current_element]->task_id = $task_id;
    $adj->line_items[$current_element]->task_description = $task_description;
    
    $project_site_id = 0;
    $project_site_description = '';
    if($_POST['project_site_id'] != -1){
        $project_site = get_project_site_details($_POST['project_site_id']);
        $project_site_id = $project_site['id'];
        $project_site_description = $project_site['description'];
    }
    $adj->line_items[$current_element]->project_site_id = $project_site_id;
    $adj->line_items[$current_element]->project_site_description = $project_site_description; 
        
    line_start_focus();
    
}



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

function handle_delete_item($id)
{
	if(check_delete_item($id))
        {
            $_SESSION['mr_items']->remove_from_cart($id);
            line_start_focus();
        }
}


//-----------------------------------------------------------------------------------------------
   
        
function handle_update_item()
{
    $id_edit = $_POST['LineNo'];
    
    if($_POST['UpdateItem'] != "" && check_item_data($_SESSION['mr_items']) && check_update_item($id_edit))
    {
    	$adj = &$_SESSION['mr_items'];
        
        $convesion_factor = $adj->line_items[$id_edit]->convertion_factor;
        $item_info = get_item_edit_info($_POST['stock_id']);
        
        $tran_unit = $adj->line_items[$id_edit]->tran_unit;
        
        get_convertion_factor2($_POST['stock_id'], $tran_unit, $convesion_factor);
        
        $adj->update_cart_item($id_edit, input_num('tran_qty')*$convesion_factor, $item_info['standard_cost'], null, 
                $_POST['line_comment'], $_POST['line_required_date'], null, null, 
                input_num('tran_qty'), $tran_unit, $convesion_factor);
        
        $adj->line_items[$id_edit]->requested_qty = input_num('tran_qty')*$convesion_factor;
        $adj->line_items[$id_edit]->required_date = $_POST['line_required_date'];
        $adj->line_items[$id_edit]->line_comment = $_POST['line_comment'];
        
        $task_id = 0;
        $task_description = '';
        if($_POST['task_id'] != -1){
            $project_task = get_task_details($_POST['task_id']);
            $task_id = $project_task['task_id'];
            $task_description = $project_task['description'];
        }
        $adj->line_items[$id_edit]->task_id = $task_id;
        $adj->line_items[$id_edit]->task_description = $task_description;
        
        $project_site_id = 0;
        $project_site_description = '';
        if($_POST['project_site_id'] != -1){
            $project_site = get_project_site_details($_POST['project_site_id']);
            $project_site_id = $project_site['id'];
            $project_site_description = $project_site['description'];
        }
        $adj->line_items[$id_edit]->project_site_id = $project_site_id;
        $adj->line_items[$id_edit]->project_site_description = $project_site_description;
        
//        $_POST['LineNo'] =-1;
        
        line_start_focus();
    }
	
}

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

function check_update_item($id_edit)
{
	global $Refs;

    $adj = &$_SESSION['mr_items'];
    $convertion_factor = $adj->line_items[$id_edit]->convertion_factor;
     
    if ((input_num('tran_qty')*$convertion_factor) < $adj->line_items[$id_edit]->issued_qty) 
	{
		display_error( _("Can not reduce quantity below issued quantity."));
		set_focus('stock_id');
		return false;
	}

    return true;
}
 

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

function check_delete_item($id)
{
	global $Refs;
        
        $adj = &$_SESSION['mr_items'];

        if ($adj->line_items[$id]->issued_qty > 0) 
	{
		display_error( _("This item has some quantities issued. Not possible to delete."));
		set_focus('stock_id');
		return false;
	}
        return true;
}
 
//-----------------------------------------------------------------------------------------------

function check_item_data(&$order)
{
    
    if(isset($order->sample_items)){
        
        if(isset($_POST['sample_items']) && $order->sample_items != $_POST['sample_items']){
            if($_POST['sample_items'] == 1)
            {
                $item = get_item($_POST['stock_id']);
                if($item['sample_item'] != 1)
                {
                    display_error(_("Selected item is not a sample item."));
                    set_focus('stock_id');
                    return false;
                }    
            }
            else
            {
                $item = get_item($_POST['stock_id']);
                if($item['sample_item'] != 0)
                {
                    display_error(_("Selected item is a sample item."));
                    set_focus('stock_id');
                    return false;
                }    
            }
        }
        else{
            if($order->sample_items == 1)
            {
                $item = get_item($_POST['stock_id']);
                if($item['sample_item'] != 1)
                {
                    display_error(_("Selected item is not a sample item."));
                    set_focus('stock_id');
                    return false;
                }    
            }
            else
            {
                $item = get_item($_POST['stock_id']);
                if($item['sample_item'] != 0)
                {
                    display_error(_("Selected item is a sample item."));
                    set_focus('stock_id');
                    return false;
                }    
            }
        }
             
    }
    else{
        if($_POST['sample_items'] == 1)
        {
            $item = get_item($_POST['stock_id']);
            if($item['sample_item'] != 1)
            {
                display_error(_("Selected item is not a sample item."));
                set_focus('stock_id');
                return false;
            }    
        }
        else
        {
            $item = get_item($_POST['stock_id']);
            if($item['sample_item'] != 0)
            {
                display_error(_("Selected item is a sample item."));
                set_focus('stock_id');
                return false;
            }    
        }
    }
    
    if ($_POST['stock_id'] == '') {
        display_error(_("Please select an item."));
        set_focus('stock_id');
        return false;
    }
    
    if (!check_num('tran_qty',0.01))
    {
            display_error(_("The quantity entered is negative or invalid."));
            set_focus('tran_qty');
            return false;
    }
    if (!is_date($_POST['line_required_date'])) 
	{
		display_error(_("The entered date for the material requisition item is invalid."));
		set_focus('line_required_date');
		return false;
	}
    
    if ($_POST['task_id'] <= 0 )
	{
		display_error(_("Please select a budget."));
		set_focus('task_id');
		return false;
	}
    
   	return true;
}

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

function send_mr_back_to_originator()
{
    if(!can_process_mr()){
        return;
    }
    
    $mr = $_SESSION['mr_items'];
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rd_msg = send_back_to_document_originator($mr->trans_type, $mr->order_id, $mr->project_id,
                                    $mr->next_approval_group_id, $current_user_id, $mr->row_state, 
                                    $mr->created_by);
    
    if($rd_msg['success'] !== true){
        cancel_transaction();
        display_error($rd_msg['message']);
    }
    else{
        $trans_no = $rd_msg['tran_no'];
        new_doc_date($_POST['mr_date']);
        $_SESSION['mr_items']->clear_items();
        unset($_SESSION['mr_items']);
        set_session_variable('mr_messages', $rd_msg['message']);
        
        meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
    }
}



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

function reject_mr()
{
    if(!can_process_mr()){
        return;
    }
    
    $mr = $_SESSION['mr_items'];
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rd_msg = reject_document($mr->trans_type, $mr->order_id, $mr->project_id,
                    $mr->next_approval_group_id, $current_user_id, $mr->row_state);
    
    if($rd_msg['success'] !== true){
        cancel_transaction();
        display_error($rd_msg['message']);
    }
    else{
        $trans_no = $rd_msg['tran_no'];
        new_doc_date($_POST['mr_date']);
        $_SESSION['mr_items']->clear_items();
        unset($_SESSION['mr_items']);
        set_session_variable('mr_messages', "Material requisition ".$rd_msg['tran_no']." has been rejected.");
        
        meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
    }

}



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


function add_mr($release = false)
{

	clear_session_variable('mr_messages');
        
        $amr_msg = add_material_requisition($_SESSION['mr_items'], $_SESSION['mr_items']->line_items, $_POST['mr_reference'],	
                $_POST['issuing_location'], $_POST['project_id'],
                $_POST['mr_date'], $_POST['memo_'], 0,
                $release, $_POST['movement_type'], $_SESSION['mr_items']->sample_items,
                get_post('linked_field_type'), $_POST['linked_field_id']);

        if($amr_msg['success'] !== true){
            display_error($amr_msg['message']);
        }
        else{
            $trans_no = $amr_msg['tran_no'];
            new_doc_date($_POST['mr_date']);
            $_SESSION['mr_items']->clear_items();
            unset($_SESSION['mr_items']);
            if($release == true){
                set_session_variable('mr_messages', $amr_msg['message']);
            }
            else{
                $text = $amr_msg['tran_no'];
                set_session_variable('mr_messages', "Material requisition $text has been created.");
            }
            meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
        }
        
        
        
} 




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

function update_mr($release = false)
{
        clear_session_variable('mr_messages');
        
    	$umr_msg = update_material_requisition($_SESSION['mr_items']->order_id, $_SESSION['mr_items'],
                        $_POST['issuing_location'], $_POST['project_id'], 
                        $_POST['mr_date'], $_POST['memo_'], 0, 
                        $_POST['mr_reference'], $release, $_POST['movement_type'],
                        $_SESSION['mr_items']->row_state,
                        get_post('linked_field_type'), $_POST['linked_field_id']);
        
        if($umr_msg['success'] !== true){
             display_error($umr_msg['message']);
             return;
        }
        else{
            $text = $umr_msg['message'];
            $trans_no = $_SESSION['mr_items']->order_id;
            new_doc_date($_POST['mr_date']);
            $_SESSION['mr_items']->clear_items();
            unset($_SESSION['mr_items']);
            if($release == true){
                set_session_variable('mr_messages', $text);
            }
            else{
                $text = $umr_msg['message'];
                set_session_variable('mr_messages', $text);
            }

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



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

function can_process_mr()
{
        global $Refs;
        $adj = &$_SESSION['mr_items'];       

        if($adj->order_id > 0){
            $mr_info = get_mr_edit_info($adj->order_id);
            if(!($mr_info['approval_status'] == AS_NEW || $mr_info['approval_status'] == AS_WITH_THE_APPROVER || $mr_info['approval_status'] == AS_AWAITING_APPROVAL)){
                display_error("This Material Requisition status does not allow further updating.");
                return false;
            }
        
            $ced_msg = can_edit_document($adj->trans_type, $adj->project_id, $adj->next_approval_group_id, 
                                $_SESSION['wa_current_user']->user, $adj->created_by);
            if($ced_msg['success'] !== true){
                    display_error( $ced_msg['message']);
                    set_focus('issuing_location');
                    return false;
            }
        }
        
        if ($_POST['issuing_location'] == '') 
        {
                $input_error = 1;
                display_error( _('Select issuing location.'));
                set_focus('issuing_location');
                return false;
        }
        
        if (!$_POST['project_id'] > 0) 
        {
                $input_error = 1;
                display_error( _('Select a project.'));
                set_focus('project_id');
                return false;
        }

        
        if (! ($_POST['movement_type'] > 0)) {
            $input_error = 1;
            display_error( _('Select a movement type.'));
            set_focus('movement_type');
            return false;
        } else {
            $mv_tp = get_movement_type($_POST['movement_type']);
                if ($mv_tp['linked_field'] != IMLF_NOT_LINKED) {
                    
                    global $inventory_movement_type_linked_fields;
                    
                    switch ($mv_tp['linked_field']) {
                        case IMLF_EMPLOYEE:
                            if((strlen($_POST['linked_field_id']) <= 2)) {
                                $input_error = 1;
                                display_error( _('Select an '.$inventory_movement_type_linked_fields[$mv_tp['linked_field']].'.'));
                                set_focus('linked_field_id');
                                return false;
                            }
                            break;
                        case IMLF_ASSET:
                            if (! ($_POST['linked_field_id'] > 0)) {
                                $input_error = 1;
                                display_error( _('Select an '.$inventory_movement_type_linked_fields[$mv_tp['linked_field']].'.'));
                                set_focus('linked_field_id');
                                return false;
                            }
                            break;
                        default :
                            if (! ($_POST['linked_field_id'] > 0)) {
                                $input_error = 1;
                                display_error( _('Select a '.$inventory_movement_type_linked_fields[$mv_tp['linked_field']].'.'));
                                set_focus('linked_field_id');
                                return false;
                            }
                            break;
                    }
                    
                    if ($mv_tp['linked_field'] == IMLF_ASSET) {
                        $asset_row = get_asset($_POST['linked_field_id']);
                            if ($asset_row['type'] == AT_VEHICLE) {
                                $message = 'Selected asset is a Vehicle. Only the assets of types "Fixed Asset" and "Tool" are allowed under this Movement Type.';
                                display_error($message);
                                set_focus('linked_field_id');
                                return false;
                            }
                    }
                }
        }
        
//        if($_POST['mr_complete'] == 1){
//            return "close_only";
//        }
        if ($_POST['project_id'] == -1) 
        {
                $input_error = 1;
                display_error( _('Select a project.'));
                set_focus('project_id');
                return false;
        }

        if (!$Refs->is_valid($_POST['mr_reference'])) 
        {
                display_error( _("You must enter a reference."));
                set_focus('mr_reference');
                return false;
        }


        $ref_msg = reference_exists($_POST['mr_reference'], ST_MATERIAL_REQ, $adj->order_id);
        if($ref_msg)        
        {
                display_error( $ref_msg);
                set_focus('mr_reference');
                return false;
        }
            
        if(($adj->order_id == 0 ) || ($adj->order_id == null) || ($adj->order_id == "" ))
        {
//            if ($_POST['requesting_location'] == $_POST['issuing_location']) 
//            {
//                    display_error( _("Requesting location and Issuing location can not be same"));
//                    set_focus('requesting_location');
//                    return false;
//            }
 
        }
        
        if (!is_date($_POST['mr_date'])) 
        {
                display_error(_("The entered date for the material requisition is invalid."));
                set_focus('mr_date');
                return false;
        } 

//        if (!is_date_in_fiscalyear($_POST['mr_date'])) 
//        {
//                display_error(_("The entered date is not in fiscal year."));
//                set_focus('mr_date');
//                return false;
//        } 
            
        if (count($adj->line_items) == 0)	
        {
            display_error(_("You must enter at least one non empty item line."));
            set_focus('stock_id');
            return false;
	}
        
	return true;
}
//---------------------------------------------------------------------------------

?>