<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_ASSET_BOOKING_REQUEST';
$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 . "/asset_register/includes/asset_booking_request_ui.inc");
include_once($path_to_root . "/asset_register/includes/db/asset_booking_request_db.inc");
include_once($path_to_root . "/reporting/includes/reporting.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 = 'Asset Booking Request'), 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 (get_post('cancel')) {
    
//    if (isset($_GET['ModifyABNumber']) && is_numeric($_GET['ModifyABNumber'])) 
//    {
//        $Ajax->activate('_page_body');
//    }
//    else
//    {
	$_SESSION['ab_items']->clear_items();
            unset ($_SESSION['ab_items']);
            clear_data();
	set_focus('issuing_location');
	$Ajax->activate('_page_body');
//    }
}

if (isset($_GET['ModifyABNumber']) && is_numeric($_GET['ModifyABNumber'])) 
{
    $help_context = 'Modifying Material Requisition';
    $_SESSION['page_title'] = sprintf( _("Modifying Asset Booking # %d"), $_GET['ModifyABNumber']);
    
    	if (isset($_SESSION['ab_items']))
	{
		$_SESSION['ab_items']->clear_items();
		unset ($_SESSION['ab_items']);
	}

    $_SESSION['ab_items'] = new items_cart(ST_MATERIAL_REQ);
    
    populate_cart_from_database($_GET['ModifyABNumber']);
}        
        
        //-----------------------------------------------------------------------------------------------


function clear_data()
{ 
    unset ($_POST['project_id']);
    unset ($_POST['issuing_location']);
    unset ($_POST['ab_reference']);
    unset ($_POST['ab_date']);
    unset ($_POST['asset_id']);
    unset ($_POST['line_comment']);
    unset ($_POST['line_required_from_date']);
    unset ($_POST['line_required_to_date']);
    unset ($_POST['mr_complete']);
    unset ($_POST['memo_']);
    
}


function populate_cart_from_database($ab_no)
{
        $myrow = get_asset_booking($ab_no);
        
        $ab_cart = $_SESSION['ab_items'];

        $ab_cart->order_id = $myrow["ab_no"];
        $ab_cart->reference = $myrow["reference"];
        if(isset($_POST['issuing_location'])){
            $ab_cart->issuing_location  = $_POST["issuing_location"];
        }
        else {
            $ab_cart->issuing_location  = $myrow["issuing_location"];
        }
        $ab_cart->required_date  = ($myrow["ab_date"]);
        $ab_cart->memo_  = $myrow["comments"];
        $ab_cart->requestor_name  = $myrow["requestor_name"];
        $ab_cart->created_on  = $myrow["created_on"];
//        $ab_cart->approval_path_id  = $myrow["approval_path_id"];
        $ab_cart->ab_complete  = $myrow["ab_complete"];
        $ab_cart->project_id  = $myrow["project_id"];
        $ab_cart->task_id  = $myrow["task_id"];
        $ab_cart->location_name = $myrow["location_name"];
        $ab_cart->project_description  = $myrow["project_description"];
        $ab_cart->task_description  = $myrow["task_description"];

  
        $ab_details = get_ab_details($ab_cart->order_id);

        $element_no = 0;
        while ($abd_row = db_fetch($ab_details)) 
        {
            $ab_line = new line_item($abd_row["asset_id"], 0, $standard_cost=null, 
                    null,null, $abd_row["line_comment"],
                    $comment=null, $abd_row["id"], null, null, null, null, null, null,
                    sql2date($abd_row["required_from_date"]), sql2date($abd_row["required_to_date"]));
            
            $ab_line->row_id = $abd_row["id"];
//            $mr_line->line_complete = $mrd_row["line_complete"];
            $ab_line->created_by = $abd_row["created_by"];
            $ab_line->created_on = $abd_row["created_on"];
                                    
            $ab_cart->line_items[$element_no] = $ab_line;
            $element_no++;
        }

}

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

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

	display_notification_centered(_("Material Transfer Requisition ".$trans_no." has been saved"));
	//display_note(get_trans_view_str($trans_type, $trans_no, _("&View this adjustment")));

	display_note(print_document_link($trans_no, _("&Print This Material Transfer Requisition"), true, $trans_type), 0, 0);

	hyperlink_no_params($_SERVER['PHP_SELF'], _("Enter &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['ab_items']))
	{
		$_SESSION['ab_items']->clear_items();
		unset ($_SESSION['ab_items']);
	}

    $_SESSION['ab_items'] = new items_cart(ST_MATERIAL_REQ);
	$_POST['ab_date'] = new_doc_date();
	if (!is_date_in_fiscalyear($_POST['ab_date']))
		$_POST['mr_date'] = end_fiscalyear();
	$_SESSION['ab_items']->tran_date = $_POST['ab_date'];	
}

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

function can_process()
{
	global $Refs;

	$adj = &$_SESSION['ab_items'];

        if(($adj->order_id == 0 ) || ($adj->order_id == null) || ($adj->order_id == "" ))
        {
//            if ($_POST['requesting_location'] == $_POST['issuing_location']) 
//            {
//                    display_error( _("Requesting location and Issuing location can not be same"));
//                    set_focus('requesting_location');
//                    return false;
//            }

            if (!$Refs->is_valid($_POST['ab_reference'])) 
            {
                    display_error( _("You must enter a reference."));
                    set_focus('ab_reference');
                    return false;
            }

            if (!is_new_reference($_POST['ab_reference'], ST_MATERIAL_REQ)) 
            {
                    display_error( _("The entered reference is already in use."));
                    set_focus('ab_reference');
                    return false;
            }
            if (!is_numeric($_POST['ab_reference'])) 
            {
                    display_error( _("Reference must be numeric."));
                    set_focus('ab_reference');
                    return false;
            }

            if (!is_date($_POST['ab_date'])) 
            {
                    display_error(_("The entered date for the material requisition is invalid."));
                    set_focus('ab_date');
                    return false;
            } 
            
            if ($_POST['project_id'] == -1) 
            {
                    display_error(_("Select a project."));
                    set_focus('project_id');
                    return false;
            }
            if ($_POST['task_id'] == -1) 
            {
                    display_error(_("Select a task."));
                    set_focus('task_id');
                    return false;
            }
            
//            elseif (!is_date_in_fiscalyear($_POST['mr_date'])) 
//            {
//                    display_error(_("The entered date is not in fiscal year."));
//                    set_focus('mr_date');
//                    return false;
//            } 
        }
        
        if (count($adj->line_items) == 0)	
        {
            display_error(_("You must enter at least one non empty item line."));
            set_focus('stock_id');
            return false;
	}
        
	return true;
}

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

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

	$ab_no = add_asset_booking($_SESSION['ab_items']->line_items, $_POST['ab_reference'],
		$_POST['issuing_location'], $_POST['project_id'], $_POST['task_id'],
                $_POST['ab_date'], $_POST['memo_'], 0);
        
        clear_data();
	$_SESSION['ab_items']->clear_items();
	unset($_SESSION['ab_items']);
        
   	meta_forward($_SERVER['PHP_SELF'], "AddedID=$ab_no");
} 

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

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

	$ab_no = update_asset_booking($_SESSION['ab_items']->order_id, 
                        $_SESSION['ab_items'],$_POST['issuing_location'], $_POST['project_id'], 
                        $_POST['task_id'],
                        $_POST['ab_date'], $_POST['memo_'], $_POST['ab_complete'], $_POST['ab_reference']);

	$_SESSION['ab_items']->clear_items();
	unset($_SESSION['ab_items']);
        
        //return;
        
   	meta_forward($_SERVER['PHP_SELF'], "AddedID=$ab_no");
} 

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

function check_item_data()
{

        if ($_POST['asset_id'] == -1) 
            {
                    display_error(_("Select an asset."));
                    set_focus('asset_id');
                    return false;
            }
        if (!is_date($_POST['line_required_from_date'])) 
	{
		display_error(_("The entered date for required from is invalid."));
		set_focus('line_required_from_date');
		return false;
	}
        if (!is_date($_POST['line_required_to_date'])) 
	{
		display_error(_("The entered date for required to is invalid."));
		set_focus('line_required_to_date');
		return false;
	}
        if (date1_greater_date2($_POST['line_required_from_date'], $_POST['line_required_to_date']))
            {
                $input_error = 1;
                display_error( _("Required to date can not be greater than required from date"));
                set_focus('line_required_to_date');
                return;
            }
   	return true;
}

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

function check_delete_item($id)
{
	global $Refs;
        
        $adj = &$_SESSION['ab_items'];

        if ($adj->line_items[$id]->issued_qty > 0) 
	{
		display_error( _("This item has some quantities issued. Not possible to delete."));
		set_focus('stock_id');
		return false;
	}
        return true;
}
 
//-----------------------------------------------------------------------------------------------

function check_update_item($id_edit)
{
	global $Refs;

        $adj = &$_SESSION['ab_items'];
         
//        if ($_POST['qty'] < $adj->line_items[$id_edit]->issued_qty) 
//	{
//		display_error( _("Can not reduce quantity below issued quantity."));
//		set_focus('stock_id');
//		return false;
//	}

        return true;
}
 
//-----------------------------------------------------------------------------------------------
   
        
function handle_update_item()
{
    $id_edit = $_POST['LineNo'];
    
    if($_POST['UpdateItem'] != "" && check_item_data() && check_update_item($id_edit))
    {
		
    	$adj = &$_SESSION['ab_items'];
        
        //$adj->update_cart_item($id_edit, input_num('qty'), input_num('std_cost'), null, $_POST['line_comment'], $_POST['line_required_date']);
        $adj->line_items[$id_edit]->stock_id = $_POST['asset_id'];
        $adj->line_items[$id_edit]->required_from_date = $_POST['line_required_from_date'];
        $adj->line_items[$id_edit]->required_to_date = $_POST['line_required_to_date'];
        $adj->line_items[$id_edit]->line_comment = $_POST['line_comment'];
        
    }
	line_start_focus();
}

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

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

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

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

	add_ab_to_cart($_SESSION['ab_items'], $_POST['asset_id'],
                $_POST['line_required_from_date'],$_POST['line_required_to_date'], $_POST['line_comment']);
        
        $adj = &$_SESSION['ab_items'];
        
//        $adj->line_items[(count($adj->line_items)-1)]->requested_qty = $_POST['qty'];
        
	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['ab_items']))
{
	handle_new_order();
}

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

display_ab_header($_SESSION['ab_items']);

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

display_ab_items(_("Asset Request Items"), $_SESSION['ab_items']);
mtr_options_controls($_SESSION['ab_items']);

end_outer_table(1, false);


if((isset($_SESSION['ab_items'])) && ($_SESSION['ab_items']->order_id > 0))
{
    submit_center_first('Update', _("Update"), '', 'default');
}
else
{
    submit_center_last('Process', _("Save Asset Booking"), '', 'default');
}

submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');

end_form();
end_page();

?>
