<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_PURCHASE_REQUISITION';
$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/approval_functions.inc");
include_once($path_to_root . "/includes/project_cost_functions.inc");
include_once($path_to_root . "/purchasing/includes/purchase_requisitions_ui.inc");
include_once($path_to_root . "/purchasing/includes/db/purchase_requisitions_db.inc");
include_once($path_to_root . "/purchasing/includes/pr_validations.inc");
include_once($path_to_root . "/projects/includes/db/project_sites_db.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 Requisition"), 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['NewRequisition']))
{
    if(isset($_SESSION['pr_items'])){
        $_SESSION['pr_items']->clear_items();
        unset ($_SESSION['pr_items']);
        clear_data();
        set_focus('requesting_location');
        $Ajax->activate('_page_body');
    }
}   

if (isset($_GET['AddedID'])) 
{
	//return;
        
    $trans_no = $_GET['AddedID'];
	$trans_type = ST_PURCH_REQ;
        
    $msg = get_session_variable('pr_messages');

    display_notification(_($msg));
        
	//display_notification_centered(_("Purchase Requisition has been saved"));
	display_note(get_trans_view_str($trans_type, $trans_no, _("&View this Purchase Requisition")));
    
    hyperlink_params("$path_to_root/purchasing/purchase_requisitions.php", _("Edit this Purchase Requisition"), "ModifyPrNumber=$trans_no");

	hyperlink_no_params($_SERVER['PHP_SELF'], _("Enter &Another Purchase Requisition"));

	hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$trans_no");
        
    clear_session_variable('pr_messages');
        
	display_footer_exit();
}
//--------------------------------------------------------------------------------------------------
if (get_post('cancel')) {
    
    unset ($_SESSION['pr_items']);
    
    if(isset($_SESSION['pr_items'])){
        $_SESSION['pr_items']->clear_items();
        unset ($_SESSION['pr_items']);
    }
    clear_data();
	set_focus('requesting_location');
	$Ajax->activate('_page_body');
}

function clear_data()
{
    unset ($_POST['requesting_location']);
    unset ($_POST['project_id']);
    unset ($_POST['pr_reference']);
    unset ($_POST['pr_date']);

    
}
function line_start_focus() {
  global 	$Ajax;

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

if (isset($_GET['ModifyPrNumber']) && is_numeric($_GET['ModifyPrNumber'])) 
{
    $help_context = 'Modifying Purchase Requisition';
    $_SESSION['page_title'] = sprintf( _("Modifying Purchase Requisition # %d"), $_GET['ModifyPrNumber']);
    
    	if (isset($_SESSION['pr_items']))
	{
		//$_SESSION['pr_items']->clear_items();
		unset ($_SESSION['pr_items']);
	}

    $_SESSION['pr_items'] = new items_cart(ST_PURCH_REQ);
    
    populate_cart($_GET['ModifyPrNumber']);
}
function populate_cart($pr_no)
{
        $myrow = get_pr_header($pr_no);
        
        $pr_cart = $_SESSION['pr_items'];
        
        $pr_cart->order_id = $myrow["pr_no"];
        $pr_cart->requesting_location = $myrow["location"];
        $pr_cart->reference = $myrow["reference"];
        $pr_cart->job_reference = $myrow["project_description"];
        $pr_cart->project_id = $myrow["project_id"];
        $pr_cart->pr_date = $myrow["pr_date"];
        $pr_cart->required_date = $myrow["pr_date"];
        $pr_cart->pr_complete = $myrow["pr_complete"];
        $pr_cart->approval_status = $myrow["approval_status"];
        $pr_cart->requestor_name = $myrow["requestor_name"];
        $pr_cart->next_approval_group_id  = $myrow["next_approval_group_id"];
        $pr_cart->created_by  = $myrow["created_by"];
        $pr_cart->row_state  = $myrow["row_state"];
        $pr_cart->source_type  = $myrow["source_type"];
        $pr_cart->source_order_id = $myrow["source_order_id"];
  
        $pr_details = get_pr_details($pr_no);

        $element_no = 0;
        while ($prd_row = db_fetch($pr_details)) 
        {
            $pr_line = new line_item($prd_row["item_code"], 0, $standard_cost=null, 
                    $prd_row['item_pr_description'],sql2date($prd_row["required_date"]), $prd_row["line_comment"],
                    $comment=null, $prd_row["id"], $prd_row["issued_qty"], $prd_row["quantity"], 0, 0, null, 0, 
                    null, null, null, null, null, $prd_row["requested_unit"], $prd_row["requested_unit_qty"], 
                    $prd_row["req_unit_conv_factor"]);

            $pr_line->row_id = $prd_row["id"];
//            $pr_line->line_complete = $prd_row["line_complete"];
            $pr_line->created_by = $prd_row["created_by"];
            $pr_line->created_on = $prd_row["created_on"];
            $pr_line->category_id = $prd_row["category_id"];
//            $pr_line->po_line_id = $prd_row["po_line_id"];
//            $pr_line->order_quantity = $prd_row["order_quantity"];
//            $pr_line->order_price = $prd_row["order_price"];
//            $pr_line->supplier_id = $prd_row["supplier_id"];
            $pr_line->estimate_price = $prd_row["estimate_price"];
            $pr_line->task_id = $prd_row["task_id"];
            $pr_line->task_description  = $prd_row["task_description"];
            $pr_line->project_site_id = $prd_row["project_site_id"];
            $pr_line->project_site_description = $prd_row["project_site_description"];
            $pr_line->quantity_ordered = $prd_row["quantity_ordered"];
            $pr_line->descr_editable = $prd_row["descr_editable"];

            $pr_cart->line_items[$element_no] = $pr_line;
            $element_no++;
        }

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

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

        $_SESSION['pr_items'] = new items_cart(ST_PURCH_REQ);
        $_SESSION['pr_items']->next_approval_group_id = 0;
        $_SESSION['pr_items']->approval_status = 0;
        $_SESSION['pr_items']->source_type = 0;
        $_SESSION['pr_items']->source_order_id = 0;
	
}

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

function copy_to_pr_cart(&$pr_cart)
{
        $pr_cart->release = false;
        $pr_cart->pr_reference = get_post('pr_reference');
        $pr_cart->requesting_location = $_POST['requesting_location'];
        $pr_cart->project_id = $_POST['project_id'];
        $pr_cart->task_id = $_POST['task_id'];
        $pr_cart->pr_date = $_POST['pr_date'];
        if(isset($_POST['Add_Release']) || isset($_POST['Release'])){
            $pr_cart->release = true;            
        }
        
         if($pr_cart->source_type > 0){
             // No change. It is the same saved value when PR is generated from the source transaction
         }
         else{
            if ($_POST['purchase_to_stock']) {
                $_SESSION['pr_items']->pr_complete = 1;
            } else {
                $_SESSION['pr_items']->pr_complete = 0;
            }
         }
            
//        $pr_cart->next_approval_group_id = $pr_cart->next_approval_group_id;
//        $pr_cart->total = $pr_cart->total;
//        $pr_cart->approval_status = $pr_cart->approval_status;
        
}

function close_purchase_requisition()
{
        close_pr($_SESSION['pr_items']->order_id);
        
        $trans_no = $_SESSION['pr_items']->order_id;
        new_doc_date($_POST['pr_date']);
        $_SESSION['pr_items']->clear_items();
        unset($_SESSION['pr_items']);
        $text = "Purchase requistion $trans_no has been closed.";
        set_session_variable('pr_messages', $text);
        
        meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
}

if (isset($_POST['Update_PR'])){
        
    copy_to_pr_cart($_SESSION['pr_items']);
    $vpid = validate_pr_item_data($_SESSION['pr_items']);
    
    if($vpid["success"] !== true){
        display_error($vpid["message"]);  
        set_focus($vpid["focus_to"]);
    }
    else{
        if($vpid["message"] == "close_only"){
            close_purchase_requisition();     
        }
        else{

            $upr_msg = update_pr($_SESSION['pr_items']);

            if($upr_msg['success'] !== true){
                cancel_transaction();
                display_error("Could not update the purchase requisition. ".$upr_msg['message']);
            }
            else{
                end_processing($upr_msg);
            }
        }
    }
//   	meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
} 


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

if (isset($_POST['Update_Release'])){

    copy_to_pr_cart($_SESSION['pr_items']); 
    $vpid = validate_pr_item_data($_SESSION['pr_items']);
    if($vpid["success"] !== true){
        display_error($vpid["message"]);  
        set_focus($vpid["focus_to"]);
    }
    else{
        if($vpid["message"] == "close_only"){
            close_purchase_requisition();     
        }
        else{

            $upr_msg = update_pr($_SESSION['pr_items'], true);

            if($upr_msg['success'] !== true){
                cancel_transaction();
                display_error("Could not update the purchase requisition. ".$upr_msg['message']);
            }
            else{
                end_processing($upr_msg);
            }
        }
    }
//   	meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
} 


if (isset($_POST['Add_PR'])){
    
    copy_to_pr_cart($_SESSION['pr_items']);
    
    $purchase_to_stock = null;
    $project = get_project_record($_SESSION['pr_items']->project_id);
    if (isset($project['purchase_to_stock'])) {
        $purchase_to_stock = $project['purchase_to_stock'];
    }
    if($purchase_to_stock || $_SESSION['pr_items']->purchase_to_stock){
        $_SESSION['pr_items']->pr_complete = 1;
    }
    else{
        $_SESSION['pr_items']->pr_complete = 0;
    }
    
    $vpid = validate_pr_item_data($_SESSION['pr_items']);
        if($vpid["success"] !== true){
        display_error($vpid["message"]);  
        set_focus($vpid["focus_to"]);
    }
    else{
        if($vpid["message"] == "close_only"){
            display_error("No need to save this requisition.It is to be completed"); 
        }
        else{

            $apr_msg = add_pr($_SESSION['pr_items']);
            if($apr_msg['success'] !== true){
                cancel_transaction();
                display_error($apr_msg['message']);
                //set_session_variable('pr_messages', );
            }
            else{
                end_processing($apr_msg);
            }
        }
    }
} 


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

if (isset($_POST['Add_Release'])){

    copy_to_pr_cart($_SESSION['pr_items']);
    
    $purchase_to_stock = null;
    $project = get_project_record($_SESSION['pr_items']->project_id);
    if (isset($project['purchase_to_stock'])) {
        $purchase_to_stock = $project['purchase_to_stock'];
    }
    if($purchase_to_stock || $_SESSION['pr_items']->purchase_to_stock){
        $_SESSION['pr_items']->pr_complete = 1;
    }
    else{
        $_SESSION['pr_items']->pr_complete = 0;
    }
    
    $vpid = validate_pr_item_data($_SESSION['pr_items']);
    if($vpid["success"] !== true){
        display_error($vpid["message"]);  
        set_focus($vpid["focus_to"]);
    }
    else{
        if($vpid["message"] == "close_only"){
            display_error("No need to create a purchase requistion. This MR is to be closed");  
        }
        else{

            $apr_msg = add_pr($_SESSION['pr_items'], true);
            if($apr_msg['success'] !== true){
                cancel_transaction();
                display_error($apr_msg['message']);
            }
            else{
                //commit_transaction();
                $release = $_SESSION['pr_items']->release;
                $trans_no = $apr_msg['tran_no'];
                new_doc_date($_POST['pr_date']);
                $_SESSION['pr_items']->clear_items();
                unset($_SESSION['pr_items']);
                if($release == true){
                    set_session_variable('pr_messages', $apr_msg['message']);
                }
                else{
                    $text = $apr_msg['tran_no'];
                    set_session_variable('pr_messages', $text);
                }
                //
                meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
            }
        }
    }
        

} 


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

function reject_pr()
{
    $pr = $_SESSION['pr_items'];
    
    $vpid = validate_pr_item_data($pr);
    if($vpid["success"] !== true){
        display_error($vpid["message"]);  
        set_focus($vpid["focus_to"]);
        return;
    }
    
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rd_msg = reject_document($pr->trans_type, $pr->order_id, $pr->project_id,
                    $pr->next_approval_group_id, $current_user_id, $pr->row_state);
    
    if($rd_msg['success'] !== true){
        cancel_transaction();
        display_error($rd_msg['message']);
    }
    else{
        $trans_no = $rd_msg['tran_no'];
        new_doc_date($_POST['pr_date']);
        $_SESSION['pr_items']->clear_items();
        unset($_SESSION['pr_items']);
        set_session_variable('pr_messages', "Purchase requisition ".$rd_msg['tran_no']." has been rejected.");
        
        meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
    }

}


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

function send_pr_back_to_originator()
{
    $pr = $_SESSION['pr_items'];
    
    $vpid = validate_pr_item_data($pr);
    if($vpid["success"] !== true){
        display_error($vpid["message"]);  
        set_focus($vpid["focus_to"]);
        return;
    }

    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rd_msg = send_back_to_document_originator($pr->trans_type, $pr->order_id, $pr->project_id,
                                    $pr->next_approval_group_id, $current_user_id, $pr->row_state, 
                                    $pr->created_by);
    
    if($rd_msg['success'] !== true){
        cancel_transaction();
        display_error($rd_msg['message']);
    }
    else{
        $trans_no = $rd_msg['tran_no'];
        new_doc_date($_POST['pr_date']);
        $_SESSION['pr_items']->clear_items();
        unset($_SESSION['pr_items']);
        set_session_variable('pr_messages', $rd_msg['message']);
        
        meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
    }

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

if (isset($_POST['Back_To_Originator'])){

    send_pr_back_to_originator();
        
} 


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

if (isset($_POST['Reject_PR'])){

    reject_pr();
        
} 


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


function end_processing($pr_msg)
{
    $release = $_SESSION['pr_items']->release;
//    $trans_no = $_SESSION['pr_items']->order_id;
    $trans_no = $pr_msg['tran_no'];
    
    new_doc_date($_POST['pr_date']);
    $_SESSION['pr_items']->clear_items();
    unset($_SESSION['pr_items']);
    if($release == true){
        set_session_variable('pr_messages', $pr_msg['message']);
    }
    else{
        $text = $pr_msg['message'];
        set_session_variable('pr_messages', $text);
    }
    meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
}

function check_item_data()
{
    if (!(strlen($_POST['stock_id']) > 0)) 
    {
            display_error(_("Please select an item."));
            set_focus('stock_id');
            return false;
    } 
    
    if (!check_num('tran_qty',0.0000001))
    {
            display_error(_("The quantity entered is negative or invalid."));
            set_focus('qty');
            return false;
    }
        
    if (!check_num('estimate_price',0))
	{
		display_error(_("The price entered is negative or invalid."));
		set_focus('estimate_price');
		return false;
	}
    
    if (input_num('estimate_price') == 0)
	{
		display_error(_("The price entered has to be greater than zero."));
		set_focus('estimate_price');
		return false;
	}
        
    if (!is_date($_POST['required_date'])) 
	{
		display_error(_("The entered date for the required date is invalid."));
		set_focus('required_date');
		return false;
	} 
	
    if (!($_POST['task_id'] > 0)) 
	{
		display_error(_("Please select a budget."));
		set_focus('task_id');
		return false;
	} 
    
//    if (!is_date_in_fiscalyear($_POST['required_date'])) 
//	{
//		display_error(_("Entered date is not in fiscal year."));
//		set_focus('required_date');
//		return false;
//	} 
   	return true;
}

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

function handle_update_item()
{
    if($_POST['UpdateItem'] != "" && check_item_data())
    {
        $id_edit = $_POST['LineNo'];
        $adj = &$_SESSION['pr_items'];
        
        $standard_cost = $adj->line_items[$id_edit]->standard_cost;
        
        $tran_unit = $adj->line_items[$id_edit]->tran_unit;
        get_convertion_factor2($_POST['stock_id'], $tran_unit, $convertion_factor);
//        $_POST['tran_unit'] = $tran_unit;
        $adj->line_items[$id_edit]->convertion_factor = $convertion_factor;
            
        $tran_unit_estaimted_price = input_num('estimate_price');
        
    	$adj->update_cart_item($id_edit, input_num('tran_qty')*$convertion_factor, null, 
                null, $_POST['line_comment'], $_POST['required_date'], input_num('tran_qty')*$convertion_factor,
                $tran_unit_estaimted_price, input_num('tran_qty'), $tran_unit, $convertion_factor);

        //$_SESSION['pr_items']->line_items[$id]->stock_category_id = $_POST['stock_category_id'];
        $_SESSION['pr_items']->line_items[$id_edit]->stock_category_id = 0;
        //$_SESSION['pr_items']->line_items[$id]->estimate_price = $_POST['estimate_price'];
        
        $adj->line_items[$id_edit]->item_description = $_POST["item_description"];
        
        $task_id = 0;
        $task_description = '';
        if($_POST['task_id'] != -1){
            $project_task = get_task_details($_POST['task_id']);
            $task_id = $project_task['task_id'];
            $task_description = $project_task['description'];
        }
        $adj->line_items[$id_edit]->task_id = $task_id;
        $adj->line_items[$id_edit]->task_description = $task_description;

        $project_site_id = 0;
        $project_site_description = '';
        if($_POST['project_site_id'] != -1){
            $project_site = get_project_site_details($_POST['project_site_id']);
            $project_site_id = $project_site['id'];
            $project_site_description = $project_site['description'];
        }
        $adj->line_items[$id_edit]->project_site_id = $project_site_id;
        $adj->line_items[$id_edit]->project_site_description = $project_site_description;
        
        $_POST['LineNo'] =-1;
        
        line_start_focus();
    }
	
}

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

function check_delete_item($id)
{
        
    $pr = &$_SESSION['pr_items'];
    
    $row_id = 0;
    if(isset($pr->line_items[$id]->row_id)){
        $row_id = $pr->line_items[$id]->row_id;
    }
    
    if($row_id > 0){
        $pr_item = get_pr_item($row_id);
        if ($pr_item['quantity_ordered'] > 0){
            display_error( _("This item has some quantities allocated. Not possible to delete."));
            set_focus('stock_id');
            return false;
        }
        if ($pr_item['issued_qty'] > 0) 
        {
            display_error( _("This item has some quantities issued. Not possible to delete."));
            set_focus('stock_id');
            return false;
        }
    }
    
    return true;
}

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

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

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

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

//    $item_info = get_item_edit_info($_POST['stock_id']);
//    $alternate_unit = get_convertion_factor($_POST['tran_unit'], $_POST['stock_id']);
//    $convertion_factor = $alternate_unit['convertion_factor'];
    
    $tran_unit = $_POST['tran_unit'];
    get_convertion_factor2($_POST['stock_id'], $tran_unit, $convertion_factor);
    $_POST['tran_unit'] = $tran_unit;
            
    $tran_unit_estaimted_price = input_num('estimate_price');
        
	add_pr_to_cart($_SESSION['pr_items'], $_POST['stock_id'],input_num('qty'), $_POST['required_date'], 
                            $_POST['line_comment'],0,0,input_num('qty'),
                            0, $tran_unit_estaimted_price, $_POST['requesting_location'], $_POST['tran_unit'], 
                            input_num('tran_qty'), $convertion_factor);
        
    $adj = &$_SESSION['pr_items'];
    $current_element = (count($adj->line_items)-1);
    
//    if($alternate_unit == ""){
//        $convertion_factor = 1;
//    }
    $adj->line_items[$current_element]->requested_qty = input_num('tran_qty')*$convertion_factor;
    $adj->line_items[$current_element]->pr_line_id = -1;

    $task_id = 0;
    $task_description = '';
    if($_POST['task_id'] != -1){
        $project_task = get_task_details($_POST['task_id']);
        $task_id = $project_task['task_id'];
        $task_description = $project_task['description'];
    }
    $adj->line_items[$current_element]->task_id = $task_id;
    $adj->line_items[$current_element]->task_description = $task_description;
    
    $project_site_id = 0;
    $project_site_description = '';
    if($_POST['project_site_id'] != -1){
        $project_site = get_project_site_details($_POST['project_site_id']);
        $project_site_id = $project_site['id'];
        $project_site_description = $project_site['description'];
    }
    $adj->line_items[$current_element]->project_site_id = $project_site_id;
    $adj->line_items[$current_element]->project_site_description = $project_site_description;
    
	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'])) {
        $_POST['LineNo'] = -1;
	line_start_focus();
}
//-----------------------------------------------------------------------------------------------

if (isset($_GET['NewAdjustment']) || !isset($_SESSION['pr_items']))
{
	handle_new_order();
}

//-----------------------------------------------------------------------------------------------
start_form();

display_pr_header($_SESSION['pr_items']);

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

$Ajax->activate('pr_items_table');
div_start('pr_items_table');
display_pr_items(_("Purchase Requisition Items"), $_SESSION['pr_items']);
div_end();
//pr_options_controls();

end_outer_table(2, false);

if(isset($_SESSION['pr_items']->order_id) && $_SESSION['pr_items']->order_id > 0)
{
    submit_center_first('Update_PR', _("Update"), '', 'default');
    submit('Update_Release', 'Release for Approval', true, '', 'default');
    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
    
    br();
    submit_center_first('Back_To_Originator', "Back To Originator", '', 'default');
    submit_center_last('Reject_PR', "Reject", '', 'default');
}
else
{
    submit_center_first('Add_PR', _("Save Requisition"), '', 'default');
    submit('Add_Release', 'Save and Release for Approval', true, '', 'default');
    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
}

end_form(3);
end_page();

?>
