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

function add_mtr_to_cart(&$order, $new_item, $new_item_qty, $required_date, $line_comment, $standard_cost, $tran_unit, $tran_qty, $convertion_factor) {
    $order->add_to_cart(count($order->line_items), $new_item, $new_item_qty, $standard_cost, null, null, 
                        $required_date, $line_comment, 0, 0, $new_item_qty, 0, 0, null, 0,null, null,null, null, null,
                        $tran_unit, $tran_qty, $convertion_factor);
}

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

function display_mtr_header(&$order)
{
	global $Refs, $approval_statuses, $Ajax;
    
    if(isset($order->order_no) && $order->order_no > 0){
        $mtr_cart = $_SESSION['mtr_items'];

        $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)
        {
            $mtr_cart = $_SESSION['mtr_items'];

            if(isset($_POST['issuing_location'])){
                $mtr_cart->issuing_location  = $_POST['issuing_location'];
            }
            if(isset($_POST['project_id'])){
            $mtr_cart->project_id  = $_POST["project_id"];
            }
//            if(isset($_POST['task_id'])){
//            $mtr_cart->task_id  = $_POST["task_id"];
//            }

            locations_list_row(_("Issuing Location:"), 'issuing_location', $order->issuing_location);
            locations_list_row(_("Reqesting Location:"), 'requesting_location', $order->requesting_location);
            
            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(_("Requesting From 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);
            } 

//            if ($_POST['project_id'] != -1)
//            {
//                $result = get_approval_path($_POST['project_id'], "MR");
//                label_row(_("Approval Path:"), $result['approval_path_name']);
//            }
//            else {
//                label_row(_("Approval Path:"),"");
//            }
            
            table_section(2, "33%");
            text_row(_("Reference:"), 'mtr_reference', $order->reference, 10, 20);
//            label_row(_("Reference:"), $order->reference);
            $_POST['mtr_date'] = sql2date($order->required_date);
            date_row(_("Date:"), 'mtr_date', $_POST['mtr_date']);

            if($order->sample_items == 1)
            {
                label_row(_("Sample Items:"), 'Yes');
            }
            else{
                label_row(_("Sample Items:"), 'No');
            }
            
            //yesno_list_row("Make Requisition Complete:", "mtr_complete", $order->mtr_complete);
            
            table_section(3, "30%");
            
            if(isset($_POST['movement_type'])){
                $movement_type = $_POST['movement_type'];
            }
            else{
                $movement_type = $order->movement_type;
            }
            movement_types_list_row(_("Movement Type:"), 'movement_type', ST_TRANSFERREQ, $movement_type, '', true);
            
            if(! isset($_POST['linked_field_id'])){
                $_POST['linked_field_id'] = $order->linked_field_id;
            }
            
            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);
            $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]);
        }
        else
        {
            locations_list_row(_("Requesting Location:"), 'requesting_location', null, null, false);
            locations_list_row(_("Issuing Location:"), 'issuing_location', null, null, false);
            
            if($order->count_items() > 0){
                hidden("project_id", $order->project_id);
            }
            else{
                project_list_row(_("Requsting From Project:"), 'project_id', $order->project_id,FALSE,TRUE);
            }
            
            //project_list_row(_("Job:"), '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) || 
                    (!isset($order->job_reference) && $_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);
            }

//            if ($_POST['project_id'] != -1)
//            {
//                $result = get_approval_path($_POST['project_id'], "MR");
//                label_row(_("Approval Path:"), $result['approval_path_name']);
//            }
//            else {
//                label_row(_("Approval Path:"),"");
//            }
            
            
            
            table_section(2, "33%");
            ref_row(_("Reference:"), 'mtr_reference', '', $Refs->get_next(ST_TRANSFERREQ));
            date_row(_("Date:"), 'mtr_date', '', false);

            
            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:", "mtr_complete");
            
            
            table_section(3, "33%");
            
            //yesno_list_row("Use Future Budgets:", "use_future_budget");
            movement_types_list_row(_("Movement Type:"), 'movement_type', ST_TRANSFERREQ, null, '', 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']);
             
            $id_user = $_SESSION['wa_current_user']->user;
            $user = get_requestor_for_mtr($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(2); // outer table
    div_end();
    $Ajax->activate('header_tbl');
}

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

function display_mtr_items($title, &$order) {
//    global $path_to_root;
    display_heading($title);    br();
    
    div_start('items_table');
	start_table(TABLESTYLE, "width=100%");
	$th = array(_("Item Code"), _("Item Description"), _("Quantity"), _("Unit"), _("Issued Qty"), _("Required Date"), _("Comment"), "", "");
	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);

                    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));
//                    if($stock_item->tran_unit == ""){
//                        label_cell($stock_item->units);
//                    }
//                    else{
//                        label_cell($stock_item->tran_unit);
//                    }
                    label_cell($stock_item->alternate_unit_name);
//                    qty_cell($stock_item->requested_qty, false, $dec);
//                    label_cell($stock_item->units);
                    qty_cell($stock_item->issued_qty, false, $dec);
                    label_cell($stock_item->required_date);
//                    label_cell($stock_item->task_description);
                    label_cell($stock_item->line_comment);
                    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_mtr_remaining_total($order->line_items);
            $order->total = $total;
            label_cells(_("Total ".$total), "", "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 ($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['issued_qty'] = $order->line_items[$id]->issued_qty;
            $_POST['tran_qty'] = qty_format($order->line_items[$id]->tran_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['project_site_id'] = $order->line_items[$id]->project_site_id;
//            if (! ($_POST['task_id'] > 0)) {
//                $_POST['task_id'] = $order->line_items[$id]->task_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('tran_unit');
                $Ajax->activate('tran_qty');
			    $Ajax->activate('qty');
			    $Ajax->activate('issued_qty');
		}
               
            $item_info = get_item_edit_info($_POST['stock_id']);
            $dec = $item_info['decimals'];
            $_POST['qty'] = number_format2(0, $dec);
            $_POST['units'] = $item_info["units"];
            $_POST['issued_qty'] = number_format2(0, $dec);
            $_POST['line_required_date'] = $_POST['mtr_date'];
            $_POST['line_comment'] = "";
                
        }
	qty_cells(null, 'tran_qty', null, null, null, $dec);
        
        if ($line_no != -1 && $line_no == $id)
	{
            $tran_unit = $order->line_items[$id]->tran_unit;
//            $_POST['std_cost'] = $_POST['std_cost'];
            if($tran_unit == ""){
                label_cell($order->line_items[$id]->units);
            }
            else{
                label_cell($order->line_items[$id]->tran_unit);
            }
        }
        else{
            units_list_cells(null, 'tran_unit', $_POST['stock_id'], null, false, true);
        }
        hidden('qty', $_POST['qty']);
        hidden('units', $_POST['units']);    
            
        qty_cell($_POST['issued_qty'], false, $dec);
        
        date_cells('', 'line_required_date');
        
//        tasks_list_cells(null, 'task_id', $_POST['project_id'], null, _('Select a budget'));
        
        text_cells('', 'line_comment',null,30);
        
        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 mtr_options_controls($mtr_cart)
{
	  echo "<br>";
	  start_table();

	  textarea_row(_("Memo:"), 'memo_', $mtr_cart->memo_, 50, 3);

	  end_table(1);
}

//function calculate_mtr_task_remaining_totals($mrt_no) {
//    $mrt_details = get_mtr_details($mrt_no);
//        while ($myrow = db_fetch($mrt_details)) {
//            $a['row_id'] = $myrow['id'];
//            $a['stock_id'] = $myrow['stock_id'];
//            $a['task_id'] = $myrow['task_id'];
//            $a['requested_qty'] = $myrow['requested_qty'];
//            $a['high_value_item'] = $myrow['high_value_item'];
//            $a['reference_cost'] = $myrow['standard_cost'];
//            $a['standard_cost'] = $myrow['standard_cost'];
//            $a['total_issued_qty'] = $myrow['issued_qty'];
//            $a['qty'] = $myrow['requested_qty']; 
//            $mrt_details_array[] = $a;
//        }
//    
//    $mrt_tasks_summary = calculate_task_remaining_totals($mrt_details_array);
//    
//    return $mrt_tasks_summary;
//}

?>