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

function can_commit_workorder($wo)
{
	global  $SysPrefs, $Refs;

//    $wo_item = get_stock_item_edit_info($wo['wo_stock_id']);
//    if($wo_item['MB_flag'] != "M"){
//        $message = "Item selected is not a manufacturing item.";
//        $focus = 'wo_stock_id';
//        return array("success" => false, "message" => $message, "focus_to" => $focus);
//    }
//    
    
	if ($wo['wo_id'] == -1 || $wo['wo_id'] == 0|| $wo['wo_id'] == '')
	{
    	if (!$Refs->is_valid($wo['wo_ref']))
    	{
    		$message = "You must enter a reference.";
			$focus = 'wo_ref';
    		return array("success" => false, "message" => $message, "focus_to" => $focus);
    	}

    	if (!is_new_reference($wo['wo_ref'], ST_WORKORDER))
    	{
    		$message = "The entered reference is already in use.";
			$focus = ('wo_ref');
    		return array("success" => false, "message" => $message, "focus_to" => $focus);
    	}
	}

    if ($wo['wo_project_id'] == -1)
    {
        $message = "Please select a Project.";
        $focus = 'project_id';
        return array("success" => false, "message" => $message, "focus_to" => $focus);
    }
    
    if ($wo['wo_task_id'] == -1)
    {
        $message = "Please select a Task.";
        $focus = 'task_id';
        return array("success" => false, "message" => $message, "focus_to" => $focus);
    }
        
	if (!is_numeric($wo['wo_tran_qty']))
	{
		$message = ( _("The quantity entered is invalid."));
		$focus = ('tran_qty');
		return array("success" => false, "message" => $message, "focus_to" => $focus);
	}

	if (!$wo['wo_tran_qty'] > 0)
	{
		$message = ( _("The quantity entered has to be possitive."));
		$focus = ('tran_qty');
		return array("success" => false, "message" => $message, "focus_to" => $focus);
	}
    
	if (!is_date(sql2date($wo['wo_start_date_time']))){
		$message = ( _("Workorder start date entered is in an invalid format."));
		$focus = ('date_');
		return array("success" => false, "message" => $message, "focus_to" => $focus);
	}
	elseif (!is_date_in_fiscalyear(sql2date($wo['wo_start_date_time']))){
		$message = (_("Workorder start date is not in fiscal year."));
		$focus = ('date_');
		return array("success" => false, "message" => $message, "focus_to" => $focus);
	}
    
	// only check bom and quantites if quick assembly
	if (!($wo['wo_type'] == WO_ADVANCED))
	{
        if (!has_bom($wo['wo_stock_id']))
        {
        	$message = (_("The selected item to manufacture does not have a bom."));
			$focus = ('wo_stock_id');
        	return array("success" => false, "message" => $message, "focus_to" => $focus);
        }

		if ($wo['wo_labour'] == ""){
			$wo['wo_labour'] = price_format(0);
        }
        
    	if (!is_numeric($wo['wo_labour']))
    	{
    		$message = ( _("The labour cost entered is invalid."));
			$focus = ('Labour');
    		return array("success" => false, "message" => $message, "focus_to" => $focus);
    	}
        
        if (!$wo['wo_labour'] > 0)
    	{
    		$message = ( _("The labour cost entered has to be possitive."));
			$focus = ('Labour');
    		return array("success" => false, "message" => $message, "focus_to" => $focus);
    	}
        
		if ($wo['wo_costs'] == ""){
			$wo['wo_costs'] = price_format(0);
        }
        
    	if (!is_numeric($wo['wo_costs']))
    	{
    		$message = ( _("The cost entered is invalid."));
			$focus = ('Costs');
    		return array("success" => false, "message" => $message, "focus_to" => $focus);
    	}
        
        if (!$wo['wo_costs'] > 0)
    	{
    		$message = ( _("The cost entered is has to be possitive."));
			$focus = ('Costs');
    		return array("success" => false, "message" => $message, "focus_to" => $focus);
    	}
        

        if (!$SysPrefs->allow_negative_stock())
        {
        	if ($wo['wo_type'] == WO_ASSEMBLY)
        	{
        		// check bom if assembling
                $result = get_bom($wo['wo_stock_id']);

            	while ($bom_item = db_fetch($result))
            	{

            		if (has_stock_holding($bom_item["ResourceType"]))
            		{

                		$quantity = $bom_item["quantity"] * ($wo['tran_qty'] * $wo['cf']);

                        $qoh = get_qoh_on_date($bom_item["component"], $bom_item["loc_code"], $wo['date_']);
                		if (-$quantity + $qoh < 0)
                		{
                			$message = (_("The work order cannot be processed because there is an insufficient quantity for component:") .
                				" " . $bom_item["component"] . " - " .  $bom_item["description"] . ".  " . _("Location:") . " " . $bom_item["location_name"]);
							$focus = ('quantity');
        					return array("success" => false, "message" => $message, "focus_to" => $focus);
                		}
            		}
            	}
        	}
        	elseif ($wo['wo_type'] == WO_UNASSEMBLY)
        	{
        		// if unassembling, check item to unassemble
				$qoh = get_qoh_on_date($wo['wo_stock_id'], $wo['wo_StockLocation'], $wo['date_']);
        		if (-$wo['tran_qty'] * $wo['cf'] + $qoh < 0)
        		{
        			$message = (_("The selected item cannot be unassembled because there is insufficient stock."));
                    $focus = ('tran_qty');
					return array("success" => false, "message" => $message, "focus_to" => $focus);
        		}
        	}
    	}
     }
     else
     {
    	if (!is_date(sql2date($wo['wo_end_date_time'])))
    	{
			$focus = ('RequDate');
    		$message = ( _("Required by date entered is in an invalid format."));
    		return array("success" => false, "message" => $message, "focus_to" => $focus);
		}
		//elseif (!is_date_in_fiscalyear($_POST['RequDate']))
		//{
		//	display_error(_("The entered date is not in fiscal year."));
		//	return false;
		//}
    	if ($wo['wo_id'] > 0)
    	{
    		$myrow = get_work_order($wo['wo_id'], true);

    		if ($myrow['units_issued'] > $wo['wo_tran_qty'] * $wo['wo_cf'])
    		{
				$focus = ('quantity');
    			$message = (_("The quantity cannot be changed to be less than the quantity already manufactured for this order."));
        		return array("success" => false, "message" => $message, "focus_to" => $focus);
    		}
    	}
        
        if (!($wo['wo_id'] == 0 || $wo['wo_id'] == -1))
    	{
            if($wo['wo_schedule_method'] == WOSM_MANUAL && $wo['wo_update_process_timings'] == false){
                $result = get_wo_processes($wo['wo_id']);
                while ($row = db_fetch($result)) {
                    if($wo['wo_start_date_time'] > $row['start_date_time']){
                        $focus = ('date_');
                        $message = (_("Process ".$row['sequence']." - ".$row['description']." starts before the start of the workorder."));
                        return array("success" => false, "message" => $message, "focus_to" => $focus);
                    }

                    if($wo['wo_end_date_time'] < $row['end_date_time']){
                        $focus = ('RequDate');
                        $message = (_("Process ".$row['sequence']." - ".$row['description']." ends after the end date time of the workorder."));
                        return array("success" => false, "message" => $message, "focus_to" => $focus);
                    }

                }
            }
    		
    	}
	}
    
    

	return array("success" => true, "message" => '');
}


function can_commit_wo_process(&$wop)
{
    if(!is_numeric($wop['wo_process_sequence'])){
        return array("success" => false, "message" => "The sequence number entered is not numeric.", "focus_to" => "bom_procees_sequence");
    }
    
    if($wop['wo_process_sequence'] < 0){
        return array("success" => false, "message" => "The sequence number entered is not possitive.", "focus_to" => "bom_procees_sequence");
    }
    

    $wo_processes = get_wo_processes($wop['wo_id']);
    while ($row = db_fetch($wo_processes)) {
        if($wop['wo_process_sequence'] == $row['sequence'] && $wop['wo_process_id'] != $row['id']){
            return array("success" => false, "message" => "The sequence number entered has been alreay used in this workorder.", "focus_to" => "bom_procees_sequence");
        }
    }

    if(!($wop['wo_process_type_id'] > 0)){
        return array("success" => false, "message" => "Please select a process type.", "focus_to" => "wo_process_type_id");
    }
    
    if(!check_num2($wop['wo_process_item_quantity'], 0)){
        return array("success" => false, "message" => "Item quantity should be numeric and positive", "focus_to" => "wo_process_item_quantity");
    }    
    
    $t2s = time2seconds($wop['wo_process_setup_time']);
    if($t2s["success"] === true){
        $wop['wo_process_setup_time_s'] = $t2s["message"];
    }
    else{
        return array("success" => false, "message" => "Setup Time - ".$t2s["message"], "focus_to" => "wo_process_setup_time");
    }
    
    $t2s = time2seconds($wop['wo_process_processing_time']);
    if($t2s["success"] === true){
        $wop['wo_process_processing_time_s'] = $t2s["message"];
    }
    else{
        return array("success" => false, "message" => "Processing Time - ".$t2s["message"], "focus_to" => "wo_process_processing_time");
    }
    
    $t2s = time2seconds($wop['wo_process_cleaning_time']);
    if($t2s["success"] === true){
        $wop['wo_process_cleaning_time_s'] = $t2s["message"];
    }
    else{
        return array("success" => false, "message" => "Cleaning Time - ".$t2s["message"], "focus_to" => "wo_process_cleaning_time");
    }
    
    if($wop['wo_process_schedule_method'] == WOSM_MANUAL){ 
        $woh = get_work_order_header($wop['wo_id']);
        if($woh['date_'] > $wop['wo_process_start_date_time']){
            return array("success" => false, "message" => "Start date time is before the start of the work order.", "focus_to" => "wo_process_start_date");
        }
        
        if($woh['required_by'] < $wop['wo_process_end_date_time']){
            return array("success" => false, "message" => "End date time is after the end of workorder.", "focus_to" => "wo_process_end_date");
        }
    }
    
    return array("success" => true, "message" => "");
}


function save_wo_process(&$wop){
    
    if($wop['wo_process_id'] > 0){
        /*No need to update the process. Scheduling will update it again*/
//        //delete_workcentre_schedule_time($wop['wo_process_id']);
//        delete_workcentre_process_schedule($wop['wo_process_id']);
//        
//        $sw = schedule_wo_process($wop);
//        if($sw["success"] !== true){
//            return $sw;
//        }
//        
//        get_work_order_process_schedule_summary($wop);
//        update_wo_process($wop['wo_process_id'], $wop['wo_process_sequence'], $wop['wo_process_description'], 
//                        $wop['wo_process_item_description'], $wop['wo_process_item_quantity'],$wop['wo_process_start_date_time'],
//                        $wop['wo_process_setup_time_s'], $wop['wo_process_processing_time_s'], $wop['wo_process_cleaning_time_s'], 
//                        0, $wop['wo_process_end_date_time'], $wop['wo_process_qc'], $wop['wo_process_comment']);
//        
        return array("success" => true, "message" => '', "tran_no" => $wop['wo_process_id']);        
    }
    else{
        add_wo_process($wop['wo_id'], $wop['wo_process_sequence'],$wop['wo_process_description'], 
                        $wop['wo_process_workcentre_id'], $wop['wo_process_item_description'], $wop['wo_process_item_quantity'],
                        $wop['wo_process_start_date_time'], $wop['wo_process_setup_time_s'], $wop['wo_process_processing_time_s'],
                        $wop['wo_process_cleaning_time_s'], 0, $wop['wo_process_end_date_time'],
                        $wop['wo_process_qc'], $wop['wo_process_comment'], $wop['wo_process_type_id']);
        $wop['wo_process_id'] = db_insert_id();
        
//        $sw = schedule_wo_process($wop);
//        if($sw["success"] !== true){
//            return $sw;
//        }
//        
//        get_work_order_process_schedule_summary($wop);
//        update_wo_process($wop['wo_process_id'], $wop['wo_process_sequence'], $wop['wo_process_description'], 
//                        $wop['wo_process_item_description'], $wop['wo_process_item_quantity'],$wop['wo_process_start_date_time'],
//                        $wop['wo_process_setup_time_s'], $wop['wo_process_processing_time_s'], $wop['wo_process_cleaning_time_s'], 
//                        0, $wop['wo_process_end_date_time'], $wop['wo_process_qc'], $wop['wo_process_comment']);
        return array("success" => true, "message" => '', "tran_no" => $wop['wo_process_id']);
    }    
    
    return array("success" => false, "message" => 'Could not save workorder process'); 
}


function schedule_wo_process($wop){

        delete_workcentre_process_schedule($wop['wo_process_id']);
        
        if($wop['wo_process_schedule_method'] > WOSM_MANUAL){
            $sw = schedule_wo_process_workcentre($wop);
            if($sw["success"] !== true){
                return $sw;
            }
        
            get_work_order_process_schedule_summary($wop);
        }
        
        update_wo_process($wop['wo_process_id'], $wop['wo_process_sequence'], $wop['wo_process_description'], 
                        $wop['wo_process_item_description'], $wop['wo_process_item_quantity'],$wop['wo_process_start_date_time'],
                        $wop['wo_process_setup_time_s'], $wop['wo_process_processing_time_s'], $wop['wo_process_cleaning_time_s'], 
                        0, $wop['wo_process_end_date_time'], $wop['wo_process_qc'], $wop['wo_process_comment'],
                        $wop['wo_process_type_id']);
        
        return array("success" => true, "message" => '', "tran_no" => $wop['wo_process_id']);        

}


function get_work_order_process_schedule_summary(&$wop)
{
    $process_start_details = get_workcentre_schedule_process_start_details($wop['wo_process_id']);
    $wo_process_start_date_time = $process_start_details['work_start_date_time'];
    
    $process_end_details = get_workcentre_schedule_process_end_details($wop['wo_process_id']);
    $end_ts = strtotime($process_end_details['work_start_date_time']) + $process_end_details['duration'];
    $wo_process_end_date_time = date('Y-m-d H:i:s', $end_ts);
    
    $wop['wo_process_start_date_time'] = $wo_process_start_date_time;
    $wop['wo_process_end_date_time'] = $wo_process_end_date_time;
    
}

function schedule_wo_process_workcentre(&$wop)
{
    switch ($wop['wo_process_schedule_method']) {
        case WOSM_FORWARD_MANUAL:
        case WOSM_FORWARD_SCHEDULAR:
            
        case WOSM_FORWARD_INLINE_MANUAL:
        case WOSM_FORWARD_INLINE_SCHEDULAR;
            
        case WOSM_FORWARD_PRIORITY_MANUAL:
        case WOSM_FORWARD_PRIORITY_SCHEDULAR:
            
        default:
            $schedulling_start_date_time = $wop['wo_process_start_date_time'];
            break;
        case WOSM_BACKWARD_MANUAL:
        case WOSM_BACKWARD_SCHEDULAR:
            $schedulling_start_date_time = $wop['wo_process_end_date_time']; 
            break;
    }
    
    $user_id = $_SESSION['wa_current_user']->user;
    
    $schedulling_start_ts = strtotime($schedulling_start_date_time);
    
    switch ($wop['wo_process_schedule_method']) {
        case WOSM_FORWARD_MANUAL:
        case WOSM_FORWARD_SCHEDULAR:
        default:
            $allocation_start_date_time = date('Y-m-d H:i:s');
            $total_outstanding_work_s = get_workcentre_total_outstanding_work($wop['wo_process_workcentre_id']);
            $w = date('Y-m-d H:i:s', $total_outstanding_work_s);
            $cwowet = calculate_workcentre_outstanding_work_end_time($wop['wo_process_workcentre_id'], $allocation_start_date_time, $total_outstanding_work_s);
            if($cwowet["success"] !== true){
                return $cwowet;
            }
            $calculated_total_work_end_ts = $cwowet["message"];
            
            $e42 = date('Y-m-d H:i:s', $calculated_total_work_end_ts);
            if($calculated_total_work_end_ts >= $schedulling_start_ts){
                $schedulling_start_ts = $calculated_total_work_end_ts;
            }
            $e2 = date('Y-m-d H:i:s', $schedulling_start_ts);
            break;
            
        
        case WOSM_FORWARD_INLINE_MANUAL:
        case WOSM_FORWARD_INLINE_SCHEDULAR;
            $schedulling_start_ts = strtotime($schedulling_start_date_time);
            $wo_end_time_details = get_workorder_schedule_end_time_details($wop['wo_id'], $wop['wo_process_sequence']);
            if($wo_end_time_details){
                $schedulling_start_ts = strtotime($wo_end_time_details['work_start_date_time']) + $wo_end_time_details['duration'];
            }
            else{
                $schedulling_start_ts = $schedulling_start_ts;
            }
            
            $y2 = date('Y-m-d H:i:s', $schedulling_start_ts);
            break;
            
            
        case WOSM_FORWARD_PRIORITY_MANUAL:
            //Start schedulling from the user entered work start from date time
            //Ignore all other schedulled work even belongs to current work order.
            
            
        case WOSM_FORWARD_PRIORITY_SCHEDULAR:
            
                                //Future enhancement: If workorder start date time is in future, check whether setting up can be started before the workorder start date time
                                // Schedule setup time backwards
                                // Then get the end time of the last scheduled anyother work on the workcentre before the  $date_time_ts
                                // If the last schedule work end time is before $date_time_ts, then no change in the new setup time schedule
                                // Else delete new setup time schedule and schedule setup time from the end time of the last schedule work
            
            //Start schedulling from the later time of schedulaer sending from date time or end time of all other processes of current workorder

            $schedulling_start_ts = $schedulling_start_ts;
            break;
        case WOSM_BACKWARD_MANUAL:
        case WOSM_BACKWARD_SCHEDULAR:
//            $schedulling_start_date_time = $wop['wo_process_end_date_time']; 
            break;
    }
    
    
    
    switch ($wop['wo_process_schedule_method']) {
        case WOSM_FORWARD_MANUAL:
        case WOSM_FORWARD_SCHEDULAR:

        case WOSM_FORWARD_INLINE_MANUAL:
        case WOSM_FORWARD_INLINE_SCHEDULAR;
            
        case WOSM_FORWARD_PRIORITY_MANUAL:
        case WOSM_FORWARD_PRIORITY_SCHEDULAR:
        
        default:
            //============================== Setup====================================
            $schedulling_started_date_time = date('Y-m-d H:i:s', $schedulling_start_ts);
            $remaining_setup_time_s = $wop['wo_process_setup_time_s'];
            if($remaining_setup_time_s > 0){
                for ($i = 0; $i < $wop['wo_process_scheduling_days_limit']; $i++) {
                    $e = date('Y-m-d H:i:s', $schedulling_start_ts);
                    $swd = schedule_workcentre_day($wop['wo_process_id'], $wop['wo_process_workcentre_id'], $schedulling_start_ts, 
                                    $wop['wo_process_schedule_method'], 1, $user_id, 
                                    $remaining_setup_time_s, $wc_from_ts, $wc_to_ts);
                    if($swd["success"] !== true){
                        return $swd;
                    }
                    if($remaining_setup_time_s > 0){
                        $schedulling_start_ts = $wc_to_ts;
                    }
                }
                if($remaining_setup_time_s > 0){
                    return array("success" => false, "message" => get_could_not_complete_wc_scheduling_message($wop, $schedulling_started_date_time));
                }
            }
            else{
                $wc_to_ts = $schedulling_start_ts;
                add_workcentre_schedule_time($wop['wo_process_id'], $wop['wo_process_workcentre_id'], 1, $schedulling_start_ts, 0, $user_id);
            }

            
            //============================== Processing====================================
            $schedulling_started_date_time = date('Y-m-d H:i:s', $wc_to_ts);
            $schedulling_start_ts = $wc_to_ts;

            $remaining_processing_time_s = $wop['wo_process_processing_time_s'];
            if($remaining_processing_time_s > 0){
                for ($i = 0; $i < $wop['wo_process_scheduling_days_limit']; $i++) {
                    if($remaining_processing_time_s > 0){
                        $swd = schedule_workcentre_day($wop['wo_process_id'], $wop['wo_process_workcentre_id'], $schedulling_start_ts, 
                                        $wop['wo_process_schedule_method'], 2, $user_id, 
                                        $remaining_processing_time_s, $wc_from_ts, $wc_to_ts);
                        if($swd["success"] !== true){
                            return $swd;
                        }

                        if($remaining_processing_time_s > 0){
                                $schedulling_start_ts = $wc_to_ts;
                        }
                    }
                }
                if($remaining_processing_time_s > 0){
                    return array("success" => false, "message" => get_could_not_complete_wc_scheduling_message($wop, $schedulling_started_date_time));
                }
            }
            else{
                $wc_to_ts = $schedulling_start_ts;
                add_workcentre_schedule_time($wop['wo_process_id'], $wop['wo_process_workcentre_id'], 2, $schedulling_start_ts, 0, $user_id);
            }
    
            
            //============================== Cleaning====================================
            $schedulling_started_date_time = date('Y-m-d H:i:s', $wc_to_ts);
            $schedulling_start_ts = $wc_to_ts;
            
            $remaining_cleaning_time_s = $wop['wo_process_cleaning_time_s'];
            if($remaining_cleaning_time_s > 0){
                for ($i = 0; $i < $wop['wo_process_scheduling_days_limit']; $i++) {
                    $swd = schedule_workcentre_day($wop['wo_process_id'], $wop['wo_process_workcentre_id'], $schedulling_start_ts, 
                                    $wop['wo_process_schedule_method'], 3, $user_id, 
                                    $remaining_cleaning_time_s, $wc_from_ts, $wc_to_ts);
                    if($swd["success"] !== true){
                        return $swd;
                    }
                    
                    if($remaining_cleaning_time_s > 0){
                        $schedulling_start_ts = $wc_to_ts;
                    }
                }
                if($remaining_cleaning_time_s > 0){
                    return array("success" => false, "message" => get_could_not_complete_wc_scheduling_message($wop, $schedulling_started_date_time));
                }
            }
            else{
                $wc_to_ts = $schedulling_start_ts;
                add_workcentre_schedule_time($wop['wo_process_id'], $wop['wo_process_workcentre_id'], 3, $schedulling_start_ts, 0, $user_id);
            }
    
            break;
        
        case WOSM_BACKWARD_MANUAL:
        case WOSM_BACKWARD_SCHEDULAR:
            //============================== Cleaning====================================
            $schedulling_started_date_time = date('Y-m-d H:i:s', $schedulling_start_ts);
            $remaining_cleaning_time_s = $wop['wo_process_cleaning_time_s'];
            if($remaining_cleaning_time_s > 0){
                for ($i = 0; $i < $wop['wo_process_scheduling_days_limit']; $i++) {
                    $swd = schedule_workcentre_day($wop['wo_process_id'], $wop['wo_process_workcentre_id'], $schedulling_start_ts, 
                                    $wop['wo_process_schedule_method'], 3, $user_id, 
                                    $remaining_cleaning_time_s, $wc_from_ts, $wc_to_ts);
                    if($swd["success"] !== true){
                        return $swd;
                    }
                    
                    if($remaining_cleaning_time_s > 0){
                        $schedulling_start_ts = $wc_from_ts;
                    }
                }
                if($remaining_cleaning_time_s > 0){
                    return array("success" => false, "message" => get_could_not_complete_wc_scheduling_message($wop, $schedulling_started_date_time));
                }
            }
            else{
                $wc_from_ts = $schedulling_start_ts;
                add_workcentre_schedule_time($wop['wo_process_id'], $wop['wo_process_workcentre_id'], 3, $schedulling_start_ts, 0, $user_id);
            }
            
            
            //============================== Processing====================================
            $schedulling_started_date_time = date('Y-m-d H:i:s', $wc_from_ts);
            $schedulling_start_ts = $wc_from_ts;
            
            $remaining_processing_time_s = $wop['wo_process_processing_time_s'];
            if($remaining_processing_time_s > 0){
                for ($i = 0; $i < $wop['wo_process_scheduling_days_limit']; $i++) {
                    $swd = schedule_workcentre_day($wop['wo_process_id'], $wop['wo_process_workcentre_id'], $schedulling_start_ts, 
                                    $wop['wo_process_schedule_method'], 2, $user_id, 
                                    $remaining_processing_time_s, $wc_from_ts, $wc_to_ts);
                    if($swd["success"] !== true){
                        return $swd;
                    }
                    
                    if($remaining_processing_time_s > 0){
                        //$e = date('Y-m-d H:i:s', $schedulling_start_ts);
                        $schedulling_start_ts = $wc_from_ts;
                        //$g = date('Y-m-d H:i:s', $schedulling_start_ts);
                    }
                }
                if($remaining_processing_time_s > 0){
                    return array("success" => false, "message" => get_could_not_complete_wc_scheduling_message($wop, $schedulling_started_date_time));
                }
            }
            else{
                $wc_from_ts = $schedulling_start_ts;
                add_workcentre_schedule_time($wop['wo_process_id'], $wop['wo_process_workcentre_id'], 2, $schedulling_start_ts, 0, $user_id);
            }

            
            //============================== Setup====================================
            $schedulling_started_date_time = date('Y-m-d H:i:s', $wc_from_ts);
            $schedulling_start_ts = $wc_from_ts;
            
            $remaining_setup_time_s = $wop['wo_process_setup_time_s'];
            if($remaining_setup_time_s > 0){
                for ($i = 0; $i < $wop['wo_process_scheduling_days_limit']; $i++) {
                    $swd = schedule_workcentre_day($wop['wo_process_id'], $wop['wo_process_workcentre_id'], $schedulling_start_ts, 
                                    $wop['wo_process_schedule_method'], 1, $user_id, 
                                    $remaining_setup_time_s, $wc_from_ts, $wc_to_ts);
                    if($swd["success"] !== true){
                        return $swd;
                    }
                    
                    if($remaining_setup_time_s > 0){
                        $schedulling_start_ts = $wc_from_ts;
                    }
                }
                if($remaining_setup_time_s > 0){
                    return array("success" => false, "message" => get_could_not_complete_wc_scheduling_message($wop, $schedulling_started_date_time));
                }
            }
            else{
                $wc_from_ts = $schedulling_start_ts;
                add_workcentre_schedule_time($wop['wo_process_id'], $wop['wo_process_workcentre_id'], 1, $schedulling_start_ts, 0, $user_id);
            }
    }
    
    return array("success" => true, "message" => "");
    
}

function schedule_workcentre_day($wo_process_id, $workcentre_id, $schedulling_start_ts, 
                            $schedule_method, $work_type_id, $user_id, 
                            &$remaining_work_s = 0, &$wc_from_ts = 0, &$wc_to_ts = 0)
{
    //$g = date('Y-m-d H:i:s', $schedulling_start_ts);
    $schedulling_date = date('Y-m-d', $schedulling_start_ts);
    $schedulling_date_ts = strtotime($schedulling_date);
    //$schedulling_date_ts = (floor($schedulling_start_ts/(3600*24))) * 3600*24;
    
    //Quering for the same day, assuming the rare case that previous work was done within an overnght shift
    $gwcswt = get_workcentre_shift_working_times($workcentre_id, $schedulling_start_ts, $shift_start_s, $shift_duration_s);
    if($gwcswt['success'] !== true){
        return $gwcswt;
    }
    
    switch ($schedule_method) {
        case WOSM_FORWARD_MANUAL:
        case WOSM_FORWARD_SCHEDULAR:            
        
        case WOSM_FORWARD_INLINE_MANUAL:
        case WOSM_FORWARD_INLINE_SCHEDULAR;
            
        case WOSM_FORWARD_PRIORITY_MANUAL:
        case WOSM_FORWARD_PRIORITY_SCHEDULAR:
        default :
            $day_start_ts = $schedulling_date_ts + $shift_start_s;
            $day_end_ts = $day_start_ts + $shift_duration_s;
            if($schedulling_start_ts >= $day_end_ts)
            {
                // This means previous work is done NOT within an overnight shift
                // Go to the next day
                $schedulling_date_ts += 3600*24;
                $gwcswt = get_workcentre_shift_working_times($workcentre_id, $schedulling_date_ts, $shift_start_s, $shift_duration_s);
                if($gwcswt['success'] !== true){
                    return $gwcswt;
                }
                $day_start_ts = $schedulling_date_ts + $shift_start_s;
                $day_end_ts = $day_start_ts + $shift_duration_s;
            }
            $a1 = date('Y-m-d H:i:s', $day_start_ts);
            $b1 = date('Y-m-d H:i:s', $day_end_ts);
            $s1 = date('Y-m-d H:i:s', $schedulling_start_ts);
            break;
        case WOSM_BACKWARD_MANUAL: 
        case WOSM_BACKWARD_SCHEDULAR: 
            // This is mostly quering the same day
            $gwcswt = get_workcentre_shift_working_times($workcentre_id, $schedulling_start_ts, $shift_start_s, $shift_duration_s);
            if($gwcswt['success'] !== true){
                return $gwcswt;
            }
            $day_start_ts = $schedulling_date_ts + $shift_start_s;
            $day_end_ts = $schedulling_date_ts + $shift_start_s + $shift_duration_s;
            //$a = date('Y-m-d H:i:s', $day_start_ts);
            //$b = date('Y-m-d H:i:s', $day_end_ts);
            //$s = date('Y-m-d H:i:s', $schedulling_start_ts);
            
            if($schedulling_start_ts <= $day_start_ts)
            {
                // Go to the previous day
                $schedulling_date_ts -= 3600*24; 
                $gwcswt = get_workcentre_shift_working_times($workcentre_id, $schedulling_date_ts, $shift_start_s, $shift_duration_s);
                if($gwcswt['success'] !== true){
                    return $gwcswt;
                }
                $day_start_ts = $schedulling_date_ts + $shift_start_s;
                $day_end_ts = $schedulling_date_ts + $shift_start_s + $shift_duration_s;
                
                //$a1 = date('Y-m-d H:i:s', $day_start_ts);
                //$b1 = date('Y-m-d H:i:s', $day_end_ts);
                //$s1 = date('Y-m-d H:i:s', $schedulling_start_ts);
            }
            break;
    }
            
    
    
    
    
    switch ($schedule_method) {
        case WOSM_BACKWARD_MANUAL: // backwards
        case WOSM_BACKWARD_SCHEDULAR:
            // Begin from the end of the shift. 
            // This is priority type scheduling as if the workcentre is already overloaeded, finding an empty slot can go infintely backwards.
            
            if($schedulling_start_ts <= $day_start_ts){
                return;
            }
            elseif($schedulling_start_ts <= $day_end_ts){
                $day_end_ts = $schedulling_start_ts;
            }
            else{
                $day_end_ts = $day_end_ts;
            }
            
            
            $work_start_ts = $day_end_ts - $remaining_work_s;
            if($work_start_ts >= $day_start_ts){
                // Remainig work can be completed with the shift day 
                $wc_to_ts = $day_end_ts;
                $wc_from_ts = $work_start_ts;        
                $wc_duration_s = $wc_to_ts - $wc_from_ts;
                $remaining_work_s = 0;
            }
            else{
                //Shift duration is not sufficient to complete the remaining work
                $wc_from_ts = $day_start_ts;
                $wc_to_ts = $day_end_ts;
                $wc_duration_s = $wc_to_ts - $wc_from_ts;
                $remaining_work_s = $day_start_ts - $work_start_ts;
            }
            //$a1 = date('Y-m-d H:i:s', $wc_from_ts);
            //$b1 = date('Y-m-d H:i:s', $wc_to_ts);
            //$s1 = date('Y-m-d H:i:s', $schedulling_start_ts);
                
            add_workcentre_schedule_time($wo_process_id, $workcentre_id, $work_type_id, $wc_from_ts, $wc_duration_s, $user_id);
            break;
                
        
        case WOSM_FORWARD_INLINE_MANUAL:
        case WOSM_FORWARD_INLINE_SCHEDULAR;
        
        case WOSM_FORWARD_PRIORITY_MANUAL:
        case WOSM_FORWARD_PRIORITY_SCHEDULAR: // Forward Priority
            // Ignore any current scheduled work of all other workorders on the workcentre.
            // Start from the end time of the last work of this workorder 

            if($schedulling_start_ts >= $day_end_ts){
                return;
            }
            elseif($schedulling_start_ts >= $day_start_ts){
                $day_start_ts = $schedulling_start_ts;
            }
            else{
                $day_start_ts = $day_start_ts;
            }
            
            $work_end_ts = $day_start_ts + $remaining_work_s;
            if($work_end_ts <= $day_end_ts){
                $wc_from_ts = $day_start_ts;
                $wc_to_ts = $work_end_ts;
                $wc_duration_s = $wc_to_ts - $wc_from_ts; 
                $remaining_work_s = 0;
            }
            else{
                $wc_from_ts = $day_start_ts;
                $wc_to_ts = $day_end_ts;
                $wc_duration_s = $wc_to_ts - $wc_from_ts; 
                $remaining_work_s = $work_end_ts - $day_end_ts;
            }
            add_workcentre_schedule_time($wo_process_id, $workcentre_id, $work_type_id, $wc_from_ts, $wc_duration_s, $user_id);
            break;

            
         
        case WOSM_FORWARD_MANUAL:
        case WOSM_FORWARD_SCHEDULAR:
        default:
            $scheduled_work_s = 0;
            // Calculate the total scheduled load of current day on the workcntre
            $scheduled_work_s = get_workcentre_total_outstanding_work($workcentre_id, $schedulling_date);
            if($shift_duration_s < $scheduled_work_s){
                // Schedulled work can not be completed within this date 
                $wc_to_ts = $day_end_ts;
                return;
            }

            if($schedulling_start_ts >= $day_end_ts){
                $wc_to_ts = $day_end_ts;
                return;
            }
            
            $day_schedulled_work_end_ts = $day_start_ts + $scheduled_work_s;
            
            if($schedulling_start_ts >= $day_schedulled_work_end_ts){
                $day_start_ts = $schedulling_start_ts;
            }
            else{
                $day_start_ts = $day_schedulled_work_end_ts;
            }
            
            // Allow time for the already scheduled work.

            $wc_from_ts = $day_start_ts;
            $work_end_ts = $wc_from_ts + $remaining_work_s;
            
            $a1 = date('Y-m-d H:i:s', $wc_from_ts);
            $b1 = date('Y-m-d H:i:s', $work_end_ts);
            $s1 = date('Y-m-d H:i:s', $schedulling_start_ts);
            
            if($work_end_ts <= $day_end_ts){
                // Can complete schedulled work within this day
                $wc_to_ts = $work_end_ts;
                $e1 = date('Y-m-d H:i:s', $wc_to_ts);
                $wc_duration_s = $wc_to_ts - $wc_from_ts; 
                $remaining_work_s = 0;
            }
            else{
                // Do part of the work on this day and send back the remaining work duration
                $wc_to_ts = $day_end_ts;
                $e1 = date('Y-m-d H:i:s', $wc_to_ts);
                $wc_duration_s = $day_end_ts - $wc_from_ts; 
                $remaining_work_s = $work_end_ts - $day_end_ts;
            }
            add_workcentre_schedule_time($wo_process_id, $workcentre_id, $work_type_id, $wc_from_ts, $wc_duration_s, $user_id);
    }
    
    return array("success" => true, "message" => "");
    
}


function get_workcentre_shift_working_times($workcentre_id, $date_time_ts, &$shift_start_s, &$shift_working_duration_s)
{
    $date = date('Y-m-d', $date_time_ts);
    $shift_schedule = get_applicable_workcentre_shift($workcentre_id, $date);
    if(!$shift_schedule){
        $workcentre = get_work_centre($workcentre_id);
        return array("success" => false, "message" => "Workcenter ".$workcentre['name']." does not have a shift for ".$date);
    }
    $shift = get_shift_details($shift_schedule['shift_id']);
    
    //$timestamp = strtotime($date);
    $day = date('D', $date_time_ts);
    
    switch ($day) {   
        case "Sat": 
            $shift_start_s = strtotime("1970-01-01 ".$shift['start_time1']." UTC");
            $shift_duration_s = time2seconds($shift['duration1'])["message"];
            switch ($shift_schedule['saturday_work_time_id']) {
                case 0:
                    $temp_shift_duration_s = $shift_duration_s;
                    break;
                case 1:
                    $temp_shift_duration_s = 3600 * 4;
                    break;
                case 2:
                    $temp_shift_duration_s = $shift_duration_s / 2; 
                    break;
                case 3:
                    $temp_shift_duration_s = 3600 * 8; 
                    break;
                case 4:
                    $temp_shift_duration_s = 0; 
                    break;
                case 5:
                    $temp_shift_duration_s = 3600 * 5;
                    break;
            } 
            $shift_working_duration_s = $temp_shift_duration_s;
            break;
        case "Sun":
            $shift_start_s = strtotime("1970-01-01 ".$shift['start_time1']." UTC");
            $shift_duration_s = time2seconds($shift['duration1'])["message"];
            switch ($shift_schedule['sunday_work_time_id']) {
                case 0:
                    $temp_shift_duration_s = $shift_duration_s;
                    break;
                case 1:
                    $temp_shift_duration_s = 3600 * 4;
                    break;
                case 2:
                    $temp_shift_duration_s = $shift_duration_s / 2; 
                    break;
                case 3:
                    $temp_shift_duration_s = 3600 * 8; 
                    break;
                case 4:
                    $temp_shift_duration_s = 0; 
                    break;
                case 5:
                    $temp_shift_duration_s = 3600 * 5;
                    break;
            } 
            $shift_working_duration_s = $temp_shift_duration_s;
            break;
        default:
            $shift_start_s = strtotime("1970-01-01 ".$shift['start_time1']." UTC");
            $temp_shift_duration_s = time2seconds($shift['duration1'])["message"];
            $shift_working_duration_s = $temp_shift_duration_s;
            break;
    }
    
    return array("success" => true, "message" => "");
}

function calculate_workcentre_outstanding_work_end_time($workcentre_id, $allocation_start_date_time, $total_outstanding_work_s)
{
    if($total_outstanding_work_s == 0){
        return array("success" => true, "message" => strtotime($allocation_start_date_time));
    }
    
    //$g = date('Y-m-d H:i:s', $schedulling_start_ts);
    //$allocation_start_date_ts = date('Y-m-d', $schedulling_start_ts);
    
    $allocation_start_ts = strtotime($allocation_start_date_time);

    
    while($total_outstanding_work_s > 0){
        $allocation_date = date('Y-m-d', $allocation_start_ts);
        $allocation_date_ts = strtotime($allocation_date);
        $gwcswt = get_workcentre_shift_working_times($workcentre_id, $allocation_start_ts, $shift_start_s, $shift_duration_s);
        if($gwcswt['success'] !== true){
            return $gwcswt;
        }
        $shift_start_ts = $allocation_date_ts + $shift_start_s;
        $shift_end_ts = $shift_start_ts + $shift_duration_s;
        if($allocation_start_ts >= $shift_end_ts){
            $allocation_date = date('Y-m-d', $allocation_start_ts);
            $allocation_date_ts = strtotime($allocation_date);
            $allocation_start_ts = $allocation_date_ts + 3600*24; 
            continue;
        }
        else{
            //$allocation_start_ts is before $shift_end_ts
            if($allocation_start_ts <= $shift_start_ts){
                $workcntre_working_duration = $shift_duration_s;
            }
            else{
                $workcntre_working_duration = $shift_end_ts - $allocation_start_ts;
            }
            
            if($total_outstanding_work_s > $workcntre_working_duration){
                $total_outstanding_work_s -= $workcntre_working_duration;
                $allocation_start_ts = $allocation_date_ts + 3600*24; 
            }
            else{
                if($allocation_start_ts > $shift_start_ts){
                    $workload_end_time_ts = $allocation_start_ts + $total_outstanding_work_s;
                }
                else{
                    $workload_end_time_ts = $shift_start_ts + $total_outstanding_work_s;
                }
                $total_outstanding_work_s = 0;
                return array("success" => true, "message" => $workload_end_time_ts);
            }            
        }
    }
}

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

function can_commit_wo_labour($wol, $id)
{
    $message = '';
    if($wol['wo_labour_job_category_id'] == -1){
        $message = ("Please select a Job Category");
        $focus = ('wo_labour_job_category_id');
        return array("success" => false, "message" => $message, "focus_to" => $focus);
    }
    
    if($wol['wo_labour_rate_category_id'] == -1){
        $message = ("Please select a Rate Category");
        $focus = ('wo_labour_rate_category_id');
        return array("success" => false, "message" => $message, "focus_to" => $focus);
    }
  
    
    if(!($wol['wo_labour_process_id'] > 0)){
        $message = ("No details found for the selected workorder Process.");
        $focus = ('wo_labour_process_id');
        return array("success" => false, "message" => $message, "focus_to" => $focus);
    }
    
    return array("success" => true, "message" => "", "focus_to" => "");
}


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


function can_delete_wo_labour($id)
{
    $message = '';

    return array("success" => true, "message" => "", "focus_to" => "");
}


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


function save_wo_labour($wol, $id){
    
    $wo_process = get_wo_process($wol['wo_labour_process_id']);
    $wol['wo_id'] = $wo_process['workorder_id'];
    
    if($id > 0){
        update_wo_labour($id, $wol['wo_labour_process_id'], $wol['wo_labour_job_category_id'],   
                        $wol['wo_labour_rate_category_id'], $wol['wo_labour_setup'],$wol['wo_labour_processing'],
                        $wol['wo_labour_cleaning'], $wol['wo_labour_comment'], $wol['user_id']);
    }
    else{
        add_wo_labour($wol['wo_labour_process_id'],$wol['wo_labour_job_category_id'], $wol['wo_labour_rate_category_id'], 
                        $wol['wo_labour_setup'],$wol['wo_labour_processing'], $wol['wo_labour_cleaning'], 
                        $wol['wo_labour_comment'], $wol['user_id'], $wol['wo_id']);
    }

    return array("success" => true); 
 
}

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

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

function save_wo_material($wom, $id){
   // return;
    
    $tran_unit = $wom['wo_material_tran_unit'];
    $cf = $wom['wo_material_cf'];
            
    get_convertion_factor2($wom['wo_material_stock_id'], $tran_unit, $cf);
    
    $wom['wo_material_tran_unit'] = $tran_unit;
    $wom['wo_material_cf'] = $cf;

    $wo_process = get_wo_process($wom['wo_material_process_id']);
    $wom['wo_id'] = $wo_process['workorder_id'];
    $wom['wo_material_workcentre_id'] = $wo_process['workcentre_id'];
    
    $item = get_item_edit_info($wom['wo_material_stock_id']);
    $wom['wo_material_std_cost'] = $item['standard_cost'];


    if($id > 0){
        update_wo_material($id, $wom['wo_material_tran_qty'] * $wom['wo_material_cf'],
                            $wom['wo_material_tran_unit'], $wom['wo_material_tran_qty'],
                            $wom['wo_material_cf'], $wom['wo_material_std_cost'],
                            $wom['wo_material_loc_code'], $wom['wo_material_comment'], 
                            $wom['user_id'], $wom['wo_id']);
                
        return array("success" => true); 
    }
    else{
        add_wo_material($wom['wo_id'], $wom['wo_material_process_id'], 
                        $wom['wo_material_stock_id'], $wom['wo_material_workcentre_id'],
                        $wom['wo_material_tran_qty'] * $wom['wo_material_cf'], $wom['wo_material_tran_unit'], 
                        $wom['wo_material_tran_qty'], $wom['wo_material_cf'], 
                        $wom['wo_material_std_cost'], $wom['wo_material_loc_code'], 
                        $wom['wo_material_comment'], $wom['user_id']);        
        return array("success" => true); 
    }
    
    return array("success" => false); 
}

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

function can_commit_wo_material($wom)
{
    if($wom['wo_material_tran_unit'] == ''){
        $message = "Please select units";
        $focus = 'wo_material_tran_unit';
        return array("success" => false, "message" => $message, "focus_to" => $focus);
    }
    
    if($wom['wo_material_tran_qty'] <= 0){
        $message = "Quantity entered can not be zero or negative.";
        $focus = 'wo_material_tran_qty';
        return array("success" => false, "message" => $message, "focus_to" => $focus);
    }
    

    return array("success" => true, "message" => '', "focus_to" => '');
}


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


function can_delete_wo_material($id)
{
    $wo_material = get_component_from_wo_material($id);
    if(!$wo_material){
        return array("success" => false, "message" => "Could not find details of selected component in the work order", "focus_to" => "");
    }
    
    if($wo_material['units_issued'] > 0){
        return array("success" => false, "message" => "Some quantities have been issued for this item. It can not be deleted", "focus_to" => "");
    }

    return array("success" => true, "message" => "", "focus_to" => "");
}


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


function can_delete_wo_proces($workorder_id, $process_id)
{
    $bom_items = get_wo_items($workorder_id, $process_id);
    $m = db_num_rows($bom_items);
    if($m > 0){
        $message = "This process can not be deleted. There are items attached to it.";
        $focus = 'wo_procees_sequence';
        return array("success" => false, "message" => $message, "focus_to" => $focus);
    }
    
    
    $bom_labour = get_wo_labour($workorder_id, $process_id);
    $l = db_num_rows($bom_labour);
    if($l > 0){
        $message = "This process can not be deleted. There is labour attached to it.";
        $focus = 'bom_procees_sequence';
        return array("success" => false, "message" => $message, "focus_to" => $focus);
    }
    
    return array("success" => true, "message" => "", "focus_to" => "");
}

function build_wo_process_array_from_bom($wo, $bom_process_row, &$wop)
{
    $wop['wo_id'] = $wo['wo_id'];
    if(isset($bom_process_row['workorder_id'])){
        // Exisitig process from a workorder
        $wop['wo_process_id'] = $bom_process_row['id'];
    }
    else{
        // New process to be saved. Copying from a bom
        $wop['wo_process_id'] = -1;
    }
    $wop['wo_process_sequence'] = $bom_process_row['sequence'];
    $wop['wo_process_description'] = $bom_process_row['description'];
    $wop['wo_process_workcentre_id']= $bom_process_row['workcentre_id']; 
    
    $wop['wo_process_item_description'] = $bom_process_row['item_description'];
    $wop['wo_process_item_quantity'] = $bom_process_row['item_quantity'] * $wo['bom_factor'];
    
    if(isset($bom_process_row['workorder_id'])){
        $wop['wo_process_start_date_time'] = $bom_process_row['start_date_time'];
    }
    else{
        $wop['wo_process_start_date_time'] = $wo['wo_start_date_time'];  
    }
    
    $wop['wo_process_setup_time']  = seconds2time($bom_process_row['setup_time']);
    $wop['wo_process_processing_time']  = seconds2time($bom_process_row['processing_time'] * $wo['bom_factor']);
    $wop['wo_process_cleaning_time']  = seconds2time($bom_process_row['cleaning_time'] * $wo['bom_factor']);
    
    if(isset($bom_process_row['workorder_id'])){
        $wop['wo_process_end_date_time'] = $bom_process_row['end_date_time'];
//        $wop['wo_process_start_date_time'] = $bom_process_row['start_date_time']; 
    }
    else{
        $wop['wo_process_end_date_time'] = $wo['wo_end_date_time'];
//        $wop['wo_process_start_date_time'] = $wo['wo_start_date_time']; 
    }
    
    $wop['wo_process_qc']  = $bom_process_row['qc'];
    
    $wop['wo_process_comment']  = $bom_process_row['comment'];
    $wop['wo_process_type_id']  = $bom_process_row['type_id'];
    $wop['wo_process_schedule_method']  = $wo['wo_schedule_method'];
    
    $wop['wo_process_scheduling_days_limit']  = $wo['wo_scheduling_days_limit'];

}

function build_wo_process_array_from_wo($wo, $wo_process_row, &$wop)
{
    $wop['wo_id'] = $wo['wo_id'];
    if(isset($wo_process_row['workorder_id'])){
        // Exisitig process from a workorder
        $wop['wo_process_id'] = $wo_process_row['id'];
    }
    else{
        // New process to be saved. Copying from a bom
        $wop['wo_process_id'] = -1;
    }
    $wop['wo_process_sequence'] = $wo_process_row['sequence'];
    $wop['wo_process_description'] = $wo_process_row['description'];
    $wop['wo_process_workcentre_id']= $wo_process_row['workcentre_id']; 
    $wop['wo_process_type_id'] = $wo_process_row['type_id']; 
            
    $wop['wo_process_item_description'] = $wo_process_row['item_description'];
    $wop['wo_process_item_quantity'] = $wo_process_row['item_quantity'];
    
    if($wo['wo_schedule_method'] == WOSM_MANUAL){
        $wop['wo_process_start_date_time'] = $wo['wo_start_date_time'];  
    }
    elseif(isset($wo_process_row['workorder_id'])){
        $wop['wo_process_start_date_time'] = $wo_process_row['start_date_time'];
    }
    else{
        $wop['wo_process_start_date_time'] = $wo['wo_start_date_time'];  
    }
    
    $wop['wo_process_setup_time']  = seconds2time($wo_process_row['setup_time']);
    $wop['wo_process_processing_time']  = seconds2time($wo_process_row['processing_time']);
    $wop['wo_process_cleaning_time']  = seconds2time($wo_process_row['cleaning_time']);
    
    $wop['wo_process_setup_time_s']  = $wo_process_row['setup_time'];
    $wop['wo_process_processing_time_s']  = $wo_process_row['processing_time'];
    $wop['wo_process_cleaning_time_s']  = $wo_process_row['cleaning_time'];
    
    if($wo['wo_schedule_method'] == WOSM_MANUAL){
        $wop['wo_process_end_date_time'] = $wo['wo_end_date_time'];  
    }
    elseif(isset($wo_process_row['workorder_id'])){
        $wop['wo_process_end_date_time'] = $wo_process_row['end_date_time'];
    }
    else{
        $wop['wo_process_end_date_time'] = $wo['wo_end_date_time'];
    }
    
    $wop['wo_process_qc']  = $wo_process_row['qc'];
    
    $wop['wo_process_comment']  = $wo_process_row['comment'];

    $wop['wo_process_schedule_method']  = $wo['wo_schedule_method'];
    
    $wop['wo_process_scheduling_days_limit']  = $wo['wo_scheduling_days_limit'];

}

function edit_work_order($wo)
{   

    begin_transaction();
    
    switch ($wo['wo_schedule_method']) {
        case WOSM_BACKWARD_MANUAL:
        case WOSM_BACKWARD_SCHEDULAR:
            $ewobp = edit_wo_backward_processes($wo);
            if($ewobp['success'] !== true){
                cancel_transaction();
                return $ewobp;
            }
            break;
            
        case WOSM_FORWARD_MANUAL:
        case WOSM_FORWARD_SCHEDULAR:

        case WOSM_FORWARD_INLINE_MANUAL:
        case WOSM_FORWARD_INLINE_SCHEDULAR:

        case WOSM_FORWARD_PRIORITY_MANUAL:
        case WOSM_FORWARD_PRIORITY_SCHEDULAR:

            $ewofp = edit_wo_forward_processes($wo);
            if($ewofp['success'] !== true){
                cancel_transaction();
                return $ewofp;
            }
            break;
            
        case WOSM_MANUAL:
            if(isset($wo['wo_update_process_timings']) && $wo['wo_update_process_timings'] ==  true){
                $ewomp = edit_wo_manual_processes($wo);
                if($ewomp['success'] !== true){
                    cancel_transaction();
                    return $ewomp;
                }
            }
            break;
        
        default:
            return array("success" => false, "tran_no" => $wo['wo_id'], "focus_to" => '', "message" => "Unknown workorder schedule method");
                
    }
    
    if($wo['wo_schedule_method'] > WOSM_MANUAL){
        get_work_order_schedule_summary($wo);
    }
    
    $uwo = update_work_order($wo['wo_id'], $wo['wo_project_id'], $wo['wo_task_id'], 
                        $wo['wo_tran_qty'] * $wo['wo_cf'], $wo['wo_start_date_time'], 
                        $wo['wo_end_date_time'], $wo['wo_comment'], $wo['wo_tran_unit'], 
                        $wo['wo_tran_qty'], $wo['wo_cf'], $wo['wo_row_state']);    
   
    if($uwo['success'] !== true){
        cancel_transaction();
        return $uwo;
    }
    else{
        commit_transaction();
        return $uwo;
    }
  
}

function edit_wo_manual_processes($wo, &$loops = 0)
{
    $loops++;
    $wo_processes_result = get_wo_processes($wo['wo_id']);   
    while ($process_row = db_fetch($wo_processes_result)){
        delete_workcentre_process_schedule($process_row['id']);
    }

    $wo_processes_result = get_wo_processes($wo['wo_id']);
    while ($process_row = db_fetch($wo_processes_result)){
        build_wo_process_array_from_wo($wo, $process_row, $wop);
//        $wo_end_details = get_workcentre_schedule_wo_end_details($wo['wo_id']);
//        $end_ts = strtotime($wo_end_details['work_start_date_time']) + $wo_end_details['duration'];
//        $wo_end_date_time = date('Y-m-d H:i:s', $end_ts);
//        if($wo_end_date_time < $wo['wo_start_date_time']){
//            $wo_end_date_time = $wo['wo_start_date_time'];
//        }
//        $wop['wo_process_start_date_time'] = $wo_end_date_time;            
//
//        $ccwop = can_commit_wo_process($wop);
//        if($ccwop['success'] !== true){
//            $wop_prefix = $wop['wo_process_sequence']." - ".$wop['wo_process_description'];
//            $ccwop['message'] = $wop_prefix." - ".$ccwop['message'];
//            return $ccwop;
//        }

//        $swop = schedule_wo_process($wop);
        $uwot = update_wo_process_timings($wop['wo_process_id'], $wop['wo_process_start_date_time'], $wop['wo_process_end_date_time']);
        if($uwot['success'] !== true){
            return $uwot;
        }     
    }
    return array("success"=>true, "message"=>"");
}

function edit_wo_forward_processes($wo, &$loops = 0)
{
    $loops++;
    $wo_processes_result = get_wo_processes($wo['wo_id']);   
    while ($process_row = db_fetch($wo_processes_result)){
        delete_workcentre_process_schedule($process_row['id']);
    }

    $wo_processes_result = get_wo_processes($wo['wo_id']);
    while ($process_row = db_fetch($wo_processes_result)){
        build_wo_process_array_from_wo($wo, $process_row, $wop);
        $wo_end_details = get_workcentre_schedule_wo_end_details($wo['wo_id']);
        $end_ts = strtotime($wo_end_details['work_start_date_time']) + $wo_end_details['duration'];
        $wo_end_date_time = date('Y-m-d H:i:s', $end_ts);
        if($wo_end_date_time < $wo['wo_start_date_time']){
            $wo_end_date_time = $wo['wo_start_date_time'];
        }
        $wop['wo_process_start_date_time'] = $wo_end_date_time;            

        $ccwop = can_commit_wo_process($wop);
        if($ccwop['success'] !== true){
            $wop_prefix = $wop['wo_process_sequence']." - ".$wop['wo_process_description'];
            $ccwop['message'] = $wop_prefix." - ".$ccwop['message'];
            return $ccwop;
        }

        $swop = schedule_wo_process($wop);
        if($swop['success'] !== true){
            return $swop;
        }     
    }
    return array("success"=>true, "message"=>"");
}

function edit_wo_backward_processes($wo, &$loops = 0)
{
    $loops++;
    
    $wo_processes_result = get_wo_processes($wo['wo_id'], true);   
    while ($process_row = db_fetch($wo_processes_result)){
        delete_workcentre_process_schedule($process_row['id']);
    }

    $wo_processes_result = get_wo_processes($wo['wo_id'], true);
    while ($process_row = db_fetch($wo_processes_result)){
        build_wo_process_array_from_wo($wo, $process_row, $wop);
        $wo_start_details = get_workcentre_schedule_wo_start_details($wo['wo_id']);
        if($wo_start_details){
            $wo_start_date_time = $wo_start_details['work_start_date_time'];
        }
        else{
            $wo_start_date_time = "3000-01-01 00:00";
        }

        if($wo_start_date_time > $wo['wo_end_date_time']){
            $wo_start_date_time = $wo['wo_end_date_time'];
        }
        $wop['wo_process_end_date_time'] = $wo_start_date_time;

        $ccwop = can_commit_wo_process($wop);
        if($ccwop['success'] !== true){
            $wop_prefix = $wop['wo_process_sequence']." - ".$wop['wo_process_description'];
            $ccwop['message'] = $wop_prefix." - ".$ccwop['message'];
            return $ccwop;
        }

        $swop = schedule_wo_process($wop);
        if($swop['success'] !== true){
            return $swop;
        }  
    }
    
    return array("success"=>true, "message"=>"");
}


function create_workorder($wo)
{
    begin_transaction();
    
    if($wo['wo_schedule_method'] == WOSM_BACKWARD_SCHEDULAR){
        $id = add_scheduler_work_order($wo['wo_id'], $wo['wo_ref'], $wo['wo_project_id'], 
                                $wo['wo_task_id'], $wo['wo_StockLocation'], $wo['wo_tran_qty'] * $wo['wo_cf'],
                                $wo['wo_stock_id'],  $wo['wo_type'], $wo['wo_start_date_time'],
                                $wo['wo_end_date_time'], $wo['wo_comment'], $wo['wo_costs'], 
                                $wo['wo_cr_acc'], $wo['wo_labour'], $wo['cr_lab_acc'], 
                                $wo['wo_tran_unit'], $wo['wo_tran_qty'], $wo['wo_cf']);

        $wo['wo_id'] = $id;
    }
    else{
        $id = add_work_order($wo['wo_ref'], $wo['wo_project_id'], $wo['wo_task_id'], 
                                $wo['wo_StockLocation'], $wo['wo_tran_qty'] * $wo['wo_cf'],
                                $wo['wo_stock_id'],  $wo['wo_type'], $wo['wo_start_date_time'],
                                $wo['wo_end_date_time'], $wo['wo_comment'], $wo['wo_costs'], 
                                $wo['wo_cr_acc'], $wo['wo_labour'], $wo['cr_lab_acc'], 
                                $wo['wo_tran_unit'], $wo['wo_tran_qty'], $wo['wo_cf']);

        $wo['wo_id'] = $id;
    }
            
    $cwop = create_wo_processes_from_bom($wo);
    if($cwop['success'] !== true){
        cancel_transaction();
        return $cwop;
    } 
    
    /*Schedule entire workorder at once after creating material as sub boms can insert processes here and there.*/
    if($wo['wo_schedule_method'] != WOSM_MANUAL){
        $swop = schedule_wo_processes($wo);
        if($swop['success'] !== true){
            cancel_transaction();
            return $swop;
        }
        
        get_work_order_schedule_summary($wo);
    }
    
    $uwo = update_work_order($wo['wo_id'], $wo['wo_project_id'], $wo['wo_task_id'], 
                        $wo['wo_tran_qty'] * $wo['wo_cf'], $wo['wo_start_date_time'], 
                        $wo['wo_end_date_time'], $wo['wo_comment'], $wo['wo_tran_unit'], 
                        $wo['wo_tran_qty'], $wo['wo_cf'], $wo['wo_row_state']); 
    
    if($uwo['success'] !== true){
        cancel_transaction();
        return $uwo;
    }
    else{
        commit_transaction();
        return $uwo;
    }
        

}

function schedule_wo_processes($wo)
{
    switch ($wo['wo_schedule_method']) {
        case WOSM_FORWARD_MANUAL:
        case WOSM_FORWARD_SCHEDULAR:

        case WOSM_FORWARD_INLINE_MANUAL:
        case WOSM_FORWARD_INLINE_SCHEDULAR:

        case WOSM_FORWARD_PRIORITY_MANUAL:
        case WOSM_FORWARD_PRIORITY_SCHEDULAR:
            return schedule_wo_processes_forward($wo);
            
        case WOSM_BACKWARD_MANUAL:
        case WOSM_BACKWARD_SCHEDULAR:
            return schedule_wo_processes_backward($wo);
            
        case WOSM_MANUAL:
            return array("success" => true, "tran_no" => $wo['wo_id'], "focus_to" => '', "message" => "Trying to schedule process for Manual Scheduling method.");
            
        default:
            return array("success" => false, "tran_no" => $wo['wo_id'], "focus_to" => '', "message" => "Unknown workorder schedule method");
    }
}

function schedule_wo_processes_forward($wo)
{
    $wo_processes_result = get_wo_processes($wo['wo_id']);
    while ($wo_process_row = db_fetch($wo_processes_result)){
        $sch_wop = array();
        build_wo_process_array_from_wo($wo, $wo_process_row, $sch_wop);
        $wo_end_details = get_workcentre_schedule_wo_end_details($wo['wo_id']);
        $end_ts = strtotime($wo_end_details['work_start_date_time']) + $wo_end_details['duration'];
        $wo_end_date_time = date('Y-m-d H:i:s', $end_ts);
        if($wo_end_date_time < $wo['wo_start_date_time']){
            $wo_end_date_time = $wo['wo_start_date_time'];
        }
        $sch_wop['wo_process_start_date_time'] = $wo_end_date_time;   
        
        $schwop = schedule_wo_process($sch_wop);
        if($schwop['success'] !== true){
            return $schwop;
        }
    }
    return array("success" => true, "message" => "");
}

function schedule_wo_processes_backward($wo)
{
    
    $wo_processes_result = get_wo_processes($wo['wo_id'], true);
    while ($wo_process_row = db_fetch($wo_processes_result)){
        build_wo_process_array_from_wo($wo, $wo_process_row, $wop);
        $wo_start_details = get_workcentre_schedule_wo_start_details($wo['wo_id']);
        if($wo_start_details){
            $wo_start_date_time = $wo_start_details['work_start_date_time'];
        }
        else{
            $wo_start_date_time = "3000-01-01 00:00";
        }

        if($wo_start_date_time > $wo['wo_end_date_time']){
            $wo_start_date_time = $wo['wo_end_date_time'];
        }
        $wop['wo_process_end_date_time'] = $wo_start_date_time;
        
        $schwop = schedule_wo_process($wop);
        if($schwop['success'] !== true){
            return $schwop;
        }
        
    }
    
    return array("success"=>true, "message"=>"");
}


function create_wo_processes_from_bom($wo, &$loops = 0)
{
    $loops++;
    
    switch ($wo['wo_schedule_method']) {
        case WOSM_BACKWARD_MANUAL:
        case WOSM_BACKWARD_SCHEDULAR:
            return create_wo_backward_processes_from_bom($wo, $loops);
            
        case WOSM_FORWARD_MANUAL:
        case WOSM_FORWARD_SCHEDULAR:

        case WOSM_FORWARD_INLINE_MANUAL:
        case WOSM_FORWARD_INLINE_SCHEDULAR:

        case WOSM_FORWARD_PRIORITY_MANUAL:
        case WOSM_FORWARD_PRIORITY_SCHEDULAR:
            
        case WOSM_MANUAL:
            return create_wo_forward_processes_from_bom($wo, $loops);
            
        default:
            return array("success" => false, "tran_no" => $wo['wo_id'], "focus_to" => '', "message" => "Unknown workorder schedule method");

    }
}

function create_wo_backward_processes_from_bom($wo, &$loops = 0)
{
    

    $bom_processes_result = get_bom_processes($wo['wo_stock_id'], true);
    while ($bom_process_row = db_fetch($bom_processes_result)){
        build_wo_process_array_from_bom($wo, $bom_process_row, $wop);
//        $wo_start_details = get_workcentre_schedule_wo_start_details($wo['wo_id']);
//        if($wo_start_details){
//            $wo_start_date_time = $wo_start_details['work_start_date_time'];
//        }
//        else{
//            $wo_start_date_time = "3000-01-01 00:00";
//        }
//
//        if($wo_start_date_time > $wo['wo_end_date_time']){
//            $wo_start_date_time = $wo['wo_end_date_time'];
//        }
//        $wop['wo_process_end_date_time'] = $wo_start_date_time;

        $ccwop = can_commit_wo_process($wop);
        if($ccwop['success'] !== true){
            $wop_prefix = $wop['wo_process_sequence']." - ".$wop['wo_process_description'];
            $ccwop['message'] = $wop_prefix." - ".$ccwop['message'];
            return $ccwop;
        }

        $swop = save_wo_process($wop);
        if($swop['success'] !== true){
            return $swop;
        }  

        $cwom = create_wo_materials_from_bom($wo, $bom_process_row, $swop['tran_no']);
        if($cwom['success'] !== true){
            return $cwom;
        }

        $cwol = create_wo_labour_from_bom($wo, $bom_process_row, $swop['tran_no']);
        if($cwol['success'] !== true){
            return $cwol;
        }
    }
    
    return array("success"=>true, "message"=>"");
}



function create_wo_forward_processes_from_bom($wo, &$loops = 0)
{
   // return;

    $bom_processes_result = get_bom_processes($wo['wo_stock_id']);
    while ($bom_process_row = db_fetch($bom_processes_result)){
        build_wo_process_array_from_bom($wo, $bom_process_row, $wop);
//        $wo_end_details = get_workcentre_schedule_wo_end_details($wo['wo_id']);
//        $end_ts = strtotime($wo_end_details['work_start_date_time']) + $wo_end_details['duration'];
//        $wo_end_date_time = date('Y-m-d H:i:s', $end_ts);
//        if($wo_end_date_time < $wo['wo_start_date_time']){
//            $wo_end_date_time = $wo['wo_start_date_time'];
//        }
//        $wop['wo_process_start_date_time'] = $wo_end_date_time;            

        $ccwop = can_commit_wo_process($wop);
        if($ccwop['success'] !== true){
            $wop_prefix = $wop['wo_process_sequence']." - ".$wop['wo_process_description'];
            $ccwop['message'] = $wop_prefix." - ".$ccwop['message'];
            return $ccwop;
        }

        $swop = save_wo_process($wop);
        if($swop['success'] !== true){
            return $swop;
        }

        $cwom = create_wo_materials_from_bom($wo, $bom_process_row, $swop['tran_no'], $loops);
        if($cwom['success'] !== true){
            return $cwom;
        }

        $cwol = create_wo_labour_from_bom($wo, $bom_process_row, $swop['tran_no']);
        if($cwol['success'] !== true){
            return $cwol;
        }
    }
    
    return array("success"=>true, "message"=>"");
    
}

function create_wo_labour_from_bom($wo, $bom_process_row, $wo_process_id)
{
   // return;
    
    $id = -1;
    $bom_labour_result = get_bom_labour($wo['wo_stock_id'], $bom_process_row['id']);
    while ($bom_labour_row = db_fetch($bom_labour_result)){
        build_wo_labour_array($wol, $bom_labour_row, $wo_process_id);
        $ccwol = can_commit_wo_labour($wol, $id);
        if($ccwol['success'] !== true){
            return $ccwol;
        }
        else{
            $swol = save_wo_labour($wol, $id);
            if($swol['success'] !== true){
                return $swol;
            }
        }
    }
    
    return array("success" => true, "message" => "");
}

function build_wo_labour_array(&$wol,$bom_labour_row, $wo_process_id)
{
    $wol['wo_labour_process_id'] = $wo_process_id;
    $wol['wo_labour_job_category_id'] = $bom_labour_row['job_category_id'];
    $wol['wo_labour_rate_category_id'] = $bom_labour_row['rate_category_id'];
    $wol['wo_labour_setup']  = $bom_labour_row['setup'];
    $wol['wo_labour_processing']  = $bom_labour_row['processing'];
    $wol['wo_labour_cleaning']  = $bom_labour_row['cleaning'];
    $wol['wo_labour_comment']  = $bom_labour_row['comment'];
    $wol['user_id']  = $_SESSION['wa_current_user']->user;
}


function create_wo_materials_from_bom($wo, $bom_process_row, $wo_process_id, &$loops = 0)
{
   // return;
    
    $id = -1;
    $bom_items_result = get_bom_items($wo['wo_stock_id'], $bom_process_row['id']);
    while ($row = db_fetch($bom_items_result)){
        build_wo_material_array($wom, $wo, $row, $wo_process_id);
        if($wom['wo_material_MB_flag'] == "M"){
            $wo_sub_bom['wo_stock_id'] = $wom['wo_material_stock_id'] ;
            $wo_sub_bom['wo_tran_unit'] = $wom['wo_material_tran_unit'];
            $wo_sub_bom['wo_tran_qty'] = $wom['wo_material_tran_qty'];
            build_workorder_sub_bom_array($wo, $wo_sub_bom);
            
            if($loops > 1){
                return array("success" => false, "message" => "Recursive loop detected in sub BOMs in workorder ".$wo['wo_id']);
            }
            else{
                $cwop = create_wo_processes_from_bom($wo_sub_bom, $loops );
                if($cwop['success'] !== true){
                    return $cwop;
                }
            }
        }
        else{
            $ccwom = can_commit_wo_material($wom, $id);
            if($ccwom['success'] !== true){
                return $ccwom;
            }
            else{
                $swom = save_wo_material($wom, $id);
                if($swom['success'] !== true){
                    return $swom;
                }
            }
        }
    }
    
    return array("success" => true, "message" => "");
}

function build_wo_material_array(&$wom, $wo, $bom_item_row, $wo_process_id)
{
    
    $wom['wo_material_process_id'] = $wo_process_id;
    $wom['wo_material_stock_id'] = $bom_item_row['component'];
    $wom['wo_material_loc_code'] = $bom_item_row['loc_code'];
    $wom['wo_material_tran_unit'] = $bom_item_row['tran_unit'];
    $wom['wo_material_tran_qty'] = $bom_item_row['tran_qty'] * $wo['bom_factor'];
    $wom['wo_material_comment'] = $bom_item_row['comment'];
    $wom['wo_material_cf'] = $bom_item_row['conversion_factor'];
    $wom['wo_material_MB_flag'] = $bom_item_row['ResourceType'];
    $wom['user_id']  = $_SESSION['wa_current_user']->user;
   

}


function get_work_order_schedule_summary(&$wo)
{
    $wo_start_details = get_workcentre_schedule_wo_start_details($wo['wo_id']);
    $wo_start_date_time = $wo_start_details['work_start_date_time'];
    
    $wo_end_details = get_workcentre_schedule_wo_end_details($wo['wo_id']);
    $end_ts = strtotime($wo_end_details['work_start_date_time']) + $wo_end_details['duration'];
    $wo_end_date_time = date('Y-m-d H:i:s', $end_ts);
    
    $wo['wo_start_date_time'] = $wo_start_date_time;
    $wo['wo_end_date_time'] = $wo_end_date_time;
    
}


function release_workcentre_schedule($process_id, $booking_qty, $process, $process_qty)
{
    $processing_time = $process['processing_time'];
    
    $sec_per_qty = $processing_time / $process_qty;
    
    $remaing_secs = $sec_per_qty * $booking_qty;
    $result = get_workcentre_process_open_schedule($process_id);
    while ($schedule = mysql_fetch_array($result)) {
        if($schedule['remaining_duration'] > $remaing_secs){
            update_workcentre_schedule_completed_duration($schedule['id'], $remaing_secs, 0);
            $remaing_secs = 0;
            return;
        }
        elseif($schedule['remaining_duration'] == $remaing_secs){
            update_workcentre_schedule_completed_duration($schedule['id'], $remaing_secs, 1);
            $remaing_secs = 0;
            return;
        }
        else{
            $remaing_secs -= $schedule['remaining_duration'];
            update_workcentre_schedule_completed_duration($schedule['id'], $schedule['remaining_duration'], 1);
        }
    }
}


function get_could_not_complete_wc_scheduling_message($wop, $schedulling_started_date_time)
{
    $wc = get_work_centre($wop['wo_process_workcentre_id']);
    return "Could not complete workcentre scheduling within ".$wop['wo_process_scheduling_days_limit']." days 
            from [".$schedulling_started_date_time."] for workcentre [".$wc['name']."] of 
            process [".$wop['wo_process_sequence']." - ".$wop['wo_process_description']."] of 
            work_order [".$wop['wo_id']."]. Please check workcentre shifts schedule and shifts' working durations.";
}


function build_workorder_sub_bom_array($wo, &$wo_sub_bom)
{   
        $wo_sub_bom['wo_id'] = $wo['wo_id'];
        $wo_sub_bom['wo_schedule_method'] = $wo['wo_schedule_method'];
        $wo_sub_bom['wo_ref'] = $wo['wo_ref'];
        $wo_sub_bom['wo_project_id'] = $wo['wo_project_id'];
        $wo_sub_bom['wo_task_id'] = $wo['wo_task_id'];
        //$wo_sub_bom['wo_tran_unit'] = $wo['wo_tran_unit'];
        //$wo_sub_bom['wo_tran_qty'] = $wo['wo_tran_qty'];
        $wo_sub_bom['wo_start_date_time'] = $wo['wo_start_date_time'];
        $wo_sub_bom['wo_end_date_time'] = $wo['wo_end_date_time'];
        $wo_sub_bom['wo_type'] = $wo['wo_type'];
        //$wo_sub_bom['wo_stock_id'] = $wo['wo_stock_id'] ;
        $wo_sub_bom['wo_labour'] = $wo['wo_labour'];
        $wo_sub_bom['wo_costs'] = $wo['wo_costs'];
        $wo_sub_bom['wo_comment'] = $wo['wo_comment'];
        $wo_sub_bom['wo_row_state'] = $wo['wo_row_state'];
        $wo_sub_bom['wo_StockLocation'] = $wo['wo_StockLocation'];

        $stock_id = $wo_sub_bom['wo_stock_id'];
        $tran_unit = $wo_sub_bom['wo_tran_unit'];
        get_convertion_factor2($stock_id, $tran_unit, $convesion_factor);
        $wo_sub_bom['wo_tran_unit'] = $tran_unit;
        $wo_sub_bom['wo_cf'] = $convesion_factor;

        $wo_sub_bom['wo_cr_acc'] = $wo['wo_cr_acc'];
        $wo_sub_bom['cr_lab_acc'] = $wo['cr_lab_acc'];   

        $bom_header = get_bom_header($wo_sub_bom['wo_stock_id']);
        $bom_qty = $bom_header['quantity'];
        $wo_qty = $wo_sub_bom['wo_tran_qty'] * $wo_sub_bom['wo_cf'];
        $wo_sub_bom['bom_factor'] = $wo_qty/$bom_qty;

        
        $wo_sub_bom['wo_scheduling_days_limit'] = $wo['wo_scheduling_days_limit'];
 
    
}

function change_work_order_approval_status($wo, $change_type, $current_user_id)
{
    
    begin_transaction();
    
    switch ($change_type) {
        case "REJECT":
            $dawo = direct_reject_work_order($wo, $current_user_id, false);
            break;
        case "REOPEN":
            $dawo = direct_reopen_work_order($wo, $current_user_id, false);
            break;
        default:
            $dawo = direct_approve_work_order($wo, $current_user_id, false);
            break;
    }
    
    if($dawo["success"] !==  true){
        cancel_transaction();
        return $dawo;
    }
    
    switch ($change_type) {
        case "REJECT":
            commit_transaction();
            return $dawo;
        case "REOPEN":
            if($wo['wo_released'] == 1){
                $uwo = unrelease_work_order($wo['wo_id'], db_new_row_state($wo['wo_row_state']));
                if($uwo["success"] !==  true){
                    cancel_transaction();
                    return $uwo;
                }
                else{
                    commit_transaction();
                    return $uwo;
                }
            }
            else{
                commit_transaction();
                return $dawo;
            }
            break;
        default:
            commit_transaction();
            return $dawo;
           
    }
    
}

function approve_work_order($wo, $current_user_id)
{
    $wo_remaining_cost = 0;
    $wo_remaining_cost = get_work_order_remaining_total_cost($wo['wo_id']);

    $tasks_summary = array();
    add_to_task_cost($tasks_summary, $wo['wo_task_id'], $wo_remaining_cost, $wo_remaining_cost, $wo_remaining_cost);
    
    begin_transaction();
    
    $info = approve_document(ST_WORKORDER, $wo['wo_id'], $wo['wo_project_id'], $tasks_summary, 
                                        $wo['wo_next_approval_group_id'], $current_user_id, $wo['wo_row_state']);

    if($info['success'] !== true){
        cancel_transaction();
        return array("success" => $info['success'], "message" => $info['message']);
    }

    if($info['approval_status'] == AS_APPROVED){            
        $apc_msg = allocate_to_tasks(ST_WORKORDER, $wo['wo_id'], 
                                    $tasks_summary, $current_user_id);
        if($apc_msg['success'] !== true)
        {
            cancel_transaction();
            return array("success" => $apc_msg['success'], "tran_no" => $wo['wo_id'], "message" => $info['message']);
        }
    }

    commit_transaction();
    return array("success" => true, "tran_no" => $wo['wo_id'], "message" => $info['message']);
}



function reject_work_order($wo, $current_user_id)
{
    begin_transaction();
    
    $drwo = direct_reject_work_order($wo, $current_user_id, false);
    if($drwo['success'] !== true){
        cancel_transaction();
        return $drwo;
    }
    
    $material_cost = 0;
    $wom_cost = get_work_order_remaining_material_cost($wo['wo_id']);
    if(isset($wom_cost['total_cost'])){
        $material_cost = $wom_cost['total_cost'];
    }
       
    $labour_cost = 0;
    $wol_cost = get_work_order_remaining_labour_cost($wo['wo_id']);
    if(isset($wol_cost['total_cost'])){
        $labour_cost = $wom_cost['total_cost'];
    }
    
    $wo_remaining_cost = $material_cost + $labour_cost;
    $tasks_summary = array();
    add_to_task_cost($tasks_summary, $wo['wo_task_id'], $wo_remaining_cost, $wo_remaining_cost, $wo_remaining_cost);
    
    get_task_cost_details($tasks_summary);
    $rta_msg = remove_task_allocations(ST_PURCH_REQ, $wo['wo_id'], $tasks_summary, $current_user_id);
    if($rta_msg['success'] !== true){
        cancel_transaction();
        return $rta_msg;
    }
    
    commit_transaction();
    return array("success" => true, "tran_no" => $wo['wo_id'], "message" => $drwo['message']);
}

function send_work_order_back_to_originator($wo, $current_user_id)
{
//    $material_cost = 0;
//    $wom_cost = get_work_order_remaining_material_cost($wo['wo_id']);
//    if(isset($wom_cost['total_cost'])){
//        $material_cost = $wom_cost['total_cost'];
//    }
//       
//    $labour_cost = 0;
//    $wol_cost = get_work_order_remaining_labour_cost($wo['wo_id']);
//    if(isset($wol_cost['total_cost'])){
//        $labour_cost = $wom_cost['total_cost'];
//    }
//    
//    $wo_remaining_cost = $material_cost + $labour_cost;
//    $tasks_summary = array();
//    add_to_task_cost($tasks_summary, $wo['wo_task_id'], $wo_remaining_cost, $wo_remaining_cost, $wo_remaining_cost);
    
    begin_transaction();
    
    $info = send_back_to_document_originator(ST_WORKORDER, $wo['wo_id'], $wo['wo_project_id'], 
                        $wo['wo_next_approval_group_id'], $current_user_id, $wo['wo_row_state'],
                        $wo['wo_created_by']);

    if($info['success'] !== true){
        cancel_transaction();
        return array("success" => $info['success'], "message" => $info['message']);
    }

    commit_transaction();
    return array("success" => true, "tran_no" => $wo['wo_id'], "message" => $info['message']);
}


?>