<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_MATERIAL_REQ_TRANSFER';
$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 . "/inventory/includes/material_requisition_pr_ui.inc");
include_once($path_to_root . "/inventory/includes/mr_validations.inc");
include_once($path_to_root . "/inventory/includes/db/issue_materials_db.inc");
include_once($path_to_root . "/inventory/includes/db/material_requisitions_db.inc");
include_once($path_to_root . "/reporting/includes/reporting.inc");
include_once($path_to_root . "/includes/project_cost_functions.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 . "/inventory/includes/db/serial_no_adjustments_db.inc");
include_once($path_to_root . "/inventory/includes/db/serial_no_db.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 for Material Requitions"), false, false, "", $js);

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

check_db_has_costable_items(_("There are no inventory items defined in the system which can be adjusted (Purchased or Manufactured)."));

check_db_has_movement_types(_("There are no inventory movement types defined in the system. Please define at least one inventory adjustment type."));

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

if (isset($_GET['Added_MI_ID'])) 
{
	//return;
        
    $trans_no = $_GET['Added_MI_ID'];
	$trans_type = ST_MATERIAL_ISSUE;
    $message = get_session_variable('mr_pr_messages');
    clear_session_variable('mr_pr_messages');
    
	display_notification_centered($message);

	hyperlink_no_params("$path_to_root/inventory/inquiry/material_requisitions_inquiry.php", _("Process &Another Material Requisition"));

	hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$trans_no");
    
//    display_note(print_document_link($trans_no, _("&Print This Material Issue"), true, $trans_type), 0, 0);

	display_footer_exit();
}

if (isset($_GET['Added_PR_ID'])) 
{
	//return;
        
    $pr_no = $_GET['Added_PR_ID'];
	$trans_type = ST_PURCH_REQ;

	$message = get_session_variable('mr_pr_messages');
    clear_session_variable('mr_pr_messages');
    
	display_notification_centered($message);
        
	display_note(print_document_link($pr_no, _("&Print this purchase requisition"), true, $trans_type), 0, 0);

	//hyperlink_no_params("$path_to_root/inventory/inquiry/material_requisitions_inquiry.php.php", _("Process &Another Material Requisition"));

	//hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$trans_no");

	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['mr_items']))
	{
		$_SESSION['mr_items']->clear_items();
		unset ($_SESSION['mr_items']);
	}

        $_SESSION['mr_items'] = new items_cart(ST_MATERIAL_ISSUE);
        
        populate_cart_from_database();
	
}

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

function populate_cart_from_database()
{
        $myrow = get_material_requisition($_GET['mr_no']);
        
        $im_cart = $_SESSION['mr_items'];

        $im_cart->order_id = $myrow["mr_no"];
        $im_cart->reference = $myrow["reference"];
        $im_cart->issuing_location  = $myrow["issuing_location"];
        $im_cart->issuing_location_name  = $myrow["issuing_location_name"];
        $im_cart->receiving_location  = $myrow["issuing_location"];
        $im_cart->receiving_location_name  = $myrow["issuing_location_name"];
        $im_cart->required_date  = $myrow["mr_required_date"];
        $im_cart->memo_  = $myrow["comments"];
        $im_cart->requestor_name  = $myrow["requestor_name"];
        $im_cart->movement_type  = $myrow["movement_type"];
        $im_cart->movement_type_name  = $myrow["movement_type_name"];
        $im_cart->linked_field_type = $myrow["linked_field_type"];
        $im_cart->linked_field_id  = $myrow["linked_field_id"];
        $im_cart->created_on  = $myrow["created_on"];
        $im_cart->project_description  = $myrow["project_description"];
        $im_cart->approval_path_description  = $myrow["approval_path_description"];
        $im_cart->mr_complete  = $myrow["mr_complete"];
        $im_cart->project_id  = $myrow["project_id"];
        //        $im_cart->approval_path_id  = $myrow["approval_path_id"];
        $im_cart->approval_status  = $myrow["approval_status"];
        $im_cart->pr_no  = $myrow["pr_no"];
        $im_cart->row_state  = $myrow["row_state"];
  
        $im_details = get_mr_details($im_cart->order_id);

        $element_no = 0;
        while ($imtd_row = db_fetch($im_details)) 
        {
            $im_line = new line_item($imtd_row["stock_id"], 0, $imtd_row["standard_cost"], 
                    $imtd_row["description"],sql2date($imtd_row["required_date"]), $imtd_row["line_comment"],$myrow["comments"],
                    $imtd_row["id"], $imtd_row["issued_qty"], $imtd_row["requested_qty"], 0, $imtd_row["price"], null, 0, 
                    null, null, null, null, null, $imtd_row["requested_unit"], $imtd_row["requested_unit_qty"], 
                    $imtd_row["req_unit_conv_factor"]);

            $im_line->row_id = $imtd_row["id"];
            $im_line->high_value_item = $imtd_row["high_value_item"];
            $im_line->sample_item = $imtd_row["sample_item"];
            $im_line->reference_cost = $imtd_row["reference_cost"];
            $im_line->stock_control_method = $imtd_row["stock_control_method"];
            $im_line->pr_line_id = $imtd_row["pr_line_id"];
            $im_line->task_id = $imtd_row["task_id"];
            $im_line->task_description = $imtd_row["task_description"];
            $im_line->project_site_id = $imtd_row["project_site_id"];
            $im_line->project_site_description = $imtd_row["project_site_description"];
            $im_line->ordered_qty = $imtd_row["ordered_qty"];
            $im_line->line_ref = $im_line->row_id;
                                    
            $im_cart->line_items[$element_no] = $im_line;
            $element_no++;
        }

}

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


//function can_process_issue_materials()
//{
//	global $Refs, $approval_statuses;
//
//    $total_qty = 0;
//
//    if(!($_SESSION['mr_items']->approval_status == AS_APPROVED || $_SESSION['mr_items']->approval_status == AS_ISSUED))
//    {
//        $a = AS_APPROVED;
//        $i = AS_ISSUED;
//        display_error("Material can be issued when the status is $approval_statuses[$a] or $approval_statuses[$i] only.");
//        return false;
//    }
//    
//	foreach ($_SESSION['mr_items']->line_items as $line_item)
//    {
//        if (isset($_POST[$line_item->row_id.'_check_mr_item']) && $_POST[$line_item->row_id.'_check_mr_item'] == true)
//        {
//            if (!check_num($line_item->row_id.'_tran_qty',0))
//            {
//                display_error(_("The quantity entered for item [".$line_item->stock_id."] is negative or invalid."));
//                set_focus($line_item->row_id."_tran_qty");
//                return false;
//            }
//            if(!(isset($line_item->task_id) && $line_item->task_id > 0)){
//                display_error("No task selected for the item [".$line_item->stock_id."]");
//                set_focus($line_item->row_id."_tran_qty");
//                return false;
//            }
//            
//            $line_item->check_issue_item = true;
//            
//            $total_qty += $_POST[$line_item->row_id."_tran_qty"];
//        }
//        else{
//            $line_item->check_issue_item = false;
//        }
//    }     
//
//    if($total_qty == 0){ 
//        if($_POST['mr_complete'] == 1){
//            return "close_only";
//        }
//        else{
//            display_error(_("No lines with valid quantities selected."));
//            set_focus($line_item->row_id."_tran_qty");
//            return false;
//        }
//
//    }
//    
//    if (strlen($_POST['im_reference']) == 0) 
//	{
//		display_error( _("You must enter a reference."));
//		set_focus('im_reference');
//		return false;
//	}
//
//    if (!$Refs->is_valid($_POST['im_reference'])) 
//	{
//		display_error( _("Entered reference already exists."));
//		set_focus('im_reference');
//		return false;
//	}
//
//    foreach ($_SESSION['mr_items']->line_items as $line_item) {		
//	            		
//        if($_POST[$line_item->row_id.'_tran_qty'] > $line_item->requested_qty + $line_item->issued_qty)		
//        {		
//            display_error(_("Issuing quantity can not be greater than the sum of requested quantity and issued quantity."));		
//            set_focus($line_item->row_id.'_tran_qty');		
//            return false;		
//        }		
//	}
//    
//    
//    $vtqd_msg = validate_transaction_quantity_details($_SESSION['mr_items']);		
//    if ($vtqd_msg['success'] !== true) 		
//    {
//        display_error($vtqd_msg['message']);
//        return false;
//    }
//
//        
//    return true;
//}

function add_lot_details()
{
    if(!isset($_SESSION['lot_info#'.ST_MATERIAL_ISSUE])){
        return;
    }
    
    $lot_info_array =  $_SESSION['lot_info#'.ST_MATERIAL_ISSUE];

    foreach ($_SESSION['mr_items']->line_items as $line_item) {
       	if($line_item->stock_control_method != SKCM_NORMAL){
            $line_item->lot_details = $lot_info_array[$line_item->stock_id] ;
        } 
    }    
}    
//-------------------------------------------------------------------------------

function update_cart()
{
    foreach ($_SESSION['mr_items']->line_items as $line_item)
    {

        
        $tran_unit_convertion = get_convertion_factor($_POST[$line_item->row_id."_tran_unit"], $line_item->stock_id);
        if($tran_unit_convertion == false){
            $tran_unit_convertion_factor = 1;
            $item = get_item($line_item->stock_id);
            $issued_unit = $item['units'];
        }
        else{
            $tran_unit_convertion_factor = $tran_unit_convertion['convertion_factor'];
            $issued_unit = $_POST[$line_item->row_id."_tran_unit"];
        }
        $line_item->convertion_factor = $tran_unit_convertion_factor;
        
        $line_item->tran_qty = input_num($line_item->row_id."_tran_qty");
        $line_item->tran_unit = $issued_unit;
        
        
//        $line_item->quantity = $line_item->tran_qty * $line_item->convertion_factor;
        
//        $item_info = get_stock_item_edit_info($line_item->stock_id);
//
////        $adj = &$_SESSION['mr_items'];
////        $current_element = (count($adj->line_items)-1);
////        $adj->line_items[$current_element]->requested_qty = $_POST['qty'];
//        
//        $line_item->high_value_item = $item_info["high_value_item"];
//        $line_item->sample_item = $item_info["sample_item"];
//        $line_item->reference_cost = $item_info["reference_cost"];
//        $line_item->stock_control_method = $item_info["stock_control_method"];
        
        $lot_details = get_selected_lot_serial_info('guid', $line_item);
        $line_item->lot_details = $lot_details;    
        
        
        if($_POST[$line_item->row_id."_project_site_id"] > 0){
            $line_item->project_site_id = $_POST[$line_item->row_id."_project_site_id"];
        }
        else{
             $line_item->project_site_id = 0;
        }
    }
}

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

function end_processing($trans_no, $type = ST_MATERIAL_ISSUE)
{
        //return;
 	$_SESSION['mr_items']->clear_items();
        //return;
	unset($_SESSION['mr_items']);        
    unset($_SESSION[ST_MATERIAL_ISSUE]);   
    
    if($type == ST_MATERIAL_ISSUE){
        meta_forward($_SERVER['PHP_SELF'], "Added_MI_ID=$trans_no");
    }
    elseif($type == ST_PURCH_REQ){
        meta_forward($_SERVER['PHP_SELF'], "Added_PR_ID=$trans_no");
    }
}

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

function close_mr_for_purchasing($mr_no){
        close_mr_for_prs($mr_no);

        set_session_variable('mr_pr_messages', "Material requisition ".$mr_no." has been closed for purchasing");
        end_processing($mr_no); 
        
}

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


//if (isset($_POST['Process']))
//{
//    //add_lot_details();
//    
//    update_cart();
//    
//    $result = can_process_issue_materials();
//    
//    if($result === "close_only")
//    {
//         close_material_requisition($_SESSION['mr_items']->order_id);     
//    }
//    elseif($result == true)  
//    {
//        $aim_msg = add_issue_materials($_SESSION['mr_items']->line_items, $_POST['im_reference'], $_POST['issuing_location'], 
//                                        $_POST['receiving_location'], $_SESSION['mr_items']->project_id, $_POST['memo_'], 
//                                        $_SESSION['mr_items']->order_id, $_SESSION['mr_items']->row_state, get_post('mr_complete'));
//                
//        if($aim_msg['success'] !== true){
//            display_error("Could not add material issue");
//        }
//        else{
//            set_session_variable('im_messages', $aim_msg['message']);
//            end_processing($aim_msg['tran_no']);
//        }
//        
//        //meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
//      
//    }
//
//} 



function create_pr_cart_from_mr()
{
    update_cart();
    
    $_SESSION['pr_from_mr'] = new items_cart(ST_MATERIAL_ISSUE);
    $pfm = &$_SESSION['pr_from_mr'];
    $im_cart = $_SESSION['mr_items'];
    
    $trans_no = $im_cart->order_id;
    //$pfm->order_id = $trans_no;
    
    $pfm->order_id = 0;
    $pfm->release = false;
    $pfm->pr_reference = get_post('im_reference');
    $pfm->requesting_location = $im_cart->issuing_location;
    
    // Do not allow PR issues for this PR
    $pfm->pr_complete = 1;
    $pfm->project_id = $im_cart->project_id;
    $pfm->pr_date = sql2date($im_cart->required_date);
    $pfm->next_approval_group_id = $im_cart->next_approval_group_id;
    //$pfm->total = $im_cart->total;
    $pfm->approval_status = AS_NEW;
    
    $pfm->source_type = ST_MATERIAL_REQ;
    $pfm->source_order_id = $im_cart->order_id;
    
    $count = 0;
    $total = 0;
    
    foreach ($im_cart->line_items as $line_item)
    {
        if (isset($_POST[$line_item->row_id.'_check_mr_item']) && $_POST[$line_item->row_id.'_check_mr_item'] == true)
        {
            if($line_item->tran_qty > 0){
                $pfm->line_items[] = $line_item;

                $pfm->line_items[$count]->quantity = $line_item->tran_qty * $line_item->convertion_factor;
//                $pfm->line_items[$count]->tran_qty = $line_item->tran_qty;

                $pfm->line_items[$count]->task_id = $line_item->task_id ;
                $pfm->line_items[$count]->project_site_id = $line_item->project_site_id ;

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

            }
        }
    }
   
    $pfm->total = $total;
    
    if($count == 0){
        $message = ("No items with valid quantities selected.");
        display_error($message); 
        return array("success"=>false, "message"=>$message );
    }
        
//        add_pr($mr_data_array, $_SESSION['pr_from_im']->line_items); 
        
    $vpid = validate_pr_item_data($_SESSION['pr_from_mr']);
    
    if($vpid["success"] !== true){
        display_error($vpid["message"]);  
        set_focus($vpid["focus_to"]);
        return $vpid;
    }
    else{
        if($vpid["message"] == "close_only"){
            $message = ("No need to create a purchase requistion. This MR is to be closed");  
            display_error($message); 
            return array("success"=>false, "message"=>$message );
        }
    }
    
    return array("success"=>true, "message"=>"" );
}


function create_pr_from_mr()
{
    $cprfmr = create_pr_cart_from_mr();
    if($cprfmr["success"] !== true){
        if(isset($cprfmr["focus_to"])){
            set_focus($cprfmr["focus_to"]);
        }
        return $cprfmr;
    }
    
    begin_transaction();
    $apr_msg = add_pr($_SESSION['pr_from_mr']);
    if($apr_msg['success'] !== true){
        //cancel_transaction();
        cancel_transaction();
        display_error($apr_msg['message']);
    }
    else{
        $pr_no = $apr_msg['tran_no'];
        commit_transaction();
        new_doc_date($_SESSION['pr_from_mr']->pr_date);
        $_SESSION['pr_from_mr']->clear_items();
        unset($_SESSION['pr_from_mr']);
        set_session_variable('mr_pr_messages', $apr_msg["message"]);
        //commit_transaction();
        end_processing($pr_no, ST_PURCH_REQ);
        //meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
    }
}

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

function create_pr_from_mr_close_mr($mr_no)
{
    $cprfmr = create_pr_cart_from_mr();
    if($cprfmr["success"] !== true){
        if (isset($cprfmr["focus_to"])) {
            set_focus($cprfmr["focus_to"]);
        }
        return $cprfmr;
    }
    
    begin_transaction();
    $apr_msg = add_pr($_SESSION['pr_from_mr']);
    if($apr_msg['success'] !== true){
        //cancel_transaction();
        cancel_transaction();
        display_error($apr_msg['message']);
    }
    else{
        $pr_no = $apr_msg['tran_no'];
        commit_transaction();
        
        close_mr_for_prs($mr_no);
        
        new_doc_date($_SESSION['pr_from_mr']->pr_date);
        $_SESSION['pr_from_mr']->clear_items();
        unset($_SESSION['pr_from_mr']);
        set_session_variable('mr_pr_messages', $apr_msg["message"]." MR ".$mr_no." has been closed for purchasing.");
        //commit_transaction();
        end_processing($pr_no, ST_PURCH_REQ);
        //meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
    }
}
//-----------------------------------------------------------------------------------------------

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

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

//function handle_update_item()
//{
////    if($_POST['UpdateItem'] != "")
////    {
////		$id = $_POST['LineNo'];
////        $adj = &$_SESSION['mr_items'];        
////        
////        $item_info = get_stock_item_edit_info($adj->line_items[$id]->stock_id);
////        if($item_info["stock_control_method"] == 1){
////          $a = "lot_info#".$adj->line_items[$id]->guid;  
////          $lot_details = get_session_variable($a)[$_POST['stock_id']];  
////        }
////        if(isset($lot_details) && $lot_details != ""){
////            $adj->line_items[$id]->lot_details = $lot_details;    
////        }
////    }
//	line_start_focus();
//}

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

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

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

//function handle_new_item()
//{
//	if (!check_item_data())
//		return;
//
//    $item_info = get_stock_item_edit_info($_POST['stock_id']);
//    
//	add_mio_to_cart($_SESSION['mr_items'], $_POST['stock_id'],input_num('qty'), 
//                                $_POST['required_date'], $_POST['line_commnet']);
//    
//    $adj = &$_SESSION['mr_items'];
//    
//    $current_element = (count($adj->line_items)-1);
//    $adj->line_items[$current_element]->requested_qty = $_POST['qty'];
//    $adj->line_items[$current_element]->high_value_item = $item_info["high_value_item"];
//    $adj->line_items[$current_element]->sample_item = $item_info["sample_item"];
//    $adj->line_items[$current_element]->reference_cost = $item_info["reference_cost"];
//    
//	line_start_focus();
//}

//-----------------------------------------------------------------------------------------------
//$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['NewAdjustment']) || !isset($_SESSION['mio_items']))
//{
//	handle_new_order();
//}

if (isset($_POST['Create_PR'])){
    create_pr_from_mr();
}

if (isset($_POST['Create_PR_Close_MR'])){
    create_pr_from_mr_close_mr($_SESSION['mr_items']->order_id);
}

if(isset($_POST['Close_MR'])){
    close_mr_for_purchasing($_SESSION['mr_items']->order_id);
}

if (isset($_GET['mr_no']) && $_GET['mr_no'] > 0) 
{
    if(!isset($_SESSION['mr_items']))
    {
        handle_new_order();
    }
    
    if($_GET['mr_no'] != $_SESSION['mr_items']->order_id)
    {
        handle_new_order();
    }
}
//-----------------------------------------------------------------------------------------------
start_form();

$guid = ST_MATERIAL_ISSUE;
$_POST['guid'] = $guid;
hidden("guid",$guid);

display_material_requisition_pr_header($_SESSION['mr_items']);

start_outer_table(TABLESTYLE, "width=80%", 10);

display_material_requisition_pr_items(_("Material Requisition Items"), $_SESSION['mr_items']);
material_requisition_pr_option_controls();

end_outer_table(1, false);

//submit_center_first('Update', _("Update"), '', null);
submit_center_first('Create_PR', _("Create PR"), '', 'default');

submit('Create_PR_Close_MR', 'Create PR & Close MR', true, '', 'default');

submit_center_last('Close_MR', 'Close MR for Purchasing', '', 'default');

end_form();
end_page();

?>
