<?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/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 . "/payroll/includes/db/shifts_db.inc");

include_once($path_to_root . "/includes/project_cost_functions.inc");
include_once($path_to_root . "/projects/includes/db/projects_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 = "Work Order Entry"), 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(_("Work order $id has 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_wo_header($workorder_id, $myrow)
{
    global $Refs, $Ajax, $wo_cost_types, $wo_types_array, $SysPrefs, $approval_statuses;
    
    
    start_table(TABLESTYLE2);

    $existing_comments = "";

    $dec = 0;
    if ($workorder_id != -1)
    {
        if (strlen($myrow[0]) == 0)
        {
            echo _("The order number sent is not valid.");
            safe_exit();
        }

        // if it's a closed work order can't edit it
        if ($myrow["closed"] == 1)
        {
            echo "<center>";
            display_error(_("This work order is closed and cannot be edited."));
            safe_exit();
        }

        $_POST['wo_ref'] = $myrow["wo_ref"];
        $_POST['stock_id'] = $myrow["stock_id"];
        //$_POST['quantity'] = qty_format($myrow["units_reqd"], $_POST['stock_id'], $dec);
        //$_POST['quantity'] = $myrow["units_reqd"];
        $_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"];
        
        $_POST["approval_status"] = $myrow["approval_status"];
        $_POST["row_state"] = $myrow["row_state"];

        hidden('wo_ref', $_POST['wo_ref']);
        hidden('stock_id', $_POST["stock_id"]);
        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('row_state', $_POST["row_state"]);

        label_row(_("Reference:"), $_POST['wo_ref']);
        label_row(_("Type:"), $wo_types_array[$_POST['type']]);
        hidden('type', $myrow["type"]);
    }
    else
    {
        $_POST['units_issued'] = $_POST['released'] = 0;
        ref_row(_("Reference:"), 'wo_ref', '', $Refs->get_next(ST_WORKORDER));

        if(!isset($_POST['type'])){
            $_POST['type'] = 2;
        }
//        wo_types_list_row(_("Type:"), 'type', null);
        label_row(_("Type:"), $wo_types_array[$_POST['type']]);
        hidden('type', $_POST['type']);
    }

    if (get_post('workorder_id') || $workorder_id != -1)
    {
        hidden('stock_id', $_POST['stock_id']);
        hidden('StockLocation', $_POST['StockLocation']);
        hidden('type', $_POST['type']);

        label_row(_("Item:"), $myrow["StockItemName"]);
        label_row(_("Destination Location:"), $myrow["location_name"]);
        
        $s = get_project_trans_view_str(ST_APPROVAL_LOG, $workorder_id."&source_type_id=".ST_WORKORDER, "Approval Status");
        label_row($s,$approval_statuses[$_POST["approval_status"]]);
    }
    else
    {
        stock_manufactured_items_list_row(_("Item:"), 'stock_id', null, false, true);
        if (list_updated('stock_id'))
            $Ajax->activate('quantity');
                    $Ajax->activate('tran_unit');
                    $Ajax->activate('tran_qty');

        //units_list_row(_("Unit:"), 'tran_unit', $_POST['stock_id'], null, false, true);
        locations_list_row(_("Destination Location:"), 'StockLocation', null, false, false);
    }

    end_table(1);
}



function display_workorder_tabs($workorder_id, $work_order, $path_to_root)
{
    div_start('details');

    if (!$work_order){
        unset($_POST['_tabs_sel']); // force settings tab for new customer
    }

    tabbed_content_start('tabs', array(
            'settings' => array(_('&General settings'), $work_order),
            'wo_processes' => array(_('&Processes'), $work_order),
            'wo_material' => array(_('&Material'), $work_order),
            'wo_labour' => array(_('&Labour'), $work_order),
        ));
	
	switch (get_post('_tabs_sel')) {
		default:
         case 'settings':    
            general_settings($workorder_id, $work_order); 
			break;
            
        case 'wo_processes':
            $_GET['work_order_id'] = $work_order['id'];
			$_GET['popup'] = 1;
			include_once($path_to_root."/manufacturing/work_order_processes.php"); 
			break;
		case 'wo_material':
			$_GET['work_order_id'] = $work_order['id'];
			$_GET['popup'] = 1;
			include_once($path_to_root."/manufacturing/work_order_material.php");
			break;
		case 'wo_labour':
			$_GET['work_order_id'] = $work_order['id'];
			$_GET['popup'] = 1;
			include_once($path_to_root."/manufacturing/work_order_labour.php");
			break;
	};
    br();
    tabbed_content_end();

    div_end();    
}




function general_settings($workorder_id, $myrow)
{
    global $Refs, $Ajax, $wo_cost_types, $wo_types_array, $SysPrefs;
    
    $project_id = -1;
    
    start_table(TABLESTYLE2);

    $existing_comments = "";

    $dec = 0;
    if ($workorder_id != -1)
    {

        $_POST['wo_ref'] = $myrow["wo_ref"];
        
        if(!(isset($_POST['project_id']) && $_POST['project_id'] > 0)){
            if((isset($_POST['_project_id_edit']) && $_POST['_project_id_edit'] > 0)){
                $_POST['project_id'] = $_POST['_project_id_edit'];
            }
            else{
                $_POST['project_id'] = $myrow["project_id"];
                $project_id = $_POST["project_id"];
            }
        }
        else{
            $project_id = $_POST['project_id'];
        }
        
        if((isset($_POST['project_id']) && $_POST['project_id'] > 0)){
            $_POST['_project_id_edit'] = $_POST['project_id'];
        }
        
        $_POST['task_id'] = $myrow["task_id"];
        $_POST['stock_id'] = $myrow["stock_id"];
        //$_POST['quantity'] = qty_format($myrow["units_reqd"], $_POST['stock_id'], $dec);
        //$_POST['quantity'] = $myrow["units_reqd"];
        
        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"]);

        //label_row(_("Reference:"), $_POST['wo_ref']);
        //label_row(_("Type:"), $wo_types_array[$_POST['type']]);
        hidden('type', $myrow["type"]);
        hidden('row_state', $myrow["row_state"]);
    }
    else
    {
        $_POST['units_issued'] = $_POST['released'] = 0;
        //ref_row(_("Reference:"), 'wo_ref', '', $Refs->get_next(ST_WORKORDER));

        //wo_types_list_row(_("Type:"), 'type', null);
    }

//    if (get_post('released'))
//    {
//        hidden('stock_id', $_POST['stock_id']);
//        hidden('StockLocation', $_POST['StockLocation']);
//        hidden('type', $_POST['type']);
//
//        label_row(_("Item:"), $myrow["StockItemName"]);
//        label_row(_("Destination Location:"), $myrow["location_name"]);
//    }
//    else
//    {
//        stock_manufactured_items_list_row(_("Item:"), 'stock_id', null, false, true);
//        if (list_updated('stock_id'))
//            $Ajax->activate('quantity');
//                    $Ajax->activate('tran_unit');
                    
    

    if(isset($_POST['project_id'])){
        $project_id = $_POST['project_id'];
    }
    
    if(isset($_POST['_project_id_edit']) && $_POST['_project_id_edit'] > 0){
        $_POST['project_id'] = $_POST['_project_id_edit'];
        $project_id = $_POST['project_id'];
    }
    
    project_list_row("Project:", "project_id", $project_id, "Select a Project", true);
    tasks_list_row("Task:", "task_id", $project_id, null, "Select a Task");
    units_list_row(_("Unit:"), 'tran_unit', $_POST['stock_id'], null, false, false);
//        locations_list_row(_("Destination Location:"), 'StockLocation', null);
//    }

    if (!isset($_POST['tran_qty'])){
        $_POST['tran_qty'] = qty_format(1, $_POST['stock_id'], $dec);
    }
    else{
        $_POST['tran_qty'] = qty_format($_POST['tran_qty'], $_POST['stock_id'], $dec);
    }


    if (get_post('type') == WO_ADVANCED)
    {
        qty_row(_("Quantity Required:"), 'tran_qty', null, null, null, $dec);
        if ($_POST['released']){
            label_row(_("Quantity Manufactured:"), number_format($_POST['units_issued'], get_qty_dec($_POST['stock_id'])));
        }
        date_row(_("Start Date") . ":", 'date_', '', true);
        date_row(_("End Date") . ":", 'RequDate', '', null, $SysPrefs->default_wo_required_by());
    }
    else
    {
        qty_row(_("Quantity:"), 'tran_qty', null, null, null, $dec);
        date_row(_("Date") . ":", 'date_', '', true);
        hidden('RequDate', '');

        $sql = "SELECT DISTINCT account_code FROM ".TB_PREF."bank_accounts";
        $rs = db_query($sql,"could not get bank accounts");
        $r = db_fetch_row($rs);
        if (!isset($_POST['Labour']))
        {
            $_POST['Labour'] = price_format(0);
            $_POST['cr_lab_acc'] = $r[0];
        }
        amount_row($wo_cost_types[WO_LABOUR], 'Labour');
        gl_all_accounts_list_row(_("Credit Labour Account"), 'cr_lab_acc', null);
        if (!isset($_POST['Costs']))
        {
            $_POST['Costs'] = price_format(0);
            $_POST['cr_acc'] = $r[0];
        }
        amount_row($wo_cost_types[WO_OVERHEAD], 'Costs');
        gl_all_accounts_list_row(_("Credit Overhead Account"), 'cr_acc', null);

    }

    if (get_post('released')){
        label_row(_("Released On:"),$_POST['released_date']);
    }

    textarea_row(_("Memo:"), 'memo_', null, 40, 5);

    yesno_list_row("Update All Processes Timings:", "update_process_timings");
    end_table(1);

//    if ($workorder_id > 0)
//    {
//        echo "<table align=center><tr>";
//
//        submit_cells('UPDATE_ITEM', _("Update"), '', _('Save changes to work order'), 'default');
//        if (get_post('released'))
//        {
//            submit_cells('close', _("Close This Work Order"),'','',true);
//        }
//        submit_cells('delete', _("Delete This Work Order"),'','',true);
//
//        echo "</tr></table>";
//    }
//    else
//    {
//        submit_center('ADD_ITEM', _("Add Workorder"), true, '', 'default');
//    }
    
    if ($workorder_id != -1) {
        br();
        submit_center_first('Update_WO_Manual', _("Manual Update (No Scheduling)"), '', 'default');
        br(2);
        submit_center_first('Update_WO_Forward', _("Update - Forward"), '', 'default');
        submit('Update_WO_Forward_Inline', _("Update - Forward Inline"), true, '', 'default');
        //submit_center_last('Update_WO_Forward_Priority', _("Update - Forward Priority"), '', 'default');
        br(2);
        submit_center_first('Update_WO_Backward', _("Update - Backward"), '', 'default');
        submit_center_last('Close_WO', _("Close"), _("Close"), '');
    }
    else
    {
        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');
    }
}



function build_workorder_array($work_order_no, $schedule_method, &$wo)
{   
        $wo['wo_id'] = $work_order_no;
        $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'] = $_POST['type'];
        $wo['wo_stock_id'] = $_POST['stock_id'];
        $wo['wo_labour'] = get_post('Labour');
        $wo['wo_costs'] = get_post('Costs');
        $wo['wo_comment'] = $_POST['memo_'];
        $wo['wo_row_state'] = get_post('row_state');
        $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');   

        if($work_order_no > 0){
            $wo['bom_factor'] = 1;
        }
        else{
            $bom_header = get_bom_header($_POST['stock_id']);
            $bom_qty = $bom_header['quantity'];
            $wo_qty = $wo['wo_tran_qty'] * $wo['wo_cf'];
            $wo['bom_factor'] = $wo_qty/$bom_qty;
        }
        
        $wo['wo_scheduling_days_limit'] = get_workcentre_scheduling_days_limit();
        $wo['wo_update_process_timings'] = $_POST['update_process_timings'];
 
    
}

function save_workorder($work_order_id, $schedule_method)
{
    build_workorder_array($work_order_id, $schedule_method, $wo);
    
    $ccwo = can_commit_workorder($wo);
    if($ccwo['success'] !== true){
        if(isset($ccwo['focus_to'])){
            set_focus($ccwo['focus_to']);
        }
        return $ccwo;
    }
    if($wo['wo_id'] == -1){
        $cwo = create_workorder($wo);
        if($cwo['success'] === true){
            new_doc_date($_POST['date_']);
            meta_forward($_SERVER['PHP_SELF'], "AddedID=".$cwo['tran_no']."&type=".$wo['wo_type']."&date=".sql2date($wo['wo_start_date_time']));
        }
        else{
            return $cwo;
        }
    }
    else{
        $ewo = edit_work_order($wo);
        if($ewo['success'] === true){
            new_doc_date($_POST['date_']);
            meta_forward($_SERVER['PHP_SELF'], "UpdatedID=".$wo['wo_id']);  
        }
        else{
            return $ewo;
        }
    }
    
}


function close_wo($woid)
{
    
    //$wo_remaining_cost = get_work_order_remaining_total_cost($woid);
    
    $woh = get_work_order_header($woid);
    
    $allocation_removing_summary = array();
    add_to_task_cost($allocation_removing_summary, $woh['task_id'], 0, 0, 0);
    get_task_cost_details($allocation_removing_summary);
    $current_user_id = $_SESSION['wa_current_user']->user;

    $cwo_msg = close_work_order($woid, $allocation_removing_summary, $current_user_id);
    if($cwo_msg['success'] !== true){
        cancel_transaction();
    }
        
    return $cwo_msg;
    
}

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


if(isset($_POST['Add_WO_Forward'])){
    $swo_msg = save_workorder($workorder_id, WOSM_FORWARD_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_Inline'])){
    $swo_msg = save_workorder($workorder_id, WOSM_FORWARD_INLINE_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_Priority'])){
    $swo_msg = save_workorder($workorder_id, WOSM_FORWARD_PRIORITY_MANUAL, true);   
    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, WOSM_BACKWARD_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_Manual'])){
    $swo_msg = save_workorder($workorder_id, 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['Update_WO_Forward'])){
    $swo_msg = save_workorder($workorder_id, WOSM_FORWARD_MANUAL, false);   
    if($swo_msg['success'] === true){
        $Mode = '';
        $selected_id = -1;
        display_notification("Workorder $workorder_id has been updated");
    }
    else{
        display_error($swo_msg['message']);
        set_focus($swo_msg['focus_to']);
    }
}

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

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

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


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

if(isset($_POST['Close_WO'])){
    
    $cwo_msg = close_wo($workorder_id);
    if($cwo_msg['success'] !== true){
        display_error($cwo_msg['message']);
    }
    else{
        meta_forward($_SERVER['PHP_SELF'], "ClosedID=$workorder_id");
    }
}

//if ($Mode == 'Delete')
//{
//    //$process_id = substr($selected_id,8);
//    
//    $dwop = delete_workorder_process($workorder_id, $selected_id);
//    if($dwop['success'] === true){
//        $selected_id = -1;
//        $Mode = 'RESET';
//         meta_forward($_SERVER['PHP_SELF'], "DeletedID=$workorder_id");
//    }
//    else{
//        display_error($dwop['message']);
//    }
//}


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

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


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

//if (isset($_POST['ADD_ITEM']) && can_process($workorder_id))
//{
//	create_workorder($workorder_id);
//}

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

//if (isset($_POST['UPDATE_ITEM']) && can_process($workorder_id))
//{
////    edit_work_order($workorder_id);
//}

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

//if (isset($_POST['delete']))
//{
//	//the link to delete a selected record was clicked instead of the submit button
//
//	$cancel_delete = false;
//
//	// can't delete it there are productions or issues
//	if (work_order_has_productions($workorder_id) ||
//		work_order_has_issues($workorder_id)	||
//		work_order_has_payments($workorder_id))
//	{
//		display_error(_("This work order cannot be deleted because it has already been processed."));
//		$cancel_delete = true;
//	}
//
//	if ($cancel_delete == false)
//	{ //ie not cancelled the delete as a result of above tests
//
//		// delete the actual work order
//		delete_work_order($workorder_id);
//		meta_forward($_SERVER['PHP_SELF'], "DeletedID=$workorder_id");
//	}
//}

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

//if (isset($_POST['close']))
//{
//
//	// update the closed flag in the work order
//	$cwo_msg = close_work_order($workorder_id);
//    if($cwo_msg['success'] !== true){
//        display_error($cwo_msg['message']);
//    }
//    else{    
//        meta_forward($_SERVER['PHP_SELF'], "ClosedID=$workorder_id");
//    }
//}

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

start_form();

if ($workorder_id != -1){
    $work_order = get_work_order_header($workorder_id);
        
    $project_id = $work_order['project_id'];    
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($project_id, $user_id);
    if($cap['success'] !== true) 
    {
        display_error($cap["message"]);
        set_focus('project_id');
        display_footer_exit();
        exit;
    }
}
else{
    $work_order = null;
}

$Ajax->activate('task_id');
    
display_wo_header($workorder_id, $work_order);
//end_form();

//start_form();
display_workorder_tabs($workorder_id, $work_order, $path_to_root);

//general_settings($selected_id);

end_form();
end_page();

?>