<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_PURCHASE_REQUISITION_ISSUES';
$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 . "/purchasing/includes/ui/pr_issues_ui.inc");
include_once($path_to_root . "/purchasing/includes/ui/po_ui.inc");
include_once($path_to_root . "/purchasing/includes/pr_validations.inc");
include_once($path_to_root . "/purchasing/includes/db/pr_issues_db.inc");
include_once($path_to_root . "/purchasing/includes/db/purchase_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 . "/projects/includes/db/projects_db.inc");
include_once($path_to_root . "/assets/includes/db/assets_db.inc");

include_once($path_to_root . "/includes/ui/ui_lists_group_companies.inc");
include_once($path_to_root . "/includes/db/group_companies_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 = "PR Issues"), 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['AddedId'])) 
{
	//return;
        
        $trans_no = $_GET['AddedId'];
	$trans_type = ST_PR_ISSUE;

	display_notification_centered(_("PR Issue ".$trans_no." has been created"));
        
        display_note(get_supplier_trans_view_str($trans_type, $trans_no, _("View this PR Issue")), 1);         

	hyperlink_no_params("$path_to_root/purchasing/inquiry/purchase_requisition_inquiry.php", _("Process &Another Purchase Requisition")); 

	display_footer_exit();
}

if (isset($_GET['AddCloseId'])) 
{
	//return;
        
        $trans_no = $_GET['AddCloseId'];
	$trans_type = ST_PR_ISSUE;

	display_notification_centered(_("PR Issue ".$trans_no." has been created and the source Purchase Requisition has been closed"));
        
        display_note(get_supplier_trans_view_str($trans_type, $trans_no, _("View this PR Issue")), 1);         

	hyperlink_no_params("$path_to_root/purchasing/inquiry/purchase_requisition_inquiry.php", _("Process &Another Purchase Requisition")); 

	display_footer_exit();
}

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

	display_notification_centered(_("Purchase Requisition ".$trans_no." has been closed"));
        
        display_note(get_supplier_trans_view_str($trans_type, $trans_no, _("View this Purchase Requisition")), 1);         

	hyperlink_no_params("$path_to_root/purchasing/inquiry/purchase_requisition_inquiry.php", _("Process &Another Purchase Requisition")); 

	display_footer_exit();
}
//--------------------------------------------------------------------------------------------------

function line_start_focus() {
  global 	$Ajax;

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

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

        $_SESSION['pr_items'] = new items_cart(ST_PURCH_REQ);        
        
        $pr_no = $_GET['pr_no'];
        populate_pr_cart_from_database('pr_items', $pr_no, $po_no);
	
}

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

function get_po_details_array(&$pod_array, $pr_no, $po_no)
{
    $query = get_po_details_for_pr_issues($pr_no, $po_no);
    while ($myrow = db_fetch($query)) 
    {
        $a = array(
                "prd_id" => $myrow["prd_id"],
                "requisition_id" => $myrow["requisition_id"],
                "item_code" => $myrow["item_code"],
                "po_line_id" => $myrow["po_line_id"],
                "order_unit_qty" => $myrow["order_unit_qty"],
                "order_unit_conv_factor" => $myrow["order_unit_conv_factor"],
                "order_unit_price" => $myrow["order_unit_price"],
                "order_unit_price_discount" => $myrow["order_unit_price_discount"],
                "unit_price" => $myrow["unit_price"],
                "quantity_received" => $myrow["quantity_received"],
                "quantity_ordered" => $myrow["quantity_ordered"],
                "po_no" => $myrow["po_no"]);

        $pod_array[] = $a;
    }
}

function get_pr_issue_po_item_details($pod_array, $pr_line_id, &$can_issue, &$po_quantity, &$po_unit_cost, &$po_quantity_received)
{
    $po_quantity = $po_unit_cost = $po_quantity_received = 0;
    $can_issue =  false;
    
    foreach ($pod_array as $line) {
        if($line['prd_id'] == $pr_line_id){
            $po_quantity = $line['quantity_ordered'];
            $po_unit_cost = $line['unit_price'];
            $po_quantity_received = $line['quantity_received'];
            $can_issue =  true;
            return;
        }
    }
}



function get_pr_item_calculated_charging_cost($prd_row, $estimated_unit_price)
{
    $values = array();
    
    $pr_allocated_price_row = get_pr_alloc_max_price($prd_row["id"]);
    if(isset($pr_allocated_price_row['id']) && $pr_allocated_price_row['id'] > 0){
        $values['charging_cost'] = $pr_allocated_price_row['alloc_price'];
        $values['cost_source'] = "PR Allocation #".$pr_allocated_price_row['id'];
        return $values;
    }
    
    $grn_price_row = get_grn_max_unit_price($prd_row["item_code"], $prd_row["description"]);        
    if(isset($grn_price_row['id']) && $grn_price_row['id'] > 0){
        $values['charging_cost'] = $grn_price_row['unit_cost'];
        $values['cost_source'] = "GRN line #".$grn_price_row['id'];
        return $values;
    }
    
    if($prd_row["mb_flag"] == "M" OR "P"){
        if(!$prd_row["descr_editable"]){
            $values['charging_cost'] = get_standard_cost($prd_row["item_code"]);
            $values['cost_source'] = "Item average cost";
            return $values;
        }
    }
    
    $values['charging_cost'] = $estimated_unit_price;
    $values['cost_source'] = "Estiamted price";
    return $values;

}
//-----------------------------------------------------------------------------------------------

function can_process()
{
    $issuing_location = $_POST['issuing_location'];
    $pri_reference = $_POST['pri_reference'];
    $pri_date_ = $_POST['pri_date'];
    $movement_type = $_POST['movement_type'];
    $linked_field_id = $_POST['linked_field_id'];
    
    $ccpri_msg = can_commit_pr_issue($issuing_location, $pri_reference, $pri_date_, $movement_type, $linked_field_id);
    
    if($ccpri_msg['success'] !== true){
        display_error($ccpri_msg['message']);        
        return false;
    }else{
        return true;
    }
}

//function can_process_1111111111()
//{
//	global $Refs;
//    
//    $total_qty = 0;
//    if(!(isset($_SESSION['pr_items']->po_no) && $_SESSION['pr_items']->po_no > 0))// No PO
//    {
//        if(!$_SESSION["wa_current_user"]->can_access('SA_PR_ISSUES_WITHOUT_POS')){ // No access to issue without a PO
//            display_error("You are not allowed to issue items without a purchase order.");
//            return false;
//        }
//    }
//    
//    if(!($_SESSION['pr_items']->approval_status == AS_APPROVED || $_SESSION['pr_items']->approval_status == AS_ISSUED))
//    {
//        display_error("Status of this Purchase Requisition does not allow item issues.");
//        return false;
//    }
//    
//    if($_SESSION['pr_items']->pr_complete == 1)
//    {
//        display_error("This Purchase Requisition has been generated from a Material Requisition or a Sales Order. No material issuing allowed from this Purchase Requisition.");
//        return false;
//    }
//    
//    if (!$_POST['issuing_location'] > 0) 
//    {
//            display_error( _("Please select an issuing location."));
//            set_focus('issuing_location');
//            return false;
//    }
//    
//    if (!$Refs->is_valid($_POST['pri_reference'])) 
//    {
//            display_error( _("You must enter a reference."));
//            set_focus('pri_reference');
//            return false;
//    }
//        
//    $ref_msg = reference_exists($_POST['pri_reference'], ST_PR_ISSUE);
//    if($ref_msg){
//        display_error($ref_msg);
//        set_focus('pri_reference');
//        return false;
//    }
//    
//    if (!(is_date($_POST['pri_date']))) 
//    {
//            display_error( _("Entered date is not a valid date."));
//            set_focus('pri_date');
//            return false;
//    }
//    
//    if (! ($_POST['movement_type'] > 0)) {
//        $input_error = 1;
//        display_error( _('Select a movement type.'));
//        set_focus('movement_type');
//        return false;
//    } else {
//        $mv_tp = get_movement_type($_POST['movement_type']);
//            if ($mv_tp['linked_field'] != IMLF_NOT_LINKED) {
//
//                global $inventory_movement_type_linked_fields;
//
//                if ($mv_tp['linked_field'] == IMLF_EMPLOYEE && ($_POST['linked_field_id'] == 0)) {
//                    $input_error = 1;
//                    display_error( _('Select an '.$inventory_movement_type_linked_fields[$mv_tp['linked_field']].'.'));
//                    set_focus('linked_field_id');
//                    return false;
//                } elseif ($mv_tp['linked_field'] == IMLF_ASSET && ! ($_POST['linked_field_id'] > 0)) {
//                    $input_error = 1;
//                    display_error( _('Select an '.$inventory_movement_type_linked_fields[$mv_tp['linked_field']].'.'));
//                    set_focus('linked_field_id');
//                    return false;
//                } elseif (! ($_POST['linked_field_id'] > 0)) {
//                    $input_error = 1;
//                    display_error( _('Select a '.$inventory_movement_type_linked_fields[$mv_tp['linked_field']].'.'));
//                    set_focus('linked_field_id');
//                    return false;
//                }
//
//                if ($mv_tp['linked_field'] == IMLF_ASSET) {
//                    $asset_row = get_asset($_POST['linked_field_id']);
//                        if ($asset_row['type'] == AT_VEHICLE) {
//                            display_error("Selected asset is a Vehicle. Only the assets of types Fixed Asset and Tool are allowed under this Movement Type.");
//                            set_focus('linked_field_id');
//                            return false;
//                        }
//                }
//            }
//    }
//    
//    foreach ($_SESSION['pr_items']->line_items as $line_item)
//    {
//        $prefix = $line_item->row_id."_".$line_item->pr_po_line_id."_".$line_item->po_line_id;
//        
//        if (!check_num($prefix.'_tran_qty',0))
//        {
//            display_error(_("Line Id ".$line_item->row_id." : quantity entered for item [".$line_item->stock_id."] is negative or invalid."));
//            set_focus($prefix."_tran_qty");
//            return false;
//        }
//        $total_qty += $_POST[$prefix."_tran_qty"];
//
//    } 
//        
//        
//    if(!(isset($_SESSION['pr_items']->po_no) && $_SESSION['pr_items']->po_no > 0)){// No PO
//        // Validate for over quantity when there is no PO
//        foreach ($_SESSION['pr_items']->line_items as $line_item) 
//        {
//            if($line_item->item_selected == false){
//                continue;
//            }
//
//            $prefix = $line_item->row_id."_".$line_item->pr_po_line_id."_".$line_item->po_line_id;
//        
//    //        $alternate_unit = get_convertion_factor($_POST[$prefix."_tran_unit"], $line_item->stock_id);
//    //        $convesion_factor = 1;
//    //        $alternate_unit = $_POST[$prefix."_tran_unit"];
//    //        get_convertion_factor2($line_item->stock_id, $alternate_unit, $convesion_factor);
//
//            $tran_unit = $line_item->tran_unit;
//    //        $pr_line = get_pr_detail_record($line_item->row_id);
//            $total_issued_qty = get_pr_item_total_issued_qty($line_item->row_id);
//            $base_unit_issued_qty = $total_issued_qty;
//            get_convertion_factor2($line_item->stock_id, $tran_unit, $tran_unit_convesion_factor);
//            $tran_unit_issued_qty = $base_unit_issued_qty / $tran_unit_convesion_factor;
//
//            $base_unit_issuing_qty = $line_item->quantity;
//            $tran_unit_issuing_qty = $line_item->tran_qty;
//
//    //        $tran_unit_requested_qty = $line_item->requested_qty / $line_item->convertion_factor;
//            $tran_unit_requested_qty = $line_item->requested_qty / $tran_unit_convesion_factor;
//    //        if($base_unit_issuing_qty + $base_unit_issued_qty > $line_item->requested_qty + 0.0000001)
//            if($tran_unit_issued_qty + $tran_unit_issuing_qty > $tran_unit_requested_qty + 0.0000001)
//            {
//                display_error(_("Line Id ".$line_item->row_id  
//                        ." - Item ".$line_item->stock_id." - ".$line_item->item_description
//                        ."<br> Issuing Unit : ". get_unit_descr($line_item->tran_unit) 
//                        .", Issuing quantity (".number_format($tran_unit_issuing_qty, 3)
//                        .") + already issued qty (".number_format($tran_unit_issued_qty, 3)
//                        .") can not be greater than the requested quantity (".number_format($tran_unit_requested_qty,3).")."));
//                set_focus($line_item->row_id.'_tran_qty');
//                return false;
//            }
//        }
//    } 
//    
//    $vtqd_msg = validate_transaction_quantity_details($_SESSION['pr_items']);		
//    if ($vtqd_msg['success'] !== true) 		
//    {
//        display_error($vtqd_msg['message']);
//        return false;
//    }
//    
//	return true;
//}

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


function can_close_purchase_requisition()
{

    $approval_status = $_SESSION['pr_items']->approval_status;
    if(!($approval_status == AS_APPROVED || $approval_status == AS_ISSUED))
    {
        display_error("Status of this Purchase Requisition does not allow closing it.");
        return false;
    }
    
    if($_SESSION['pr_items']->pr_complete == 1)
    {
        display_error("This Purchase Requisition has been generated from a Material Requisition. No material issuing allowed from this Purchase Requisition.");
        return false;
    }
    
    return true;
    
}

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

function update_cart()
{
    $count =0;
    
    foreach ($_SESSION['pr_items']->line_items as &$line_item)
    {
        $prefix = $line_item->row_id."_".$line_item->pr_po_line_id."_".$line_item->po_line_id;
        
        if(isset($_POST[$prefix.'_check_pr_issue_item']) && $_POST[$prefix.'_check_pr_issue_item'] == true){
            $alternate_unit = get_convertion_factor($_POST[$prefix."_tran_unit"], $line_item->stock_id);
            if($alternate_unit == false){
                $convertion_factor = 1;
                $item = get_item($line_item->stock_id);
                $issued_unit = $item['units'];
            }
            else{
                $convertion_factor = $alternate_unit['convertion_factor'];
                $issued_unit = $_POST[$prefix."_tran_unit"];
            }    

            $lot_details = get_selected_lot_serial_info('guid', $line_item);   
            $line_item->lot_details = $lot_details;    


            $line_item->quantity = input_num($prefix."_tran_qty")*$convertion_factor;
            $line_item->tran_unit = $issued_unit;
            $line_item->tran_qty = input_num($prefix."_tran_qty");
            $line_item->tran_unit_conv_factor = $convertion_factor;
            $line_item->project_site_id = $_POST[$prefix."_project_site_id"];    
            
            if($line_item->quantity > 0){
                $line_item->item_selected = true;
                $count++;
            }
            else{
                $line_item->item_selected = false;
            }
        }
        else{
            $line_item->item_selected = false;
        }
    }

    if($count == 0){
        display_error("No items with quantities selected");
        return false;
    }
    else{
        return true;
    }    
}
//-------------------------------------------------------------------------------

function end_processing($trans_no, $id_name="AddedId")
{
        //return;
 	$_SESSION['pr_items']->clear_items();
        //return;
	unset($_SESSION['pr_items']);  
        unset($_SESSION[ST_PURCH_REQ]); 
        
   	meta_forward($_SERVER['PHP_SELF'], "$id_name=$trans_no");
}

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

function close_purchase_requisition($pr_no){
        if(!can_close_purchase_requisition()){
            return;
        }
        
        $cpr_msg = close_pr($pr_no, AS_CLOSED);
        if($cpr_msg['success'] !== true){
            display_error($cpr_msg['message']);
        }
        else{
//            set_session_variable('im_messages', "Purchase requisition ".$pr_no." has been closed");
            end_processing($pr_no, "ClosedId"); 
        }
}


function process_pr_issue($close_pr = false)
{    
    $result = can_process();
    
    if(!$result){
        return;
    }
    
    $api_msg = add_pr_issue($_SESSION['pr_items']->line_items, $_POST['pri_reference'], $_SESSION['pr_items']->requesting_location,  
                            $_POST['issuing_location'], $_SESSION['pr_items']->project_id, $_POST['memo_'], $_POST['pri_date'],
                            $_SESSION['pr_items']->order_id, $close_pr, $_SESSION['pr_items']->row_state, $_SESSION['pr_items']->po_no,
                            $_POST['movement_type'], $_POST['linked_field_type'], $_POST['linked_field_id'], $_POST['group_company_code'],
                            $_POST['employee_code'], $_POST['employee_company_code']);
                
	//new_doc_date($_POST['mio_date']);
    if($api_msg['success'] !== true){
        display_error($api_msg['message']);
    }
    else{
        //set_session_variable('pri_messages', $api_msg['message']);
        if($close_pr == true){
            end_processing($api_msg['tran_no'], "AddCloseId");
        }else{
            end_processing($api_msg['tran_no'], "AddedId");            
        }
    }
//        end_processing($trans_no);
        
        //meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
      
    

}


//-------------------------------------------------------------------------------
if(isset($_POST['Close_PR_Only'])){
    close_purchase_requisition($_SESSION['pr_items']->order_id);
}


if (isset($_POST['Create_PRI_Close_PR']))
{
    if(update_cart()){
        process_pr_issue(true);
    }

}

if (isset($_POST['Create_PRI']))
{
    if(update_cart()){
        process_pr_issue();
    }

}

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

function check_item_data()
{
	if (!check_num('qty',0))
	{
		display_error(_("The quantity entered is negative or invalid."));
		set_focus('qty');
		return false;
	}
        
	if (input_num('qty') == 0)
	{
		display_error(_("The quantity entered has to be greater than zero."));
		set_focus('qty');
		return false;
	}
   	return true;
}

start_form();

$po_no = 0;
if (isset($_GET['po_no']) && $_GET['po_no'] > 0) 
{ 
    $_POST['po_no'] = $_GET['po_no'];
}
if (isset($_POST['po_no']) && $_POST['po_no'] > 0) 
{ 
    hidden('po_no',$_POST['po_no']);
    $po_no = $_POST['po_no'];
}

if (isset($_GET['pr_no']) && $_GET['pr_no'] > 0) 
{
    if(!isset($_SESSION['pr_items']))
    {
        handle_new_order($po_no);
    }
    if(!isset($_SESSION['pr_items']->order_id))// Session variable available but not the class details
    {
        unset($_SESSION['pr_items']);
        handle_new_order($po_no);
    }
    
    if($_GET['pr_no'] != $_SESSION['pr_items']->order_id || $po_no != $_SESSION['pr_items']->po_no )
    {
        handle_new_order($po_no);
    }
}


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


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

display_purchase_requisition_header($_SESSION['pr_items'], $po_no);

start_outer_table(TABLESTYLE, "width=96%", 2);

display_purchase_requisition_items(_("Purchase Requisition Items"), $_SESSION['pr_items'], $po_no);
pr_options_controls();

end_outer_table(1, false);

//submit_center_first('Update', _("Update"), '', null);
submit_center_first('Create_PRI', _("Process PR Issue"), 'Issue items (system will automatically complete PR if all quantities issued)', 'default');
submit_center_last('Create_PRI_Close_PR', _("Process PR Issue & Close PR"), 'Issue selected quantities and close PR', 'default');

br();
submit_center('Close_PR_Only', 'Close PR (No Item Issues)', true, 'Close PR without issuing items', 'default');

end_form();

br();

end_page();

?>
