<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_WORKORDERENTRY';
$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 . "/includes/inventory.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/manufacturing/includes/db/work_order_entry_db.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 . "/inventory/includes/db/alternate_units_db.inc");
include_once($path_to_root . "/manufacturing/includes/work_order_validations.inc");

//include_once($path_to_root . "/manufacturing/work_order_material.inc");


include_once($path_to_root . "/payroll/includes/db/shifts_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 = "Copy Work Order"), false, false, "", $js);


check_db_has_manufacturable_items(_("There are no manufacturable items defined in the system."));

check_db_has_locations(("There are no inventory locations defined in the system."));

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

if (isset($_GET['trans_no']))
{
	$workorder_id = $_GET['trans_no'];
}
elseif(isset($_POST['workorder_id']))
{
	$workorder_id = $_POST['workorder_id'];
}
else{
    $workorder_id  = -1;
}

$Mode = '';
//---------------------------------------------------------------------------------------

if (isset($_GET['AddedID']))
{
	$id = $_GET['AddedID'];
	$stype = ST_WORKORDER;

	display_notification_centered(_("Work order $id has been added."));

    display_note(get_trans_view_str($stype, $id, _("View this Work Order")), 0, 1);

	if ($_GET['type'] != WO_ADVANCED)
	{
		include_once($path_to_root . "/reporting/includes/reporting.inc");

		submenu_print(_("&Print This Work Order"), ST_WORKORDER, $id, 'prtopt');
		submenu_print(_("&Email This Work Order"), ST_WORKORDER, $id, null, 1);
    	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, 'PARAM_3' => '',
    		'PARAM_4' => (isset($def_print_orientation) && $def_print_orientation == 1 ? 1 : 0)); 
    	display_note(print_link(_("Print the GL Journal Entries for this Work Order"), 702, $ar), 1);
		hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$stype&trans_no=$id");
	}
	
	safe_exit();
}

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

if (isset($_GET['UpdatedID']))
{
	$id = $_GET['UpdatedID'];

	display_notification_centered(_("The work order been updated."));
	safe_exit();
}

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

if (isset($_GET['DeletedID']))
{
	$id = $_GET['DeletedID'];

	display_notification_centered(_("Work order has been deleted."));
	safe_exit();
}

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

if (isset($_GET['ClosedID']))
{
	$id = $_GET['ClosedID'];

	display_notification_centered(_("This work order has been closed. There can be no more issues against it.") . " #$id");
	safe_exit();
}

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

function safe_exit()
{
	global $path_to_root;

	hyperlink_no_params("", _("Enter a new work order"));
	hyperlink_no_params("search_work_orders.php", _("Select an existing work order"));
	
	display_footer_exit();
}

//-------------------------------------------------------------------------------------
if (!isset($_POST['date_']))
{
	$_POST['date_'] = new_doc_date();
	if (!is_date_in_fiscalyear($_POST['date_']))
		$_POST['date_'] = end_fiscalyear();
}



function display_exisiting_work_order_header($workorder_id, $myrow)
{
    
    display_heading("Copy From Workorder : ".$workorder_id);
    
    br();
    
    start_table(TABLESTYLE2);

    
//    hidden('stock_id', $_POST['stock_id']);
//    hidden('StockLocation', $_POST['StockLocation']);
//    hidden('type', $_POST['type']);

    label_row(_("Item:"), $myrow["StockItemName"]." - ".$myrow["StockItemName"]);
    label_row(_("Destination Location:"), $myrow["location_name"]);
    label_row(_("Project:"), $myrow["project_name"]);
    label_row(_("Task:"), $myrow["task_description"]);
    label_row(_("Unit:"), $myrow["requested_unit"]);
    label_row(_("Quantity Required:"), $myrow["requested_unit_qty"]);
    label_row(_("Date:"), sql2date($myrow["date_"]));
    label_row(_("Date Required By:"), sql2date($myrow["required_by"]));
    

    end_table(1);
}



function display_new_work_order_header($workorder_id, $myrow)
{
    global $Refs, $Ajax, $wo_cost_types, $wo_types_array, $SysPrefs;
    
    $project_id = -1;
    
    display_heading("New Workorder");
    
    br();
    
    start_table(TABLESTYLE2);

    $dec = 0;

    

//    if(!isset($_POST['project_id'])){
//        $project_id = $myrow["project_id"];
//    }
//    else{
//        $project_id = $_POST['project_id'];
//    }
//
//    $_POST['task_id'] = $myrow["task_id"];
//    
//
//    if(!isset($_POST['tran_unit'])){
//        $_POST['tran_unit'] = $myrow["requested_unit"];
//    }
//    if(!isset($_POST['tran_qty'])){
//        $_POST['tran_qty'] = $myrow["requested_unit_qty"];
//    }
//
//    //$_POST['StockLocation'] = $myrow["loc_code"];
//    $_POST['released'] = $myrow["released"];
//    $_POST['closed'] = $myrow["closed"];
//    $_POST['type'] = $myrow["type"];
//    $_POST['date_'] = sql2date($myrow["date_"]);
//    $_POST['RequDate'] = sql2date($myrow["required_by"]);
//    $_POST['released_date'] = sql2date($myrow["released_date"]);
//    $_POST['memo_'] = "";
//    $_POST['units_issued'] = $myrow["units_issued"];
//    $_POST['Costs'] = price_format($myrow["additional_costs"]);
//    $_POST['memo_'] = $myrow["comments"];
//
//    //hidden('wo_ref', $_POST['wo_ref']);
//    hidden('units_issued', $_POST['units_issued']);
//    hidden('released', $_POST['released']);
//    hidden('released_date', $_POST['released_date']);
    hidden('workorder_id',  $workorder_id);
//    hidden('old_qty', $myrow["units_reqd"]);
//    hidden('old_stk_id', $myrow["stock_id"]);
//    hidden('type', $myrow["type"]);
//    hidden('row_state', $myrow["row_state"]);
//
//    $_POST['units_issued'] = $_POST['released'] = 0;
//    $_POST['factor_wo'] = 1;
////    
//
//
//
//    if(isset($_POST['project_id'])){
//        $project_id = $_POST['project_id'];
//    }
//    
    
    if(!isset($_POST['wo_ref']) || $_POST['wo_ref'] == ''){
        ref_row(_("Reference:"), 'wo_ref', '', $Refs->get_next(ST_WORKORDER));
    }
    else{
        ref_row(_("Reference:"), 'wo_ref', '',$_POST['wo_ref']);
    }
    
    
    if(!isset($_POST['stock_id']) || $_POST['stock_id'] == ''){
        $_POST['stock_id'] = $myrow["stock_id"];
    }
    stock_manufactured_items_list_cells(_("Item:"), 'stock_id', null, false, true);
    
    
    if(!isset($_POST['StockLocation']) || $_POST['StockLocation'] == ''){
        $_POST['StockLocation'] = $myrow["loc_code"];
    }
    locations_list_row(_("Destination Location:"), 'StockLocation', null, false, false);
    
    if(!isset($_POST['project_id']) || $_POST['project_id'] == ''){
        $_POST['project_id'] = $myrow["project_id"];
    }
    project_list_row("Project:", "project_id", null, "Select a Project", true);
    
    if(list_updated('project_id')){
         $_POST['task_id'] = 0;
    }
    if(!isset($_POST['task_id']) || $_POST['task_id'] == 0 || $_POST['task_id'] == ''){
        $_POST['task_id'] = $myrow["task_id"];
    }
    tasks_list_row("Task:", "task_id", $_POST['project_id'], null, "Select a Task");
    

    if(!isset($_POST['tran_unit']) || $_POST['tran_unit'] == ''){
        if($_POST['stock_id'] == $myrow['stock_id']){
            $_POST['tran_unit'] = $myrow["requested_unit"];
        }
        else{
            $_POST['tran_unit'] = '';
        }
    }
    if(list_updated('stock_id')){
         $_POST['tran_unit'] = '';
    }
    units_list_row(_("Unit:"), 'tran_unit', $_POST['stock_id'], null, false, false);

    
    if (!isset($_POST['tran_qty'])){
        $_POST['tran_qty'] = qty_format($myrow["requested_unit_qty"], $_POST['stock_id'], $dec);
    }
    else{
        $_POST['tran_qty'] = qty_format($_POST['tran_qty'], $_POST['stock_id'], $dec);
    }
    qty_row(_("Quantity Required:"), 'tran_qty', null, null, null, $dec);

    date_row(_("Date") . ":", 'date_', '', true);
    date_row(_("Date Required By") . ":", 'RequDate', '', null, $SysPrefs->default_wo_required_by());


    textarea_row(_("Memo:"), 'memo_', null, 40, 5);
    
    if(!isset($_POST['factor_wo'])){
         $_POST['factor_wo'] = 1.00000;
    }
    qty_row(_("Factor:"), 'factor_wo', null, null, null, 5);
    end_table(1);


    br();
    submit_center_first('Add_WO_Manual', _("Manual Add (No Scheduling)"), '', 'default');
    br(2);    
    submit_center_first('Add_WO_Forward', _("Add - Forward"), '', 'default');
    submit('Add_WO_Forward_Inline', _("Add - Forward Inline"), true, '', 'default');
    //submit_center_last('Add_WO_Forward_Priority', _("Add - Forward Priority"), '', 'default');
    br(2);
    submit_center_last('Add_WO_Backward',_("Add - Schedule Backwards"), '', 'default');
    
    br(2);
    
}



function build_workorder_array($copy_from_wo_id, $factor, $schedule_method, &$wo)
{   
        $wo['wo_id'] = -1;
        $wo['wo_schedule_method'] = $schedule_method;
        $wo['wo_ref'] = $_POST['wo_ref'];
        $wo['wo_project_id'] = $_POST['project_id'];
        $wo['wo_task_id'] = $_POST['task_id'];
        $wo['wo_tran_unit'] = $_POST['tran_unit'];
        $wo['wo_tran_qty'] = $_POST['tran_qty'];
        
        $start_date = date2sql($_POST['date_']);
        $start_date .= " 08:00:00"; 
        $end_date = date2sql($_POST['RequDate']);
        $end_date .= " 17:00:00"; 
        $wo['wo_start_date_time'] = $start_date;
        $wo['wo_end_date_time'] = $end_date;
        $wo['wo_type'] = WO_ADVANCED;
        $wo['wo_stock_id'] = $_POST['stock_id'];
        $wo['wo_labour'] = 0;
        $wo['wo_costs'] = 0;
        $wo['wo_comment'] = $_POST['memo_'];
        $wo['wo_row_state'] = 0;
        $wo['wo_StockLocation'] = get_post('StockLocation');
        

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

        $wo['wo_cr_acc'] = get_post('cr_acc');
        $wo['cr_lab_acc'] = get_post('cr_lab_acc');   

        $wo['bom_factor'] = $factor;

 
    
}

function build_workorder_process_array($wo, $factor, $wo_process_data, $schedule_method, &$wop)
{   
       
    
        $wop['wo_id']= $wo['wo_id'];
        $wop['wo_process_id'] = -1;
        $wop['wo_process_sequence']=$wo_process_data['sequence'];
        $wop['wo_process_workcentre_id']=$wo_process_data['workcentre_id'];      
        $wop['wo_process_description']= $wo_process_data['description'];
        $wop['wo_process_type_id'] = $wo_process_data['type_id'];
        $wop['wo_process_item_description']= $wo_process_data['item_description'];
        $wop['wo_process_item_quantity']= $wo_process_data['item_quantity']*$factor;
        $wop['wo_process_start_date_time']= $wo['wo_start_date_time'];
        $wop['wo_process_setup_time_s']= $wo_process_data['setup_time'];
        $wop['wo_process_processing_time_s']= $wo_process_data['processing_time']*$factor;
        $wop['wo_process_cleaning_time_s']= $wo_process_data['cleaning_time'];
        $wop['wo_process_end_date_time']= $wo['wo_end_date_time'];
        $wop['wo_process_qc']= $wo_process_data['qc'];
        $wop['wo_process_comment']= get_post('memo_');  
        $wop['wo_process_schedule_method']= $schedule_method;   
        $wop['wo_process_scheduling_days_limit']  = get_workcentre_scheduling_days_limit();
        

}

function build_workorder_material_array($new_work_order_id,$process_id,$wo_material_data,$factor,&$wom)
{   
       
    
        $wom['wo_id']=$new_work_order_id;
        $wom['wo_material_process_id']=$process_id;
        $wom['wo_material_stock_id']=$wo_material_data['stock_id'];
        $wom['wo_material_workcentre_id']=$wo_material_data['workcentre'];
        $wom['wo_material_tran_qty']=$wo_material_data['req_unit_qty']*$factor; 
        $wom['wo_material_tran_unit']=$wo_material_data['req_unit'];
        $wom['wo_material_cf']=$wo_material_data['req_unit_conversion_factor'];
        $wom['wo_material_std_cost']=$wo_material_data['std_cost']*$factor;
        $wom['wo_material_loc_code']=$wo_material_data['loc_code'];
        $wom['wo_material_comment']=$wo_material_data['comment'];
//        $wom['user_id']
        

     
    
}

function build_workorder_labour_array($new_work_order_id,$process_id,$factor,$wo_labour,&$wol)
{   
       
    
        $wol['wo_labour_process_id']=$process_id;
        $wol['wo_labour_job_category_id']=$wo_labour['job_category_id'];
        $wol['wo_labour_rate_category_id'] =$wo_labour['rate_category_id'];
        $wol['wo_labour_setup'] =$wo_labour['setup'];
        $wol['wo_labour_processing'] =$wo_labour['processing'];
        $wol['wo_labour_cleaning'] =$wo_labour['processing'];
        $wol['wo_labour_comment']=$wo_labour['comment'];
        $wol['wo_id']= $new_work_order_id;
        

     
    
}

function can_commit_copy_wo()
{
    if (!check_num('factor_wo',0.0001)) 
	{
		display_error(_("Factor value entered is not numeric or positive."));
		set_focus('factor_wo');
		return false;
	} 
    
    return true;
}

function save_workorder($copy_from_wo_id, $factor, $schedule_method)
{
    if(!can_commit_copy_wo()){
        return;
    }
    
    $wo = array();
    build_workorder_array($copy_from_wo_id, $factor, $schedule_method, $wo);
    
    $ccwo = can_commit_workorder($wo);
    if($ccwo['success'] !== true){
        if(isset($ccwo['focus_to'])){
            set_focus($ccwo['focus_to']);
        }
        return $ccwo;
    }
  
    //$cwo = create_workorder($wo);
    $new_wo_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']);
    
    if(!($new_wo_id > 0)){
        return array("success" => false, "message" => 'Could not create new workorder'); 
    }
    $wo['wo_id'] = $new_wo_id;
    
    $wo_processes = get_wo_processes($copy_from_wo_id);
    while($wo_process_data= db_fetch($wo_processes))
    {
        $wop = array();
        build_workorder_process_array($wo, $factor, $wo_process_data, $schedule_method, $wop);
        $swop=save_wo_process($wop);
        if($swop['success'] !== true){
            return $swop;
        }
        
        
        $wo_items_data= get_wo_items($copy_from_wo_id, $wo_process_data['id']);
        while($wo_items=db_fetch($wo_items_data))
        {
            $wom = array();
            build_workorder_material_array($wo['wo_id'], $swop['tran_no'], $wo_items, $factor, $wom);
            $swom = save_wo_material($wom, -1);
            if($swom['success'] !== true){
                return $swom;
            }
        }
        
        
        $labour_data=get_wo_labour($copy_from_wo_id, $wo_process_data['id']);
        while($wo_labour=db_fetch($labour_data))
        {
            $wol = array();
            build_workorder_labour_array($wo['wo_id'],$swop['tran_no'], $factor, $wo_labour, $wol);
            $swol = save_wo_labour($wol, -1);
            if($swol['success'] !== true){
                return $swol;
            }
        }
    }

    if($wo['wo_schedule_method'] != WOSM_MANUAL){
        $swop = schedule_wo_processes($wo);
        if($swop['success'] !== true){
            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){
        return $uwo;
    }
            
    new_doc_date($_POST['date_']);
    meta_forward($_SERVER['PHP_SELF'], "AddedID=".$wo['wo_id']."&type=".$wo['wo_type']."&date=".sql2date($wo['wo_start_date_time']));

}


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


if(isset($_POST['Add_WO_Manual'])){
    $swo_msg = save_workorder($workorder_id, $_POST['factor_wo'], WOSM_MANUAL, true);  
    if($swo_msg['success'] === true){
        $Mode = '';
        $selected_id = -1;
    }
    else{
        display_error($swo_msg['message']);
        set_focus($swo_msg['focus_to']);
    }
}

if(isset($_POST['Add_WO_Forward'])){
    $swo_msg = save_workorder($workorder_id, $_POST['factor_wo'], WOSM_FORWARD_MANUAL);   
    if($swo_msg['success'] === true){
        $Mode = '';
        $selected_id = -1;
    }
    else{
        display_error($swo_msg['message']);
        set_focus($swo_msg['focus_to']);
    }
}

if(isset($_POST['Add_WO_Forward_Inline'])){
    $swo_msg = save_workorder($workorder_id, $_POST['factor_wo'], WOSM_FORWARD_INLINE_MANUAL);   
    if($swo_msg['success'] === true){
        $Mode = '';
        $selected_id = -1;
    }
    else{
        display_error($swo_msg['message']);
        set_focus($swo_msg['focus_to']);
    }
}

if(isset($_POST['Add_WO_Forward_Priority'])){
    $swo_msg = save_workorder($workorder_id, $_POST['factor_wo'], WOSM_FORWARD_PRIORITY_MANUAL);   
    if($sbp_msg['success'] === true){
        $Mode = '';
        $selected_id = -1;
    }
    else{
        display_error($swo_msg['message']);
        set_focus($swo_msg['focus_to']);
    }
}

if(isset($_POST['Add_WO_Backward'])){
    $swo_msg = save_workorder($workorder_id, $_POST['factor_wo'], WOSM_BACKWARD_MANUAL);  
    if($swo_msg['success'] === true){
        $Mode = '';
        $selected_id = -1;
    }
    else{
        display_error($swo_msg['message']);
        set_focus($swo_msg['focus_to']);
    }
}

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


if ($Mode == 'RESET')
{
	$selected_id = '';
	$sav = get_post('show_inactive');
	unset($_POST);
	$_POST['show_inactive'] = $sav;
}

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





//-------------------------------------------------------------------------------------
if (get_post('_type_update')) 
{
  $Ajax->activate('_page_body');
}
//-------------------------------------------------------------------------------------

start_form();

if ($workorder_id != -1){
    $work_order = get_work_order_header($workorder_id);
}
else{
    $work_order = null;
}
    
display_exisiting_work_order_header($workorder_id, $work_order);

br();
br();


display_new_work_order_header($workorder_id, $work_order);

//general_settings($selected_id);

end_form();
end_page();

?>