<?php
/**********************************************************************
***********************************************************************/

$page_security = 'SA_TOOL_REQUEST';
if (!@$_GET['popup'])
	$path_to_root = "..";
else	
	$path_to_root = "../..";

include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/inventory.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/includes/approval_functions.inc");
include_once($path_to_root . "/projects/includes/db/project_payment_application_db.inc"); 
include_once($path_to_root . "/reporting/includes/reporting.inc");
include_once($path_to_root . "/assets/includes/db/tool_requests_db.inc");
include_once($path_to_root . "/includes/references.inc");
include_once($path_to_root . "/includes/ui/ui_lists_group_companies.inc");
include_once($path_to_root . "/includes/db/group_companies_db.inc");
include_once($path_to_root . "/assets/includes/db/assets_db.inc");
include_once($path_to_root . "/includes/project_cost_functions.inc");


$js = '';
if ($SysPrefs->use_popup_windows){
	$js .= get_js_open_window(900, 500);
}

if (user_use_date_picker()){
	$js .= get_js_date_picker();
}

page(_($help_context = "Tool Request"), false, false, "", $js);

//------------------------------------------------------------------------------------------------------
simple_page_mode(true);


$ar_no = -1;
 
if (isset($_GET['ARNo']))
{
    $_POST['ARNo'] = $_GET['ARNo'];
    set_session_variable("ST_TOOL_REQUEST_ar_no", $_POST['ARNo']);
}

if (isset($_GET['NewOrder']))
{
    $_POST['ARNo'] = -1;
    set_session_variable("ST_TOOL_REQUEST_ar_no", $_POST['ARNo']);
}        
        
if (isset($_POST['ARNo']) && $_POST['ARNo'] > 0){
    $ar_no = $_POST['ARNo'];
}
else{
    if(!isset($_POST['ARNo']) > 0){
        $_POST['ARNo'] = -1;
        set_session_variable("ST_TOOL_REQUEST_ar_no", $_POST['ARNo']);
    }else{
        $ar_no = get_session_variable('ST_TOOL_REQUEST_ar_no');
    }
}


if (isset($_GET['Processed_AR_No'])) 
{            
    $trans_no = $_GET['Processed_AR_No'];
    $trans_type = ST_TOOL_REQUEST;
    $message = get_session_variable('ST_TOOL_REQUEST_messages');
    clear_session_variable('ST_TOOL_REQUEST_messages');
    
	display_notification_centered($message);
        
	display_note(print_document_link($trans_no, _("&Print this toll request"), true, $trans_type), 0, 0);

	hyperlink_no_params("$path_to_root/assets/tool_requests.php", _("Create another &tool Request"));

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

	display_footer_exit();
}


function can_process_ar_header($ar_no)
{  
    global $Refs;
    
    $header_id = $row_state = 0;
    $ar_header = get_tool_request_header($ar_no);
      
    if($ar_no > 0 && isset($ar_header['id']) && $ar_header['id'] > 0){
        if(!($ar_header['approval_status'] == AS_NEW || $ar_header['approval_status'] == AS_WITH_THE_APPROVER || 
                $ar_header['approval_status'] == AS_AWAITING_APPROVAL || $ar_header['approval_status'] == AS_BACK_TO_ORIGINATOR)){
        
            $message = ("This document status does not allow further updating.");
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
        
        $current_user_id = $_SESSION['wa_current_user']->user;
        $ced_msg = can_edit_document(ST_TOOL_REQUEST, $ar_header['project_id'], $ar_header['next_approval_group_id'], 
                            $current_user_id, $ar_header['created_by'], $ar_no);
        if($ced_msg['success'] !== true){
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $ced_msg['message']);
        }
        
        $header_id = $ar_header['id'];
        $row_state = $ar_header['row_state'];
    } 
    
    if(!$Refs->is_valid($_POST['reference'])){
        $message("Please enter a reference.");
        $set_focus = 'reference';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);      
    }    
 
    $ref_msg = reference_exists($_POST['reference'], ST_TOOL_REQUEST, $header_id);
    if($ref_msg){
        $message = $ref_msg;
        $set_focus = 'reference';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);       
    }
       
    if(!($_POST['project_id'] > 0))
    {
        $message = "Please select a Project.";
        $set_focus = 'project_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
              
    if(!(strlen($_POST['employee_code']) > 1))
    {
        $message = "Please select an employee.";
        $set_focus = 'employee_code';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }  

    if($_POST['location'] == '')
    {
        $message = "Please select an asset location.";
        $set_focus = 'location';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }        

    if(!is_date($_POST['tran_date']))
    {
        $message = "Date entered is not a valid date.";
        $set_focus = 'tran_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
        
            
    return array("success" => true, 'row_state' => $row_state, "message" => "");    
}


function can_process_ar_line()
{
    if(!isset($_POST['Save_Tool_Request_Header'])){
        if(!($_POST['asset_id'] > 0))
        {
            $message = "Please select an asset.";
            $set_focus = 'asset_id';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        }
        
        $asset = get_asset($_POST['asset_id']);        
//        if(!($asset['type'] == "T"))
//        {
//            global $asset_types;
//            $message = "Only assets of the type ".$asset_types[AT_TOOL]." can be selected.";
//            $set_focus = 'task_id';
//            return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
//        } 
        
        $multiple_items = $asset['multiple_items'];
        if($multiple_items == 1){
            if(!(check_num('quantity', 0.00001)))
            {
                $message = "Quantity should be greater than zero.";
                $set_focus = 'quantity';
                return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
            }
        }else{
            if(input_num('quantity') > 1){
                $message = "This is a single item asset. Quantity should be one.";
                $set_focus = 'quantity';
                return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
            }
        }
        
        if(!($_POST['task_id'] > 0))
        {
            $message = "Please select a Budget.";
            $set_focus = 'task_id';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
        }        
                
        if(!is_date($_POST['from_date']))
        {
            $message = "From date entered is not a valid date.";
            $set_focus = 'from_date';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
        }
        
        if(!is_date($_POST['to_date']))
        {
            $message = "To date entered is not a valid date.";
            $set_focus = 'to_date';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
        }
        
        if(date1_greater_date2($_POST['from_date'], $_POST['to_date']))
        {
            $message = "From date cannot be after to date.";
            $set_focus = 'to_date';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
        }
        
        if(!check_num('no_of_days', 0.001))
        {
            $message = "No of charging units should be positive and greater than zero.";
            $set_focus = 'no_of_days';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
        }
                                    
        return array("success" => true, "focus_to" => '', "message" => "");  
        
    }
}


function can_delete_ar_line($ar_no, $selected_id)
{
   $arh = get_tool_request_header_record($ar_no);
   
   if($ar_no > 0){
        if(!($arh['approval_status'] == AS_NEW || $arh['approval_status'] == AS_WITH_THE_APPROVER || 
                $arh['approval_status'] == AS_AWAITING_APPROVAL || $arh['approval_status'] == AS_BACK_TO_ORIGINATOR)){
            $message = ("This document status does not allow further updating.");
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
    } 
    
    $line_count = get_tool_request_line_count($ar_no);
    if(!($line_count > 1)){
        $message = ("This is the last line. Can not delete this line.");
        $set_focus = '';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }    
    return array("success" => true, "focus_to" => '', "message" => "");       
}


function can_release_tool_request($ar_no)
{
    $line_count = get_tool_request_line_count($ar_no);
    if (!($line_count > 0))
    {
        $message = ("There are no tool request details entered. Can not release this document.");
        $set_focus = '';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
   return array("success" => true, "focus_to" => '', "message" => "");    
}

function save_ar_header(&$ar_no)
{

    $ar_no = write_tool_request_header($ar_no, $_POST['reference'], $_POST['project_id'],
                                            $_POST['group_company_code'], $_POST['employee_code'], $_POST['location'], 
                                            $_POST['comment'], $_POST['tran_date']);  
                         
    
    if($ar_no > 0){
        set_session_variable("ST_TOOL_REQUEST_ar_no", $ar_no);
        return array("success" => true, 'trans_no' => $ar_no, "message" => "Tool request $ar_no has been saved.");
    }
    else{
        return array("success" => false, 'trans_no' => '', "message" => "Could not save tool request.");
    }
}


function save_ar_detail(&$ar_no, $selected_id)        
{    

    $asset_rate = get_tool_rate_category($_POST['asset_id']);
    
//    $no_of_days = date_diff2($_POST["to_date"], $_POST["from_date"], 'd') + 1;
    
    $no_of_days = input_num('no_of_days');
    
    $asset_rate_value = 0;
    if($_POST['project_asset'] == 1){
        $asset_rate_value = 0;
    }else{
        if (isset($asset_rate['id']) && $asset_rate['id'] > 0) {
            $asset_rate_value = $asset_rate['rate'];
        }
    }
    
    write_tool_request_line($ar_no, $selected_id, $_POST['asset_id'], get_post('rate_category_id'), 
                                $asset_rate_value, input_num('quantity'), get_post('task_id'), get_post('site_id'), 
                                $_POST['from_date'], $_POST['to_date'], 
                                $_POST['project_asset'], $_POST['line_comment'], $no_of_days); 
          
                                  
    return array("success" => true, 'trans_no' => $ar_no, "message" => "Tool Request Line saved.");
}


function save_tool_request(&$ar_no, $selected_id)
{
    
    $cparh_msg = can_process_ar_header($ar_no);   
    
    if($cparh_msg["success"] !== true) 
    {          
        if(isset($cparh_msg["focus_to"])){
            set_focus($cparh_msg["focus_to"]);            
        }
        return array("success" => false, "message" => $cparh_msg["message"]);
    }
    
    
    
    $line_msg = can_process_ar_line();
    if($line_msg['success'] !== true){
         if(isset($line_msg["focus_to"])){
            set_focus($line_msg["focus_to"]);            
        }
        return array("success" => false, 'trans_no' => $ar_no, "message" => $line_msg['message']);        
    }
       
    begin_transaction();
    
    $header_msg = save_ar_header($ar_no);
    if($header_msg["success"] !== true){
        cancel_transaction();
        return array("success" => false, 'trans_no' => $ar_no, "message" => $header_msg['message']);
    }

    $manual_line_msg = save_ar_detail($ar_no, $selected_id);
    if($manual_line_msg['success'] !== true){
        cancel_transaction();
        return array("success" => false, 'trans_no' => $ar_no, "message" => $manual_line_msg['message']);
    }

    commit_transaction();
    return array("success" => true, 'trans_no' => $ar_no, "message" => "Tool Request $ar_no has been saved.");

}

function display_ar_header($ar_no)
{
    global $Refs;
    
    if($ar_no>0){
        
        $ar_header = get_tool_request_header($ar_no);
        $_POST['project_id'] = $ar_header['project_id'];
        
        $project_id = $_POST['project_id'];
        $user_id = $_SESSION['wa_current_user']->user;
        $cap = can_access_project($project_id, $user_id);
        if($cap['success'] !== true) 
        {
            display_error($cap["message"]);
            set_focus('project_id');
            display_footer_exit();
            exit;
        }  
        
               
        if(!isset($_POST['reference'])){
            $_POST['reference'] = $ar_header['reference'];
        }
        
        if(!isset($_POST['comment'])){
            $_POST['comment'] = $ar_header['comment'];
        }        
              
        if(!isset($_POST['location'])){
            $_POST['location'] = $ar_header['location'];
        }

        if(!isset($_POST['tran_date'])){
            $_POST['tran_date'] = sql2date($ar_header['date']);
        }

        if(!isset($_POST['project_description'])){
            $_POST['project_description'] = $ar_header['project_description'];
        }
        
        if(!isset($_POST['group_company_code'])){
            $_POST['group_company_code'] = $ar_header['company_code'];
        }
        
        if(!isset($_POST['employee_code'])){
            $_POST['employee_code'] = $ar_header['employee_code'];
        }
        
        if(!isset($_POST['approval_status'])){
            $_POST['approval_status'] = $ar_header['approval_status'];
        }
    }else{
        $_POST['reference'] = $Refs->get_next(ST_TOOL_REQUEST);            
        $_POST['approval_status'] = 0;
    }
  
    start_outer_table(TABLESTYLE2, "width=30%"); // outer table
    start_table(TABLESTYLE2);  
        table_section(1, "50%");
        
        if($ar_no > 0){
            $pd_request = get_tool_request_header($ar_no);
            $reference = $pd_request['reference'];            
            text_row("Reference:", 'reference', $reference, null, null);            
        }else{            
            text_row("Reference:", 'reference', $Refs->get_next(ST_TOOL_REQUEST), null, null);   
        }
                  
        if($ar_no > 0){
            label_row("Project:", $_POST['project_description']);   
            hidden('project_id', $_POST['project_id']);
        }
        else{
            project_list_row(_("Project:"), 'project_id', null, _('Select a project'), true);                         
        } 
            
        group_companies_list_row("Company:", 'group_company_code', null, false, true);    
        group_company_employees_simple_list_row(_("Select an Employee:"), 'employee_code', $_POST['group_company_code'],'', "Please select an employee", "Select an employee", false);    
      

        asset_locations_list_row("Tool Location:", 'location', null, 'Select Location', false);           
      
        date_row("Date:", "tran_date");
        
        textarea_row("Comment:", 'comment', null, 30, 2); 
        
        global $approval_statuses;
        $s = get_project_trans_view_str(ST_APPROVAL_LOG, $ar_no."&source_type_id=".ST_TOOL_REQUEST, "Approval Status");
        label_row($s, $approval_statuses[$_POST['approval_status']]);
    
      
//    end_table();
    end_outer_table(1); // outer table
    
}


function release_tool_request_for_approval($ar_no)
{     
    $cparh_msg = can_process_ar_header($ar_no);      
    if($cparh_msg["success"] !== true) 
    {          
        if(isset($cparh_msg["focus_to"])){
            set_focus($cparh_msg["focus_to"]);            
        }
        display_error($cparh_msg['message']);
        return;
    }
        
    $row_state =  $cparh_msg['row_state'];
    
    $release_msg = can_release_tool_request($ar_no);
     if($release_msg['success'] !== true){
        display_error($release_msg['message']);
        return;
    }   
    
    begin_transaction();
    
    $arh_msg = save_ar_header($ar_no);
    if($arh_msg['success'] !== true){
        cancel_transaction();
        display_error($arh_msg['message']);
        return;
    } 

    $ar_msg = release_tool_request($ar_no, $row_state);
    if($ar_msg['success'] !== true){
        cancel_transaction();
        display_error($ar_msg['message']);
        return;
    }

    commit_transaction();
    clear_session_variable("ST_TOOL_REQUEST_no");
    set_session_variable('ST_TOOL_REQUEST_messages', $ar_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_AR_No=$ar_no");    
   
}
  
  
function send_tool_request_back_to_originator($ar_no)
{        
    $msg = can_process_ar_header($ar_no);
    if($msg['success'] !== true){
        display_error($msg['message']);
        return $msg;
    }
    
    begin_transaction();
     
    $arh = get_tool_request_header($ar_no);

    $current_user_id = $_SESSION['wa_current_user']->user;

    $ar_msg = send_back_to_document_originator(ST_TOOL_REQUEST, $ar_no, $arh['project_id'],
                                    $arh['next_approval_group_id'], $current_user_id, $arh['row_state'], 
                                    $arh['created_by']);
    
    if($ar_msg['success'] !== true){
        display_error_cancel($ar_msg['message']);
        return;
    }

    commit_transaction();
    clear_session_variable("ST_TOOL_REQUEST_no");
    set_session_variable('ST_TOOL_REQUEST_messages', $ar_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_AR_No=$ar_no");        
}
 
 
function reject_tool_request($ar_no)
{
    $msg = can_process_ar_header($ar_no);
    if($msg['success'] !== true){
        display_error($msg['message']);
        return $msg;
    }
    
    begin_transaction();
    $arh = get_tool_request_header($ar_no);

    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rj_msg = reject_document(ST_TOOL_REQUEST, $ar_no, $arh['project_id'],
                                $arh['next_approval_group_id'], $current_user_id, $arh['row_state']);
    
    if($rj_msg['success'] !== true){
        display_error_cancel($rj_msg['message']);
        return;
    }

    commit_transaction();
    clear_session_variable("ST_TOOL_REQUEST_no");
    set_session_variable('ST_TOOL_REQUEST_messages', $rj_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_AR_No=$ar_no");
 
}    
     
      
function display_ar_details($ar_no)
{  
    global $project_invoice_line_types;    
    
    display_heading("Details");
    $result = get_tool_request_details($ar_no);      
                              
    start_table(TABLESTYLE, "width=98%");
    $th = array(_("ID"),_("Tool"), _('Rate Category'),_('Budget'),
                _('Site'), _("From Date"),_("To Date"),_("Project Asset"),_("Comment"), 
                _("Quantity"),"Rate", "Days", "Cost","","");  
                          

    table_header($th);
    $k = 0; //row colour counter
   // $total = 0;
    $line_total = 0;
            
    while ($myrow = db_fetch($result)) 
    {
        alt_table_row_color($k);

        label_cell($myrow['id']);
        label_cell($myrow["asset_code"]."-".$myrow["asset_description"]."-"."(".$myrow["asset_id"].")");  
        label_cell($myrow["asset_rate_description"]);
      
        label_cell($myrow["task_description"]."(".($myrow["task_code"]).")");         
        label_cell($myrow["site_description"]);          
        label_cell(sql2date($myrow["from_date"]), "align=center"); 
        label_cell(sql2date($myrow["to_date"]), "align=center"); 
        
        label_cell(get_yes_no_name($myrow["project_asset"]), "align=center"); 
        label_cell($myrow["line_comment"]);

        label_cell($myrow["quantity"], "align=right");
        hidden('quantity', 1);
        
        amount_decimal_cell($myrow["rate"]);
//        $days = date_diff2(sql2date($myrow["to_date"]), sql2date($myrow["from_date"]), 'd');
//        qty_cell($days, false, 0);
        label_cell($myrow["no_of_days"], "align=right");
        
        if($myrow["no_of_days"] == 0){
            $days = date_diff2(sql2date($myrow["to_date"]), sql2date($myrow["from_date"]), 'd');
            $line_cost = ($myrow["rate"] * $myrow["quantity"]) * $days;
        }else{
            $line_cost = $myrow["rate"] * $myrow["quantity"] * $myrow["no_of_days"];
        }
      
        amount_decimal_cell($line_cost);
        
        $line_total += $line_cost;
                
        edit_button_cell("Edit".$myrow["id"], _("Edit"));    
        delete_button_cell("Delete".$myrow["id"], _("Delete"));  

        end_row();        

    }
    
    start_row();
    
    label_cell("Total", "colspan=12 align=right");
    amount_cell($line_total, true);
        
    end_row();
    
}

function display_ar_edit_controls($selected_id, &$Mode)
{
    global $Ajax;
    
    $Ajax->activate("billing_items");    

    if($selected_id > 0)
    {      
        $myrow = get_tool_request_detail_line($selected_id); 
        
            $_POST['id'] = $myrow["id"];
            $_POST['asset_id'] = $myrow["asset_id"];
            $_POST['rate_category_id'] = $myrow["id"];
            $_POST['task_id'] = $myrow["task_id"];
            $_POST['site_id'] = $myrow["site_id"];
            $_POST['from_date'] = sql2date($myrow["from_date"]);
            $_POST['to_date'] = sql2date($myrow["to_date"]);
            $_POST['line_comment'] = $myrow["line_comment"]; 
            $_POST['project_asset'] = $myrow["project_asset"]; 
            $_POST['quantity'] = $myrow["quantity"]; 
            $_POST['no_of_days'] = $myrow["no_of_days"]; 
          
    } else {
        $_POST['rate_category_id'] = 0;
    }
  
    br();

    div_start('billing_items');
    start_table(TABLESTYLE2);
      
    
    start_row();
    
    if($selected_id > 0){        
        $asset_details = get_asset($_POST['asset_id']);
        label_row("Asset:", $asset_details['asset_code']." - ".$asset_details['description']." - "."(".$asset_details['asset_id'].")");
        hidden('asset_id', $asset_details['asset_id']);
    }else{
        label_cell(_("Asset:"), "class='label'");

        echo "<td>";
//            echo tool_list('asset_id', null, false, true);
            echo asset_list('asset_id', null, false, true);
        echo "</td>";
    }
    end_row();
        
    $rate_description = '';
    $asset_rate = get_tool_rate_category($_POST['asset_id']);
    if (isset($asset_rate['id']) && $asset_rate['id'] > 0) {
        $rate_description = $asset_rate['rate_description'];
        $_POST['rate_category_id'] = $asset_rate['id'];
    }


    label_row("Rate Category:", $rate_description);
    hidden('rate_category_id', $_POST['rate_category_id']);
       
    $multiple_items = $owner_project_id = 0;
    $asset_details = get_asset($_POST['asset_id']);
    if (isset($asset_details['asset_id']) && $asset_details['asset_id'] > 0) {
        $multiple_items = $asset_details['multiple_items'];
        $owner_project_id = $asset_details['owner_project_id'];
    }
        
    global $Ajax;
    
//    div_start('quantity');
        $Ajax->activate('quantity');
  
    
    if($multiple_items == true){            
        amount_row("Quantity:", 'quantity', null, null, null, 0);
    }else{
        label_row("Quantity:", 1);
        hidden('quantity', 1);
    }
//  div_end();
          
    tasks_list_row(_("Budget:"), 'task_id', $_POST['project_id'], null, _('Select a budget'), false); 
    
    project_sites_list_row("Project Site:", 'site_id', $_POST['project_id'], null, 'Select a Site', false);     
    
    date_row("From Date:", 'from_date'); 
    date_row("To Date:", 'to_date');
    
    if($_POST['project_id'] == $owner_project_id){
        $project_asset = 1;
    }else{
        $project_asset = 0;
    }
    
    amount_row("Charging Units (Per Tool):", 'no_of_days', null, null, null, 0);
    
    label_row("Project Asset:", get_yes_no_name($project_asset));
    hidden('project_asset', $project_asset);
    
    textarea_row("Comment:", 'line_comment', null, 35, 2); 
    
    end_table(1);
    div_end();

}

function handle_save_tool_request_header($ar_no)
{
        
    $cparh_msg = can_process_ar_header($ar_no);   
    
    if($cparh_msg["success"] !== true) 
    {          
        if(isset($cparh_msg["focus_to"])){
            set_focus($cparh_msg["focus_to"]);            
        }
        return array("success" => false, "message" => $cparh_msg["message"]);
    }
    
    begin_transaction();
    $msg = save_ar_header($ar_no);
    if($msg["success"] !== true) 
    {          
        cancel_transaction();
        return array("success" => false, "message" => $cparh_msg["message"]);
    }
    else{
        commit_transaction();
        return $msg;
    }

}

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

    $msg = handle_save_tool_request_header($ar_no);
    
    if($msg['success'] !== true){
        display_error($msg['message']);
    }
    else{
        $_POST['ARNo'] = $msg['trans_no'];
        display_notification($msg['message']);
        $Mode = 'RESET';
    }

}


if(isset($_POST['Add_Tool_Request']) || isset($_POST['Update_Tool_Request'])){        
    
    $msg = save_tool_request($ar_no, $selected_id);
    
    if($msg['success'] !== true){
        display_error($msg['message']);
    }
    else{
        $ar_no = $msg['trans_no'];
        hidden('ARNo', $msg['trans_no']);
        display_notification($msg['message']);
        $Mode = 'RESET';
    }
}


if(isset($_POST['Update_Release_AR'])){
    release_tool_request_for_approval($ar_no);
}

if(isset($_POST['Back_To_Originator_AR'])){
    send_tool_request_back_to_originator($ar_no); 
}

if(isset($_POST['Reject_AR'])){
    reject_tool_request($ar_no);  
}


if (isset($_POST['cancel'])){
    $Mode = 'RESET';
    $selected_id = -1;
    unset($_POST);
}  
//--------------------------------------------------------------------------------------------------------

if ($Mode == 'Delete')    
{
    $can_delete_msg = can_delete_ar_line($ar_no, $selected_id);    
    if($can_delete_msg['success'] !== true){
        if(isset($can_delete_msg["focus_to"])){
            set_focus($can_delete_msg["focus_to"]);
        }
        display_error($can_delete_msg["message"]);
    }
    else{
        save_delete_tool_request_line($ar_no, $selected_id);
        display_notification(_("Tool request item has been deleted."));               
    }
    $Mode = 'RESET';
}

if ($Mode == 'RESET')
{
    $selected_id = -1;
}

global $Ajax;

$Ajax->activate('_page_body');
$Ajax->activate('billing_items');
    
//--------------------------------------------------------------------------------------------------------------

start_form();

$pi_header = display_ar_header($ar_no);


if(($ar_no > 0)){
    submit_center_first('Save_Tool_Request_Header', _("Save"), '', 'default');
    br(2);

    submit_center_first('Update_Release_AR', "Release for Approval", '', 'default');
    submit('Back_To_Originator_AR', 'Back To Originator', true, '', 'default');
    submit_center_last('Reject_AR', "Reject", '', 'default');	
}
 
//------------------------------------------------------------------------------------------------------------
 
br();

display_ar_details($ar_no);
hidden('ARNo', $ar_no);

//inactive_control_row($th);
end_table();
//-----------------------------------------------------------------------------------------------------------

$Ajax->activate('asset_id');

display_ar_edit_controls($selected_id, $Mode);


if($selected_id > 0){
    submit_center_first('Update_Tool_Request', _("Update"), '', 'default');
    hidden('selected_id', $selected_id);
    
    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
}
else{        
    submit_center_first('Add_Tool_Request', _("ADD"), '', 'default');
    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
}

br();


if (!@$_GET['popup'])
{
    end_form();
    end_page(@$_GET['popup'], false, false);        
}




?>
