<?php
/**********************************************************************
***********************************************************************/

//-------------------------------------------------------------------------------------------------------------
include_once($path_to_root . "/inventory/includes/db/material_requisitions_db.inc");
include_once($path_to_root . "/includes/common_functions.inc");

function add_return_materials($items, $im_reference,  
                            $receiving_location, $project_id, $memo_, 
                            $source_mr_no, $mr_row_state, 
                            $approval_status, 
                            $company_code, $employee_code, $rm_date)
{
	global $loc_notification, $path_to_root, $Refs;
    $mr_no = $_SESSION['rm_items']->order_id;
    $current_user_id = $_SESSION['wa_current_user']->user;
        $type = ST_MATERIAL_RETURN;
        $date = sql2date(date('Y/m/d'));
        
        $created_by = $_SESSION['wa_current_user']->user;

	begin_transaction();
	$args = func_get_args();
	$args = (object)array_combine(array('items', 'im_reference', 
                                        'receiving_location', 'project_id', '$memo_', 
                                        'source_mr_no', ',$mr_row_state', 
                                        'approval_status', 'company_code', 'employee_code','rm_date'), $args);
	$args->trans_no = 0;
	hook_db_prewrite($args, $type);

    if($im_reference == '' || $im_reference == null )
    {
        $im_reference = get_next_trans_no($type);
    }

    //$mrt_no = get_next_trans_no($type);
    
    $rm_no = add_return_materials_header($im_reference, $receiving_location, 
                                        $project_id, $memo_, $source_mr_no, 
                                        $company_code, $employee_code, $rm_date, 
                                        $created_by);

    if(!$rm_no > 0)
    {
        cancel_transaction();
        return array("passed" => false, "tran_no" => $rm_no, "message" => "Could not create material return");
    }

    if ($loc_notification == 1)
	{
		include_once($path_to_root . "/inventory/includes/inventory_db.inc");
		$st_ids = array();
		$st_names = array();
		$st_num = array();
		$st_reorder = array();
	}
     
        
	foreach ($items as $line_item)
	{
        if($line_item->check_issue_item == true){
            if ($loc_notification == 1){
                $loc = calculate_reorder_level($receiving_location, $line_item, $st_ids, $st_names, $st_num, $st_reorder); 
            }

            if($line_item->tran_qty > 0){
                $item_info = get_item_edit_info($line_item->stock_id);
                
                $rmd_id = add_return_material_item($rm_no, $line_item->row_id,
                                                $line_item->stock_id, $line_item->tran_qty * $line_item->convertion_factor, $item_info['standard_cost'],
                                                $line_item->tran_unit, $line_item->tran_qty,
                                                $line_item->convertion_factor, $line_item->task_id,
                                                $line_item->project_site_id);
                        
                add_stock_move(ST_MATERIAL_RETURN, $line_item->stock_id, $rm_no, $receiving_location,
                        $rm_date, $im_reference, $line_item->tran_qty * $line_item->convertion_factor, $item_info['standard_cost'], 
                        null, null, null, null, 
                        null, $line_item->tran_unit, $line_item->tran_qty, $line_item->convertion_factor,
                        $line_item->task_id, $line_item->project_site_id, $rmd_id, $project_id);

                $ailqdm_msg =  add_item_line_quantity_detail_movements(ST_MATERIAL_RETURN, $rm_no, $receiving_location, 
                                                                        $rm_date, $line_item, false, '');
                if($ailqdm_msg['success'] !== true){
                    cancel_transaction();
                    return array("success" => $ailqdm_msg['success'], "tran_no" => $rm_no, "message" => $ailqdm_msg['message']);
                }

                update_mr_item_returned_qty($line_item->row_id, $line_item->tran_qty*$line_item->convertion_factor);

            }
        }
	}

	$Refs->save(ST_MATERIAL_RETURN, $rm_no, $im_reference);
	add_audit_trail(ST_MATERIAL_RETURN, $rm_no, $rm_date);
	
//	if ($loc_notification == 1 && count($st_ids) > 0)
//		send_reorder_email($loc, $st_ids, $st_names, $st_num, $st_reorder);  
        
        
	$args->trans_no = $rm_no;
	hook_db_postwrite($args, $type);

    $mr_details = get_material_return_details($rm_no);
    
    while ($myrow = db_fetch($mr_details))
    {
        $a['row_id'] = $myrow['mr_line_id'];
        $a['stock_id'] = $myrow['item_code'];
        $a['task_id'] = $myrow['task_id'];
        $a['requested_qty'] = $myrow['qty_returned'];
        $a['high_value_item'] = 0;
        $a['reference_cost'] = $myrow['standard_cost'];
        $a['standard_cost'] = $myrow['standard_cost'];
        $a['total_issued_qty'] = 0;
        $mr_details_array[] = $a;
    }
    
    foreach ($mr_details_array as &$mr_line){
        $mr_line['qty'] = 0;
        foreach ($items as $stk_item){
            if($stk_item->check_issue_item == true && $stk_item->row_id == $mr_line['row_id'] && abs($stk_item->tran_qty) > 0){
                $mr_line['qty'] = $stk_item->tran_qty * $stk_item->convertion_factor;
                break;
            }
        }
    }
    $tasks_summary = calculate_task_remaining_totals($mr_details_array);
    //$tasks_summary = calculate_mr_task_remaining_totals($items);
    
//    $apc_msg = allocate_to_tasks(ST_MATERIAL_REQ, $mr_no, 
//                                $tasks_summary, $current_user_id);
//    if($apc_msg['success'] !== true)
//    {
//        cancel_transaction();
//        return array("success" => $apc_msg['success'], "tran_no" => $mr_no, "message" => $apc_msg['message']);
//    }
    
    //$im_total = calculate_document_total($items);
    
    $rcft_msg = remove_costs_from_tasks(ST_MATERIAL_RETURN, $rm_no, 
                        $tasks_summary, $current_user_id);
     
    
    if($rcft_msg['success'] !== true)
    {
        cancel_transaction();
        return array("success" => $rcft_msg['success'], "tran_no" => $rm_no, "message" => $rcft_msg['message']);
    }
    
    commit_transaction();
    
//    if($mr_complete){
//        close_mr($source_mr_no);
//    }
//    else{
//        if(check_all_mr_lines_issued($source_mr_no)=== true){
//            close_mr($source_mr_no);
//        }
//    }
//            
	
        
    return array("success" => true, "tran_no" => $rm_no, "message" => "Material return $rm_no has been created");
}

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

function add_return_materials_header($reference,  $receiving_location,
                                    $project_id, $comment, $source_mr_no, 
                                    $company_code, $employee_code, $rm_date, 
                                    $created_by)
{
	//$mr_date = date2sql($date_);
        $created_on = date('Y-m-d H:i:s');

	$sql = "INSERT INTO ".TB_PREF."return_materials(reference,"
                        . " receiving_location,"
                        . " project_id,"
                        . " source_mr_no, "
                        . " company_code, "
                        . " employee_code, "
                        . " rm_date, "
                        . " comment, "
                        . " created_by, created_on) "
                . "VALUES (".db_escape($reference).", "
                        .db_escape($receiving_location).", "
                        .db_escape($project_id).", "
                        .db_escape($source_mr_no).", "
                        .db_escape($company_code).", "
                        .db_escape($employee_code).", "
                        .db_escape(date2sql($rm_date)).", " 
                        .db_escape($comment).", "
                        .db_escape($created_by).", ".db_escape($created_on).")";

		$error_msg = "Could not add_return_materials_header";

	db_query($sql, $error_msg);

	return db_insert_id();
}
//--------------------------------------------------------------------------------------------------

function add_return_material_item($rm_no, $mr_line_id,
                    $item_code, $qty_returned, $unit_cost,
                    $tran_unit, $tran_qty,
                    $conversion_factor, $task_id,
                    $site_id)
{
    $sql = "INSERT INTO ".TB_PREF."return_material_details (
                    rm_no, mr_line_id,
                    item_code, qty_returned, unit_cost,
                    tran_unit, tran_qty,
                    conversion_factor, task_id,
                    site_id) 
            VALUES (".db_escape($rm_no).", ".db_escape($mr_line_id).", "
                        .db_escape($item_code).", ".db_escape($qty_returned).", ".db_escape($unit_cost).", "
                        .db_escape($tran_unit).", ".db_escape($tran_qty).", "
                        .db_escape($conversion_factor).", ".db_escape($task_id).", "
                        .db_escape($site_id).")";
    
    db_query($sql, "Could not add_return_material_item.");
    return db_insert_id();
}


function get_material_return_header($mrt_no)
{
    $sql = "SELECT mrt.*, 
                    rl.location_name receiving_location_name,
                    il.location_name issuing_location_name,
                    u.real_name created_user_name 
            FROM ".TB_PREF."material_requisition_transfers mrt,
                    ".TB_PREF."locations rl,
                    ".TB_PREF."locations il,
                    ".TB_PREF."users u 
            WHERE mrt.issuing_location = il.loc_code AND 
                    mrt.receiving_location = rl.loc_code AND 
                    mrt.created_by = u.id AND  
                    mrt_no = '".$mrt_no."'";
    
    $result = db_query($sql);
    return db_fetch($result);
    
}

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

function get_material_return_details($rm_no)
{
    $sql = "SELECT  rmd.*,
                    sm.material_cost + sm.labour_cost + sm.overhead_cost AS standard_cost 
            FROM    ".TB_PREF."return_material_details rmd,
                    ".TB_PREF."stock_master sm   
            WHERE   rmd.item_code = sm.stock_id AND 
                    rmd.rm_no = ".db_escape($rm_no);
    
    $result = db_query($sql);
    
    return $result;
    
}

function get_return_materials($im_no)
{
    $sql = "SELECT DISTINCT im.*, 
                   il.location_name issuing_location_name,
                   apn.value_name task_description,
                   pm.description project_description,
                    u.real_name created_user_name 
            FROM ".TB_PREF."issue_materials im,
                    ".TB_PREF."locations il,
                        ".TB_PREF."projects_master pm, 
                        ".TB_PREF."project_tasks pt, 
                        ".TB_PREF."list_values apn, 
                    ".TB_PREF."users u 
            WHERE im.issuing_location = il.loc_code AND 
                    im.created_by = u.id AND  
                    im.task_id = pt.task_id AND
                    pt.type_id = apn.id AND
                    im_no = '".$im_no."'";
    
    $result = db_query($sql);
    return db_fetch($result);
    
}

function get_return_material_details_qty_returned($mr_line_id) {
    $sql = "SELECT SUM(qty_returned) total_qty_returned 
            FROM ".TB_PREF."return_material_details  
            WHERE mr_line_id = ".db_escape($mr_line_id);
    
        $result = db_query($sql, 'get_return_material_details_qty_returned');
        return db_result_value($result, 'total_qty_returned');
}

?>