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

function add_work_order_issue($woid, $ref, $to_work_order, 
                                $items, $header_location, $workcentre,
                                $date_, $memo_, $project_id, $task_id,
                                $employee_code, $supp_id, $close)
{
	global $Refs;

	begin_transaction();
	$args = func_get_args();
	$args = (object)array_combine(array('woid', 'ref', 'to_work_order', 
                                'items', 'location', 'workcentre', 
                                'date_', 'memo_', 'project_id', 'task_id', 
                                'employee_code', 'supp_id','close'), $args);
    
	$args->trans_no = 0;
	hook_db_prewrite($args, ST_MANUISSUE);

    $current_user_id = $_SESSION['wa_current_user']->user;
    
	$details = get_work_order($woid);

    if (strlen($details[0]) == 0)
    {
    	cancel_transaction();
        return array("success" => false, "tran_no" => 0, "message" => "The order number sent is not valid.");
    }

	if (work_order_is_closed($woid))
	{
		cancel_transaction();
        return array("success" => false, "tran_no" => 0, "message" => "UNEXPECTED : Issuing items for a closed Work Order");
	}

	$woi_number = add_workorder_issue_header($woid, $ref, $date_, $header_location, $workcentre, $project_id, $task_id ,$employee_code, $supp_id);

	$issue_total = $total_cost = 0;
    $tasks_charging_cost_summary = array();
    
	foreach ($items as &$item)
	{
        if(!isset($item->check_issue_item)){
            continue;
        }
        if(!$item->check_issue_item){
            continue;
        }
        
        $increase = true;
        $item->quantity = $item->tran_qty * $item->convertion_factor;
		if($to_work_order){
			$item->quantity = -$item->quantity;
            $item->tran_qty = - $item->tran_qty;
            $increase = false;
        }
        
		//Chaitanya: Stamp the standard_cost
		$item->standard_cost = get_standard_cost($item->stock_id);
        
        add_workorder_issue_details($woi_number, $item);
        
        if(isset($item->material_line_id) && $item->material_line_id > 0){
            update_workorder_material_issue_qty($woid, $item->material_line_id, $item->quantity);
        }
		// insert a -ve stock move for each item
		add_stock_move(ST_MANUISSUE, $item->stock_id, $woi_number,
                    $item->loc_code, $date_, $ref, -$item->quantity, $item->standard_cost, null, null, null, 
                        null, null, $item->tran_unit, $item->tran_qty, $item->convertion_factor, $task_id);

        $ailqdm_msg =  add_item_line_quantity_detail_movements(ST_MANUISSUE, $woi_number, $item->loc_code, 
                                                                    $date_, $item, $increase, $ref);
        if($ailqdm_msg['success'] !== true){
            cancel_transaction();
            return $ailqdm_msg;
        } 

        

		//$standard_cost = get_standard_cost($item->stock_id);
		$issue_cost = $item->standard_cost * $item->quantity;
		$issue = get_stock_gl_code($item->stock_id);
        $stockitem = get_item($item->stock_id);
		
		//Chaitanya : Compatibility for Service Items
		if (!is_service($issue["mb_flag"])){
			$ivaccount = $issue["inventory_account"];
        }
		else{
			$ivaccount = $issue["cogs_account"];	
        }
		
        $total_cost += add_gl_trans_std_cost(ST_WORKORDER, $woid, $date_, $ivaccount, 0, 0,
                $date_.": "._("Issue of")." ".$stockitem["description"], -$issue_cost);	
        
        $issue_total += $issue_cost;
	}
    
    
	if ($issue_total != 0){
		//Chaitanya : Apply cost to QOH as adjustment only
		add_issue_cost($details['stock_id'], $details['units_reqd'], $date_, $issue_total, true);
    }
    
    if($close){
        close_work_order_for_issues($woid);
    }
    
    add_to_task_cost($tasks_charging_cost_summary, $task_id, $issue_total, $issue_total, $issue_total);
    
    
	//$issue = get_stock_gl_code($details['stock_id']);
    $stockitem = get_item($details['stock_id']);
    
    add_gl_trans_std_cost(ST_WORKORDER, $woid, $date_, $stockitem["assembly_account"],
                    0, 0, $date_.": "._("Issue to")." ".$stockitem["description"], -$total_cost);	

    
    $material_cost = 0;
    $wom_cost = get_work_order_remaining_material_cost($woid);
    if(isset($wom_cost['total_cost'])){
        $material_cost = $wom_cost['total_cost'];
    }
       
    $labour_cost = 0;
    $wol_cost = get_work_order_remaining_labour_cost($woid);
    if(isset($wol_cost['total_cost'])){
        $labour_cost = $wom_cost['total_cost'];
    }
    
    $wo_remaining_cost = $material_cost + $labour_cost;

    $tasks_new_allocation_summary = array();
    add_to_task_cost($tasks_new_allocation_summary, $task_id, $wo_remaining_cost, $wo_remaining_cost, $wo_remaining_cost);
    get_task_cost_details($tasks_new_allocation_summary);
    
    $at_msg = allocate_to_tasks(ST_WORKORDER, $woid, $tasks_new_allocation_summary, $current_user_id);  
    if($at_msg['success'] !== true)
    {
        cancel_transaction();
        return array("success" => $at_msg['success'], "tran_no" => $woid, "message" => $at_msg['message']);
    }
    
    get_task_cost_details($tasks_charging_cost_summary);
    $cct_msg = charge_cost_to_tasks(ST_MANUISSUE, $woi_number, $tasks_charging_cost_summary, $current_user_id);
    if ($cct_msg['success'] !== true)
    {
    	cancel_transaction();
        return array("success" => false, "tran_no" => $woi_number, "message" => $cct_msg["message"]);
    }
    
    
	if ($memo_){
		add_comments(ST_MANUISSUE, $woi_number, $date_, $memo_);
    }

	$Refs->save(ST_MANUISSUE, $woi_number, $ref);
	add_audit_trail(ST_MANUISSUE, $woi_number, $date_);

	$args->trans_no = $woi_number;
	hook_db_postwrite($args, ST_MANUISSUE);
	commit_transaction();
    
    return array("success" => true, "tran_no" => $woi_number, "message" => "");
}

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

function add_workorder_issue_header($woid, $ref, $date_, $location, $workcentre, $project_id, $task_id ,$employee_code, $supp_id)
{
    // insert the actual issue
    $created_by = $_SESSION['wa_current_user']->user;
    $created_on = date('Y-m-d H:i:s');
    
	$sql = "INSERT INTO ".TB_PREF."wo_issues (workorder_id, reference, 
                        issue_date, loc_code, 
                        workcentre_id,
                        project_id, task_id,employee_code,supplier_id,
                        created_by, created_on)
            VALUES (".db_escape($woid).", ".db_escape($ref).", '"
                        .date2sql($date_) . "', ".db_escape($location).", "
                        .db_escape($workcentre).","
                        .db_escape($project_id).", ".db_escape($task_id).", "
                        .db_escape($employee_code).", ".db_escape($supp_id).", "
                        .db_escape($created_by).", ".db_escape($created_on).")";
    
	db_query($sql,"The work order issue could not be added");

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



function add_workorder_issue_details($woi_number, $item)
{
    $sql = "INSERT INTO ".TB_PREF."wo_issue_items (issue_id, process_id, 
                                    stock_id, qty_issued, 
                                    issued_unit, issued_unit_qty, 
                                    issued_unit_conv_factor)
			VALUES (".db_escape($woi_number).", ".db_escape($item->process_id).", "
                                .db_escape($item->stock_id).", ".db_escape($item->quantity).", "
                                .db_escape($item->tran_unit).", ".db_escape($item->tran_qty).", "
                                .db_escape($item->convertion_factor).")";
    
		db_query($sql,"A work order issue item could not be added");
}
//--------------------------------------------------------------------------------------

function update_workorder_material_issue_qty($wo_id, $line_id, $units_issued)
{
    $sql = "UPDATE ".TB_PREF."wo_material SET 
                    units_issued = units_issued + ".db_escape($units_issued)."  
            WHERE id = ".db_escape($line_id)."  AND workorder_id = ".db_escape($wo_id);  
    
    db_query($sql,"Could not update_workorder_material_issue_qty");
}

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


function get_work_order_issues($woid)
{
	$sql = "SELECT * FROM ".TB_PREF."wo_issues WHERE workorder_id=".db_escape($woid)
	." ORDER BY issue_no";
    return db_query($sql, "The work order issues could not be retrieved");
}

function get_additional_issues($woid)
{
	$sql = "SELECT ".TB_PREF."wo_issues.*, ".TB_PREF."wo_issue_items.*
		FROM ".TB_PREF."wo_issues, ".TB_PREF."wo_issue_items
		WHERE ".TB_PREF."wo_issues.issue_no=".TB_PREF."wo_issue_items.issue_id
		AND ".TB_PREF."wo_issues.workorder_id=".db_escape($woid)
		." ORDER BY ".TB_PREF."wo_issue_items.id";
    return db_query($sql, "The work order issues could not be retrieved");
}
//--------------------------------------------------------------------------------------

function get_work_order_issue($issue_no)
{
	$sql = "SELECT DISTINCT ".TB_PREF."wo_issues.*, ".TB_PREF."workorders.stock_id,
		".TB_PREF."stock_master.description, ".TB_PREF."locations.location_name, "
		.TB_PREF."workcentres.name AS WorkCentreName
		FROM ".TB_PREF."wo_issues, ".TB_PREF."workorders, ".TB_PREF."stock_master, "
		.TB_PREF."locations, ".TB_PREF."workcentres
		WHERE issue_no=".db_escape($issue_no)."
		AND ".TB_PREF."workorders.id = ".TB_PREF."wo_issues.workorder_id
		AND ".TB_PREF."locations.loc_code = ".TB_PREF."wo_issues.loc_code
		AND ".TB_PREF."workcentres.id = ".TB_PREF."wo_issues.workcentre_id
		AND ".TB_PREF."stock_master.stock_id = ".TB_PREF."workorders.stock_id";
    $result = db_query($sql, "A work order issue could not be retrieved");

    return db_fetch($result);
}

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

function get_work_order_issue_details($issue_no)
{
	$sql = "SELECT ".TB_PREF."wo_issue_items.*,"
	.TB_PREF."stock_master.description, ".TB_PREF."stock_master.units
		FROM ".TB_PREF."wo_issue_items, ".TB_PREF."stock_master
		WHERE issue_id=".db_escape($issue_no)."
		AND ".TB_PREF."stock_master.stock_id=".TB_PREF."wo_issue_items.stock_id
		ORDER BY ".TB_PREF."wo_issue_items.id";
    return db_query($sql, "The work order issue items could not be retrieved");
}

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

function exists_work_order_issue($issue_no)
{
	$sql = "SELECT issue_no FROM ".TB_PREF."wo_issues WHERE issue_no=".db_escape($issue_no);
	$result = db_query($sql, "Cannot retreive a wo issue");

    return (db_num_rows($result) > 0);
}

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

function void_work_order_issue($type_no)
{
	begin_transaction();
	hook_db_prevoid(ST_MANUISSUE, $type_no);
	
	//Chaitanya : Skip processing already voided entry i.e. explicitly voided
	$void_entry = get_voided_entry(ST_MANUISSUE, $type_no);
	if ($void_entry)
		return;

	// void the actual issue items and their quantities
	$sql = "UPDATE ".TB_PREF."wo_issue_items Set qty_issued = 0 WHERE issue_id="
		.db_escape($type_no);
	db_query($sql,"A work order issue item could not be voided");

	// void any related gl trans
	//Chaitanya : Nothing happens due to next statement as all gl postings are done against WO
	//void_gl_trans(ST_MANUISSUE, $type_no, true);
	
	//Chaitanya : Reverse the gl posting
	$issue = get_work_order_issue($type_no);
	$manf_stock_id = $issue["stock_id"];
	$date_ = sql2date($issue["issue_date"]);
	$woid = $issue["workorder_id"];
		
	$result = get_stock_moves(ST_MANUISSUE, $type_no);
	$total_cost = 0;
	$issue_total = 0;
	while ($myrow = db_fetch($result))
	{
		$issue_cost = $myrow["qty"]*$myrow["standard_cost"];
		$issue = get_stock_gl_code($myrow["stock_id"]);
        $stockitem = get_item($myrow["stock_id"]);
		
		//Chaitanya : Compatibility for Service Items
		if (!is_service($issue["mb_flag"]))
			$ivaccount = $issue["inventory_account"];
		else
			$ivaccount = $issue["cogs_account"];		
		
		if ($issue_cost != 0)
		{
			$total_cost += add_gl_trans_std_cost(ST_WORKORDER, $woid, $date_, $ivaccount, 0, 0,
				$date_.": "._("Reversed the issue of")." ".$stockitem["description"],
				-$issue_cost);			
			$issue_total += $issue_cost;
		}
	}
	if ($issue_total != 0)
		//Chaitanya : Revese cost effect on manfactured stock item as adjustment only
		add_issue_cost($manf_stock_id, 0, $date_, $issue_total, true);
	$issue = get_stock_gl_code($manf_stock_id);
    $stockitem = get_item($manf_stock_id);
	if ($total_cost != 0)
		add_gl_trans_std_cost(ST_WORKORDER, $woid, $date_, $issue["inventory_account"],
			0, 0, $date_.": "._("Reversed the issue to")." ".$stockitem["description"], 
			-$total_cost);	
	
	//Chaitanya : Shifted below void all related stock moves
	void_stock_move(ST_MANUISSUE, $type_no);
	
	commit_transaction();
}


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

?>