<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_MANUFRECEIVE';
$path_to_root = "..";
include_once($path_to_root . "/includes/session.inc");

include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/gl/includes/db/gl_db_bank_trans.inc");
include_once($path_to_root . "/includes/db/inventory_db.inc");
include_once($path_to_root . "/includes/inventory.inc");

include_once($path_to_root . "/manufacturing/includes/manufacturing_db.inc");
include_once($path_to_root . "/manufacturing/includes/manufacturing_ui.inc");
include_once($path_to_root . "/manufacturing/includes/db/work_order_booking_db.inc");
include_once($path_to_root . "/manufacturing/includes/work_order_validations.inc");

include_once($path_to_root . "/payroll/includes/db/employees_db.inc");

$js = "";
if ($SysPrefs->use_popup_windows)
	$js .= get_js_open_window(900, 500);
if (user_use_date_picker())
	$js .= get_js_date_picker();
page(_($help_context = "Workorder Production Booking"), false, false, "", $js);

if (isset($_GET['trans_no']) && $_GET['trans_no'] != "")
{
	$_POST['selected_id'] = $_GET['trans_no'];
}

$selected_process_id = -1;

function get_selected_process_id(&$selected_process_id, &$Mode)
{
    foreach( $_POST as $key => $post_var ) {
        if(!is_array( $post_var ) ) {
            $time = substr($key,0,19);
            if($time == 'Edit_Process_id_Qty'){
                $selected_process_id = substr($key,19);
                $Mode = "Qty_Entry";
                return ;
            }
            $labour = substr($key,0,22);
            if($labour == 'Edit_Process_id_Labour'){
                $selected_process_id = substr($key,22);
                $Mode = "Labour_Entry";
                return ;
            }
        } 
    }
    if(isset($_POST['process_id']))
    {
        $selected_process_id=$_POST['process_id'];
        if(isset($_POST['Add_Order_Booking_Qty'])){
            $Mode = "Qty_Entry";
        }
        if(isset($_POST['Add_Order_Booking_Labour'])){
            $Mode = "Labour_Entry";
        }
        

    }
    
    return -1;
}

get_selected_process_id($selected_process_id, $Mode);
//--------------------------------------------------------------------------------------------------

if (isset($_GET['AddedID']))
{
	include_once($path_to_root . "/reporting/includes/reporting.inc");
	$id = $_GET['AddedID'];
	$stype = ST_WORKORDER;

	display_notification(_("The manufacturing process has been entered."));
	
        display_note(get_trans_view_str($stype, $id, _("View this Work Order")));

   	display_note(get_gl_view_str($stype, $id, _("View the GL Journal Entries for this Work Order")), 1);
   	$ar = array('PARAM_0' => $_GET['date'], 'PARAM_1' => $_GET['date'], 'PARAM_2' => $stype); 
   	display_note(print_link(_("Print the GL Journal Entries for this Work Order"), 702, $ar), 1);

	hyperlink_no_params("search_work_orders.php", _("Select another &Work Order to Process"));
	br();

	end_page();
	exit;
}

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

$wo_details = get_work_order($_POST['selected_id']);
//$wo_processes = get_wo_processes($_POST['Edit_WO_Process']);

if (strlen($wo_details[0]) == 0)
{
	display_error(_("The order number sent is not valid."));
	exit;
}

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

function can_process_qty($process_id)
{
    //validate quantity
    //validate date
    //validate start and end times
    //start time should be earlier than end time
    
    $start_date_time=date2sql(get_post('date'))." ".get_post('work_start_time');
    $end_date_time=date2sql(get_post('date'))." ".get_post('work_end_time');
	
	if (!check_num('booking_qty', 0))
	{
		display_error(_("The quantity entered is not a valid number or less then zero."));
		set_focus('booking_qty');
		return false;
	}
        if (get_post('booking_qty')<= 0)
	{
		display_error(_("Please enter a quantity"));
		set_focus('booking_qty');
		return false;
	}

	if (!is_date($_POST['date']))
	{
		display_error(_("The entered date is invalid."));
		set_focus('date_');
		return false;
	}
        
        if (!is_time($_POST['work_start_time']))
	{
		display_error(_("The entered start time is invalid."));
		set_focus('work_start_time');
		return false;
	}
        
        if (!is_time($_POST['work_end_time']))
	{
		display_error(_("The entered end time is invalid."));
		set_focus('work_end_time');
		return false;
	}
        
        if ($_POST['work_end_time']< $_POST['work_start_time'])
	{
		display_error(_("Start time should be earlier than end time."));
		set_focus('work_end_time');
		return false;
	}
        
         if ($_POST['work_end_time']== $_POST['work_start_time'])
	{
		display_error(_("Start time and end time cannot be same."));
		set_focus('work_end_time');
		return false;
	}
        
    if($_POST['is_return'] == 0){
        $employee_labour=get_process_qty_booking_details($process_id, $start_date_time, $end_date_time);
        if($employee_labour)
        {
            display_error(_("There is an already entered overlapping quantity booking detail."));
            set_focus('work_start_time');
            return false;    
        }
    }

	return true;
}


function can_process_labour($process_id, $rate_category)
{
    $start_date_time=date2sql(get_post('date'))." ".get_post('work_start_time');
    $end_date_time=date2sql(get_post('date'))." ".get_post('work_end_time');
    if ($_POST['employee_code'] =='0' )
	{
		display_error(_("Please select an employee code"));
		set_focus('employee_code');
		return false;
	}
    
    if(!$rate_category)
    {
        display_error("No Rate Category found for the date ".get_post('date')." for the selected employee");
        set_focus('employee_code');
		return false;
    }
    
        
        if (!is_date($_POST['date']))
	{
		display_error(_("The entered date is invalid."));
		set_focus('date_');
		return false;
	}
        
         if (!is_time($_POST['work_start_time']))
	{
		display_error(_("The entered start time is invalid."));
		set_focus('work_start_time');
		return false;
	}
        
        if (!is_time($_POST['work_end_time']))
	{
		display_error(_("The entered end time is invalid."));
		set_focus('work_end_time');
		return false;
	}
        if ($_POST['work_end_time']< $_POST['work_start_time'])
	{
		display_error(_("Start time should be earlier than end time."));
		set_focus('work_end_time');
		return false;
	}
         if ($_POST['work_end_time']== $_POST['work_start_time'])
	{
		display_error(_("Start time and end time cannot be same."));
		set_focus('work_end_time');
		return false;
	}
        
    if($_POST['is_return'] == 0){
        $employee_labour=get_employee_labour_booking_details($_POST['employee_code'], $start_date_time, $end_date_time);
        if($employee_labour)
        {
            display_error(_("There is an already entered overlapping labour booking detail."));
            set_focus('work_start_time');
            return false;    
        }
    }
        
        
        return true;
    
}

function display_wo_qty_booking_controls($process_id)
{
    $procees_details= get_wo_process($process_id);

    $_POST['process_id']  = $procees_details["id"];
    $_POST['process_des']  = $procees_details["description"];
    $_POST['work_centre']  = $procees_details["workcentre_name"];
    $_POST['process_item_description']  = $procees_details["item_description"];
    
    if(isset($_POST['Edit_Process_id_Qty'.$procees_details["id"]])){
        $_POST['booking_qty']  = $procees_details["item_quantity"] - $procees_details["qty_completed"];
    }
    if(!isset($_POST['booking_qty'])){
        $_POST['booking_qty']  = $procees_details["item_quantity"];
    }

    hidden('process_id', $_POST['process_id']);
    
    label_row("Work order processes:",  $_POST['process_des']);

    label_row("Work centre:", $_POST['work_centre'] );

    label_row("Item Description:", $_POST['process_item_description']);
    two_value_list_row("Type", 'is_return',"0", "Add","Return" ,"0","1");    

    small_qty_row("Quantity:", 'booking_qty', null, null, null);

    date_row(_("Date:"), 'date');
    
    if(isset($_POST['Edit_Process_id_Qty'.$procees_details["id"]])){
        $_POST['work_start_time']  = "09:00";
    }
    if(!isset($_POST['work_start_time'])){
       $_POST['work_start_time']  = "09:00";
    }
    time_row("Start Time (hhh:mm) :", "work_start_time", null, 5);
    
    if(isset($_POST['Edit_Process_id_Qty'.$procees_details["id"]])){
        $_POST['work_end_time']  = "17:00";
    }
    if(!isset($_POST['work_end_time'])){
       $_POST['work_end_time']  = "17:00";
    }
    time_row("End Time (hhh:mm) :", "work_end_time", null, 5);
    
    textarea_row(_("Memo:"), 'comment', null, 40, 3);

    end_table(1);

    submit_center_first('Add_Order_Booking_Qty', _("Save Quantity"), '', 'default');    
    div_end();
    
}


function display_wo_labour_booking_controls($process_id)
{
    $procees_details= get_wo_process($process_id);

    $_POST['process_id']  = $procees_details["id"];
    $_POST['process_des']  = $procees_details["description"];
    $_POST['work_centre']  = $procees_details["workcentre_name"];
    $_POST['process_item_description']  = $procees_details["item_description"];
    $_POST['booking_qty']  = $procees_details["item_quantity"];

    hidden('process_id', $_POST['process_id']);
    
    label_row("Work order processes:",  $_POST['process_des']);

    label_row("Work centre:", $_POST['work_centre'] );

    label_row("Item Description:", $_POST['process_item_description']);

    two_value_list_row("Type", 'is_return',"0", "Add","Return" ,"0","1");  
    
    workorder_process_work_type_list_row("Worktype", "worktype", 2);
    
    employees_simple_list_row("Employee :", "employee_code", null, "");
    //small_qty_row("Quantity:", 'booking_qty', null, null, null);

    date_row(_("Date:"), 'date');
    
    if(isset($_POST['Edit_Process_id_Labour'.$procees_details["id"]])){
        $_POST['work_start_time']  = "09:00";
    }
    if(!isset($_POST['work_start_time'])){
       $_POST['work_start_time']  = "09:00";
    }
    time_row("Start Time (hhh:mm) :", "work_start_time", null, 5);
    
    if(isset($_POST['Edit_Process_id_Labour'.$procees_details["id"]])){
        $_POST['work_end_time']  = "17:00";
    }
    if(!isset($_POST['work_end_time'])){
       $_POST['work_end_time']  = "17:00";
    }
    time_row("End Time (hhh:mm) :", "work_end_time", null, 5);

    textarea_row(_("Memo:"), 'comment', null, 40, 3);

    end_table(1);
    
    submit_center_first('Add_Order_Booking_Labour', _("Save Labour"), '', 'default');
    
    div_end();
    
}

function add_workorder_process_booking_qty($process_id)
{
    $booking_qty = 0;
    $start_date_time=date2sql(get_post('date'))." ".get_post('work_start_time');
    $end_date_time=date2sql(get_post('date'))." ".get_post('work_end_time');
    $booking_qty = $_POST['booking_qty'];

    $is_return=get_post('is_return');
    if($is_return == '1')
    {
        $booking_qty = $booking_qty * -1;
    }
    
    begin_transaction();
    add_wo_process_manufactured_qty( $process_id,$booking_qty,$start_date_time,$end_date_time,$_POST['comment']);
    
    $process = get_wo_process($process_id);
    if($process['item_quantity'] == 0){
        $wo = get_work_order_header($process['workorder_id']);
        $process_qty = $wo['requested_unit_qty'];
    }
    else{
        $process_qty = $process['item_quantity'];
    }
    
    $close = 0;
    if(($process_qty - $process['qty_completed']) <= $booking_qty){
        $$close = 1;
    }
    add_wo_process_completed_qty($process_id, $booking_qty, $close);
    
    if($booking_qty > 0){
        close_workcentre_process_schedules($process_id, WOPWT_SETUP);
    }
    
    if($booking_qty > 0){
        release_workcentre_schedule($process_id, $booking_qty, $process, $process_qty);
    }
    
    if($close == 1){
        close_workcentre_process_schedules($process_id, WOPWT_PROCESSING);
        close_workcentre_process_schedules($process_id, WOPWT_CLEANING);
    }
    
    commit_transaction();
    
}


function add_workorder_process_booking_labour($process_id, $company_code, $employee, $rate_category)
{
    $start_date_time=date2sql(get_post('date'))." ".get_post('work_start_time');
    $end_date_time=date2sql(get_post('date'))." ".get_post('work_end_time');
    //use a new db file called workorder_booking_db
    
//    add_wo_process_booking_labour( $process_id, $_POST['worktype'], $_POST['employee_code'], 
//                            $_POST['comment'], $start_date_time, $end_date_time,
//                            $_POST['add_return']);
    $employee_name = $employee['first_name']." ".$employee['last_name'];
    
    add_wo_process_booking_labour( $process_id, $_POST['worktype'], $employee['employee_code'], $employee_name,
                            $_POST['comment'], $start_date_time, $end_date_time,
                            $_POST['is_return'], $company_code, $rate_category['rate_category_id'],
                            $rate_category['rate']);

}


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

if(isset($_POST['process_id']))
{
    $process_id=$_POST['process_id'];
    
}

//$process_id=get_post('process_id');


if(isset($_POST['Add_Order_Booking_Qty']) && can_process_qty($process_id)) 
{

    add_workorder_process_booking_qty($process_id);
    $Mode = 'RESET';

    display_notification(_('Workorder quantity booking details have been saved.'));
    
}

if(isset($_POST['Add_Order_Booking_Labour'])) 
{
    $company_code = CC_SAW;
    
    $employee = get_employee($_POST['employee_code']);
    $rate_category=get_employee_current_rate(get_post('date'),$_POST['employee_code']);
    
    if(!can_process_labour($process_id, $rate_category)){
        return;
    }

    add_workorder_process_booking_labour($process_id, $company_code, $employee, $rate_category);
    $Mode = 'RESET';
    display_notification(_('Workorder labour booking details have been saved.'));
    
    
}

global  $Ajax;

$Ajax->Activate("process_info");
//-------------------------------------------------------------------------------------
start_form();
display_wo_details($_POST['selected_id']);
br();
br();

$Ajax->Activate("Processes");
div_start("Processes");
display_wo_process_details($_POST['selected_id']);
div_end();

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



hidden('selected_id', $_POST['selected_id']);
//hidden('WOReqQuantity', $_POST['WOReqQuantity']);

div_start("process_info");
start_table(TABLESTYLE2);
br();
if ($selected_process_id > 0) 
{
    if($Mode == "Qty_Entry"){
        display_wo_qty_booking_controls($selected_process_id);
    }
    elseif($Mode == "Labour_Entry"){
        display_wo_labour_booking_controls($selected_process_id);
    }

}

end_table();

div_end();

end_form();

end_page();

?>