<?php

function process_stock_count_job($stock_count_no)
{ 
        global $stock_counting_statuses;
        
        $sch = get_stock_count_header($stock_count_no);
        $status_id = $sch['status_id'];
        
        if($status_id == SC_PROCESSED){
            return array("success"=>false, "message"=>"This stock count has been processed already");
        }
        elseif($status_id == SC_COMPLETED){
            update_stock_count_header_status($stock_count_no, SC_PROCESSING, SC_COMPLETED);
        }
        elseif($status_id == SC_PROCESSING){
            update_stock_count_header_status($stock_count_no, SC_PROCESSING, SC_PROCESSING);
        }
        else{
            return array("success"=>false, "message"=>"Not possible to process this stock count as it has not been $stock_counting_statuses[SC_COMPLETED] yet.");
        }

        return add_stock_count_adjustments($stock_count_no);

}


function add_stock_count_adjustments($stock_count_no)
{
	global $path_to_root, $Refs;
        
	$args = func_get_args();
	$args = (object)array_combine(array('stock_count_no'), $args);
	$args->trans_no = 0;
        
	hook_db_prewrite($args, ST_STOCK_COUNT);
        
    $sc_header = get_stock_count_header($stock_count_no);
    $tran_date = sql2date($sc_header['tran_date']);

    $sc_sheets_result = get_stock_count_sheets($stock_count_no);    
    while ($sc_sheet = db_fetch($sc_sheets_result)){
        
        $sc_line_result = get_stock_count_counted_details($stock_count_no, $sc_sheet['sheet_no']); 
        while ($sc_item = db_fetch($sc_line_result)){
            if($sc_item['status_id'] != SC_COMPLETED){
                continue;
            }

            begin_transaction();
                
            $msg_scia = add_stock_count_item_adjustment($stock_count_no, $sc_header, ST_STOCK_COUNT, $sc_item);

            if($msg_scia['success'] === true){
                commit_transaction();
            }
            else{
                cancel_transaction();
                return array("success"=>false, "message"=>"Could not prcess item : ".$sc_item['stock_id']);
            }
        }            
                 
    }
        
    $processed = check_stock_count_processed($stock_count_no);
    if($processed){

        begin_transaction();
        add_audit_trail(ST_STOCK_COUNT, $stock_count_no, $tran_date);
        $args->trans_no = $stock_count_no;
        hook_db_postwrite($args, ST_STOCK_COUNT);
        commit_transaction();
        
        $n = update_stock_count_header_status($stock_count_no, SC_PROCESSED, SC_PROCESSING);
        if($n != 1){
            return array("success"=>false, "message"=>"Another user has processed stock count.");
        }
        else{
            return array("success"=>true, "message"=> "Stock count $stock_count_no has been processed.");
        }
    }
    else{
        begin_transaction();
        add_audit_trail(ST_STOCK_COUNT, $stock_count_no, $tran_date);
        $args->trans_no = $stock_count_no;
        hook_db_postwrite($args, ST_STOCK_COUNT);
        commit_transaction();
        
        return array("success"=>false, "message"=>"Could not process all stock count items");
    }

}


function add_stock_count_item_adjustment($stock_count_no, $sc_header, $type, $sc_item, $memo_ = null)
{
    $base_unit_adj_qty = ($sc_item['good_qty'] + $sc_item['damaged_qty']) - $sc_item['system_qty'];
    $stock_id = $sc_item['stock_id'];
    
    if($base_unit_adj_qty == 0){
        update_stock_count_item_processed($sc_item['id'], $stock_id);
        return array("success"=>true, "message"=> '');
    }
    
	$item = get_stock_item_edit_info($stock_id);

    if (is_service($item['mb_flag']))
    {
        update_stock_count_item_processed($sc_item['id'], $stock_id);
        return array("success"=>true, "message"=> '');
    }
        
    $qoh = get_qoh_on_date($stock_id);
    
    /*
    Final item stock value = Item stock value now + Stock value of the item quantity adding in to the inventory due to stock count difference
    $new_qoh * $new_std_cost = $qoh * $item['standard_cost'] + $adj_qty * $sc_item['standard_cost']
    */
    
//    if($qoh != $sc_item['system_qty']){
//        $comment = "";
//        update_stock_count_item_ignored($sc_item['id'], $stock_id, $qoh, $comment);
//        return array("success"=>true, "message"=> '');
//    }
    
    $adj_standard_cost = $sc_item['standard_cost'];
    $item_new_stock_value = ($qoh * $item['standard_cost'] + $base_unit_adj_qty * $adj_standard_cost);
    $new_qoh = $qoh + $base_unit_adj_qty;
    
    if($new_qoh != 0){
        $new_std_cost = $item_new_stock_value / $new_qoh;
        if($new_std_cost < 0){
            $new_std_cost = -$new_std_cost;
        }
    }
    else{
        $new_std_cost = $item['standard_cost'];
    }
    
    $date_ = sql2date($sc_header['tran_date']);
    
//    $type, $stock_id, $trans_no, $location,
//                        $date_, $reference, $quantity, $std_cost, 
//                        $person_id=0, $show_or_hide=1, $price=0, $discount_percent=0, 
//                        $error_msg="", $tran_unit = "", $tran_qty = 0, $convertion_factor = 1,
//                        $task_id = 0, $project_site_id = 0, $reference_line_id = 0
            
            $project_id = $sc_header['project_id'];
            $location_code = $sc_header['loc_code'];
            $tran_unit = $sc_item['tran_unit'];
            $convertion_factor = $sc_item['conversion_factor'];
            $tran_qty_adj_qty = $base_unit_adj_qty/$convertion_factor;
            $person_id = "";
            
            
	add_stock_move(ST_STOCK_COUNT, $stock_id, $stock_count_no, $location_code,
                        $date_, $sc_header['reference'], $base_unit_adj_qty, $adj_standard_cost, 
                        $person_id, null, 0, 0, 
                        "", $tran_unit, $tran_qty_adj_qty, $convertion_factor, 
                        $sc_header['task_id'], 0, $sc_item['id'], $project_id);
            

//    if ($sc_item['standard_cost'] > 0){
//        add_gl_trans_std_cost(ST_STOCK_COUNT, $stock_count_no, 
//                        $date_, $item['adjustment_account'], 
//                        $item['dimension_id'], $item['dimension2_id'], 
//                        $memo_, ($adj_standard_cost  * -($base_unit_adj_qty)));
//
//        add_gl_trans_std_cost(ST_STOCK_COUNT, $stock_count_no, 
//                        $date_, $item['inventory_account'], 
//                        0, 0, 
//                        $memo_, ($adj_standard_cost * $base_unit_adj_qty));
//	}
        
    
    
    $new_material_cost = $new_std_cost - ($item['overhead_cost'] + $item['labour_cost']);
    if($new_material_cost < 0){
        $new_material_cost = 0;
    }
    
    update_stock_item_material_cost($stock_id, $new_material_cost);
    
    update_stock_count_item_processed($sc_item['id'], $stock_id);
    
    
    return array("success"=>true, "message"=> '');
}


function get_new_material_cost($stock_id)
{
    

	if ($adj_only)
	{
		if ($qoh > 0){
			$material_cost = ($qoh * $material_cost + $qty * $price_in_home_currency) /	$qoh;
        }
	}
	else
	{
		if ($qoh < 0)
		{
			if ($qoh + $qty >= 0)
				$cost_adjust = true;
			$qoh = 0;
		}
		if ($qoh + $qty > 0){
			$material_cost = ($qoh * $material_cost + $qty * $price_in_home_currency) /	($qoh + $qty);
        }
	}
}