<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_MANUFISSUE';
$path_to_root = "..";
include_once($path_to_root . "/includes/ui/items_cart.inc");

include_once($path_to_root . "/includes/session.inc");

include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/data_checks.inc");

include_once($path_to_root . "/includes/project_cost_functions.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/work_order_pr_ui.inc");

include_once($path_to_root . "/inventory/includes/lots_validation.inc");
include_once($path_to_root . "/inventory/includes/serial_no_validation.inc");

include_once($path_to_root . "/purchasing/includes/pr_validations.inc");
include_once($path_to_root . "/projects/includes/db/projects_db.inc");

$js = "";
if ($SysPrefs->use_popup_windows)
	$js .= get_js_open_window(800, 500);
if (user_use_date_picker())
	$js .= get_js_date_picker();
page(_($help_context = "Purchase Request Items for Work Order"), false, false, "", $js);

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

if (isset($_GET['AddedID'])) 
{
	$id = $_GET['AddedID'];
   	display_notification(_("Purchase Requisition $id has been created."));

    display_note(get_trans_view_str(ST_PURCH_REQ, $id, _("View this Purchase Requisition")));

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

	display_footer_exit();
}


if (isset($_GET['ClosedID'])) 
{
	$id = $_GET['ClosedID'];
   	display_notification(_("Work order $id has been closed for purchasing."));

//    display_note(get_trans_view_str(ST_PURCH_REQ, $id, _("View this Purchase Requisition")));
//
//   	hyperlink_no_params("search_work_orders.php", _("Select another &Work Order to Process"));

	display_footer_exit();
}

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

function line_start_focus() {
  global 	$Ajax;

  $Ajax->activate('items_table');
  set_focus('_stock_id_edit');
}

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

function handle_new_order()
{
	if (isset($_SESSION['issue_items']))
	{
		$_SESSION['issue_items']->clear_items();
		unset ($_SESSION['issue_items']);
	}

     $_SESSION['issue_items'] = new items_cart(ST_MANUISSUE);
     $_SESSION['issue_items']->order_id = $_GET['trans_no'];
     
     populate_cart_from_workorder($_SESSION['issue_items']);
}

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

function populate_cart_from_workorder(&$order)
{
    $woh = get_work_order_header($order->order_id);
    
    $wop = get_wo_processes($order->order_id);	
	while ($process = db_fetch($wop)){
        $wopm = get_wo_process_material($process['id']);
        while ($item = db_fetch($wopm)) 
        {
            add_to_issue($order, $item['stock_id'], $item['units_req'], $item['req_unit'], $item['req_unit_qty'], 
                        $item['req_unit_conversion_factor']);
            
            $line_no = count($order->line_items) - 1;
            
            $_POST['line_ref'] = $order->get_line_ref();
            set_line_ref($order, $line_no);
            
            $order->line_items[$line_no]->row_id = $item['id'];
            
            $order->line_items[$line_no]->req_unit = $item['req_unit'];
            $order->line_items[$line_no]->req_unit_qty = $item['req_unit_qty'];
            $order->line_items[$line_no]->req_unit_conversion_factor = $item['req_unit_conversion_factor'];
            $order->line_items[$line_no]->units_issued = $item['units_issued'] / $order->line_items[$line_no]->req_unit_conversion_factor;
            
            $order->line_items[$line_no]->stock_control_method = $item['stock_control_method'];
            
            $order->line_items[$line_no]->loc_code = $item['loc_code'];
            $order->line_items[$line_no]->location_name = $item['location_name'];
            
            $order->line_items[$line_no]->material_line_id = $item['id'];
            
            $order->line_items[$line_no]->process_id = $process['id'];
            $order->line_items[$line_no]->process = $process['sequence']."-".$process['description'];
            
            $remaining_issue_qty = ($order->line_items[$line_no]->req_unit_qty - $order->line_items[$line_no]->units_issued) / $order->line_items[$line_no]->req_unit_conversion_factor;
            if($remaining_issue_qty < 0){
                $remaining_issue_qty = 0;
            }
            
            $order->line_items[$line_no]->tran_qty =  $remaining_issue_qty;
            
            $order->line_items[$line_no]->qty_ordered = $item['qty_ordered'];
            
            $order->line_items[$line_no]->required_date = sql2date($woh['date_']);
            $order->line_items[$line_no]->price = $item['standard_cost'];
        }
    }
    
}
//-----------------------------------------------------------------------------------------------

function can_process()
{
	global $Refs;

    if (!(strlen($_POST['pr_location']) > 0))
    {
        display_error(_("Please select a location."));
		set_focus('pr_location');
		return false;
    }
    
	if (!is_date($_POST['date_'])) 
	{
		display_error(_("The entered date for the issue is invalid."));
		set_focus('date_');
		return false;
	} 
	elseif (!is_date_in_fiscalyear($_POST['date_'])) 
	{
		display_error(_("The entered date is not in fiscal year."));
		set_focus('date_');
		return false;
	}
    
	if (!$Refs->is_valid($_POST['ref'])) 
	{
		display_error(_("You must enter a reference."));
		set_focus('ref');
		return false;
	}

	if (!is_new_reference($_POST['ref'], ST_MANUISSUE)) 
	{
		display_error(_("The entered reference is already in use."));
		set_focus('ref');
		return false;
	}

    if ($_POST['project_id'] == -1)
    {
        display_error(_("Please select a project."));
		set_focus('project_id');
		return false;
    }
    
    if ($_POST['task_id'] == -1)
    {
        display_error(_("Please select a task."));
		set_focus('task_id');
		return false;
    }
    
//	$failed_item = $_SESSION['issue_items']->check_qoh($_POST['Location'], $_POST['date_'], !$_POST['IssueType']);
//	if ($failed_item != -1) 
//	{
//    	display_error( _("The issue cannot be processed because an entered item would cause a negative inventory balance :") .
//    		" " . $failed_item->stock_id . " - " .  $failed_item->item_description);
//		return false;
//	}

//    $vtqd_msg = validate_transaction_quantity_details($_SESSION['issue_items']);
//    if ($vtqd_msg['success'] !== true) 
//    {
//        display_error($vtqd_msg['message']);
//        return false;
//    }
//    

    
	return true;
}


//function save_workorder_issue()
//{
//    $awoi = add_work_order_issue($_SESSION['issue_items']->order_id,
//                                $_POST['ref'], $_POST['IssueType'], $_SESSION['issue_items']->line_items,
//                                '', 0, $_POST['date_'], $_POST['memo_'], $_POST['project_id'], $_POST['task_id']);
//
//	if ($awoi['success'] != true) 
//	{
////		display_error(_("The process cannot be completed because there is an insufficient total quantity for a component.") . "<br>"
////		. _("Component is :"). $failed_data[0] . "<br>"
////		. _("From location :"). $failed_data[1] . "<br>");
//        display_error($awoi['message']);
//	} 
//	else 
//	{
//		meta_forward($_SERVER['PHP_SELF'], "AddedID=".$_SESSION['issue_items']->order_id);
//	}
//}
//

function create_pr_for_wo($close = false)
{
    
    $_SESSION['pr_for_wo'] = new items_cart(ST_MANUISSUE);
    $pr_wo = &$_SESSION['pr_for_wo'];
    $wo_issue = $_SESSION['issue_items'];
    
    $trans_no = $wo_issue->order_id;
    //$pfm->order_id = $trans_no;
    
    $pr_wo->order_id = 0;
    $pr_wo->release = false;
//    $pr_wo->pr_reference = get_next_reference_for_auto_generation(ST_PURCH_REQ);
    $pr_wo->pr_reference = $_POST['ref'];
    $pr_wo->requesting_location = $_POST["pr_location"];
    
    // Do not allow PR issues for this PR
    $pr_wo->pr_complete = 1;
    $pr_wo->project_id = $_POST["project_id"];
    $pr_wo->pr_date = $_POST["date_"];
    $pr_wo->next_approval_group_id = $wo_issue->next_approval_group_id;
    //$pfm->total = $im_cart->total;
    $pr_wo->approval_status = AS_NEW;
    
    $pr_wo->source_type = ST_WORKORDER;
    $pr_wo->source_order_id = $wo_issue->order_id;
    
    $count = 0;
    $total = 0;
    
    foreach ($wo_issue->line_items as $line_item)
    {
        if(isset($_POST[$line_item->row_id."_check_wo_pr_item"])){
            if(isset($_POST[$line_item->row_id."_qty"]) && input_num($line_item->row_id."_qty") > 0){
                $pr_wo_unit_qty = input_num($line_item->row_id."_qty");
                $pr_wo->line_items[] = $line_item;
                
                $pr_wo->line_items[$count]->required_date = $_POST[$line_item->row_id."_item_required_date"];
                $pr_wo->line_items[$count]->quantity = $pr_wo_unit_qty * $line_item->convertion_factor;
                $pr_wo->line_items[$count]->tran_qty = $pr_wo_unit_qty;

                $pr_wo->line_items[$count]->task_id = $_POST["task_id"];
                $pr_wo->line_items[$count]->project_site_id = 0 ;
                
                $itm = get_item_edit_info($pr_wo->line_items[$count]->stock_id) ;
                $pr_wo->line_items[$count]->project_site_id = $itm["standard_cost"] ;

                $total += $pr_wo->line_items[$count]->quantity;// * $line_item->price;
                
                $count = $count + 1;

                
            }
        }
    }
   
    $pr_wo->total = $total;
    
    if($count == 0){
        display_error("No items selected or no quantities entered for selected items.");
        return;
    }
        
//        add_pr($mr_data_array, $_SESSION['pr_from_im']->line_items); 
        
    $vpid = validate_pr_item_data($_SESSION['pr_for_wo']);
    
    if($vpid["success"] !== true){
        display_error($vpid["message"]);  
        set_focus($vpid["focus_to"]);
        return;
    }
    else{
        if($vpid["message"] == "close_only"){
            display_error("No need to create a purchase requistion. This MR is to be closed");  
            return;
        }
        else{
            begin_transaction();
            $apr_msg = add_pr($_SESSION['pr_for_wo']);
            if($apr_msg['success'] !== true){
                //cancel_transaction();
                cancel_transaction();
                display_error($apr_msg['message']);
            }
            else{
                $pr_no = $apr_msg['tran_no'];
                if($close){
                    close_work_order_for_prs($wo_issue->order_id);
                }
                commit_transaction();
                new_doc_date($_SESSION['pr_for_wo']->pr_date);
                $_SESSION['pr_for_wo']->clear_items();
                unset($_SESSION['pr_for_wo']);
                //set_session_variable('pr_for_wo_messages', $apr_msg["message"]);
                //commit_transaction();
//                end_processing($pr_no, ST_PURCH_REQ);
                meta_forward($_SERVER['PHP_SELF'], "AddedID=$pr_no");
                
            }
        }
    }
}



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

function check_item_data()
{

    if (!($_POST['process_id'] > 0))
	{
		display_error(_("Please select a process."));
		set_focus('process_id');
		return false;
	}
    
    	if ($_POST['stock_id'] == '')
	{
		display_error(_("Please select an item."));
		set_focus('stock_id');
		return false;
	}

	if ($_POST['loc_code'] == '')
	{
		display_error(_("Please select a location."));
		set_focus('loc_code');
		return false;
	}

    if (!check_num('tran_qty', 0.01))
	{
		display_error(_("The quantity entered is negative or invalid."));
		set_focus('qty');
		return false;
	}
    
   	return true;
}

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

function handle_update_item()
{
    if(!check_item_data($_SESSION['issue_items'])){
        $_POST['Edit'.get_post('LineNo')] = 1;
        return;
    }
    
    if($_POST['UpdateItem'] != "")
    {
        $id_edit = $_POST['LineNo'];
        $order = &$_SESSION['issue_items'];
        
        $standard_cost = $order->line_items[$id_edit]->standard_cost;
        
        $tran_unit = $_POST['tran_unit'];
        $convesion_factor = 1;
        get_convertion_factor2($order->line_items[$id_edit]->stock_id, $tran_unit, $convesion_factor);
        
        $order->update_cart_item($id_edit, input_num('tran_qty')*$convesion_factor, $standard_cost, 
                null, null, null, null, null, input_num('tran_qty'), $tran_unit, $convesion_factor);
        
        $order->line_items[$id_edit]->loc_code = $_POST['loc_code'];
        $location_name = get_location_name($order->line_items[$id_edit]->loc_code);
        $order->line_items[$id_edit]->location_name = $location_name;
            
        $lot_details = get_selected_lot_serial_info('guid', $order->line_items[$id_edit]); 

        $order->line_items[$id_edit]->lot_details = $lot_details;
    
        unset($_POST['Edit'.$id_edit]);
    
        line_start_focus();
    }
	
}

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

function handle_delete_item($id)
{
	$_SESSION['issue_items']->remove_from_cart($id);
	line_start_focus();
}

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

function handle_new_item()
{
	if (!check_item_data()){
		return;
    }

    $order = &$_SESSION['issue_items'];
    
    $item_info = get_item_edit_info($_POST['stock_id']);
    $alternate_unit = get_alternate_unit_details($_POST['tran_unit']);
    $convertion_factor = $alternate_unit['convertion_factor'];
    $tran_unit = $alternate_unit['alternate_unit'];
        
	add_to_issue($order, $_POST['stock_id'], input_num('qty'), $tran_unit, input_num('tran_qty'), 
                        $convertion_factor);
    
    $line_no = count($order->line_items) - 1;
            
    $order->line_items[$line_no]->stock_control_method = $item_info['stock_control_method'];
    
    $order->line_items[$line_no]->loc_code = $_POST['loc_code'];
    $location_name = get_location_name($order->line_items[$line_no]->loc_code);
    $order->line_items[$line_no]->location_name = $location_name;
                      
    $order->line_items[$line_no]->process_id = $_POST['process_id'];
    $process = get_wo_process($order->line_items[$line_no]->process_id);
    $order->line_items[$line_no]->process = $process['sequence']."-".$process['description'];
    
    set_line_ref($order, $line_no);
    $lot_details = get_selected_lot_serial_info('guid', $order->line_items[$line_no]); 
    
    if(isset($lot_details) && $lot_details != ""){
        $order->line_items[$line_no]->lot_details = $lot_details;    
    }

            
	line_start_focus();
}

if (isset($_POST['Create_PR_For_WO']) && can_process())
{

    create_pr_for_wo();

} 

if (isset($_POST['Create_PR_For_WO_Close']) && can_process())
{

    create_pr_for_wo(true);

} 

if (isset($_POST['Close_WO_For_PRs']))
{
    $wo_no = $_SESSION['issue_items']->order_id;
    close_work_order_for_prs($wo_no);
    
    $_SESSION['issue_items']->clear_items();
    unset($_SESSION['issue_items']);
    meta_forward($_SERVER['PHP_SELF'], "ClosedID=$wo_no");
                
} 


//-----------------------------------------------------------------------------------------------
$id = find_submit('Delete');
if ($id != -1)
	handle_delete_item($id);

if (isset($_POST['AddItem']))
	handle_new_item();

if (isset($_POST['UpdateItem']))
	handle_update_item();

if (isset($_POST['CancelItemChanges'])) {
	line_start_focus();
}

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

if (isset($_GET['trans_no']))
{
	handle_new_order();
}

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

display_wo_details($_SESSION['issue_items']->order_id);
echo "<br>";

start_form();
hidden("guid",substr(md5(microtime()),rand(0,26),15));

start_table(TABLESTYLE, "width=90%", 10);
echo "<tr><td>";
display_wo_pr_items(_("Items to Order"), $_SESSION['issue_items']);
wo_pr_options_controls($_SESSION['issue_items']->order_id);
echo "</td></tr>";

end_table();

br();
submit_center_first('Create_PR_For_WO', _("Create PR"), '', 'default');
submit('Create_PR_For_WO_Close', _("Create PR & Close"), true, '', 'default');
br(2);
submit_center_first('Close_WO_For_PRs', _("Close WO for PRs"), '', 'default');
end_form();

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

end_page();

?>
