<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_VEHICLE_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 . "/transport/includes/db/vehicle_requests_db.inc");
include_once($path_to_root . "/transport/includes/db/vehicle_packages_db.inc");
//include_once($path_to_root . "/gl/includes/db/approve_i_owe_you_enties_db.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 . "/reporting/includes/reporting.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 = "Vehicle Requests"));
//------------------------------------------------------------------------------------------
simple_page_mode(true);

//$vr_id = 0;

if (isset($_GET['ModifyVRNumber']))
{
	  $selected_id = $_GET['ModifyVRNumber'];
}
if (isset($_POST['ModifyVRNumber']) && $_POST['ModifyVRNumber'] > 0)
{
	  $selected_id = $_POST['ModifyVRNumber'];
}



if (isset($_GET['VR_ID'])) 
{
	//return;
        
    $trans_no = $_GET['VR_ID'];
	$trans_type = ST_VEHICLE_REQUEST;
    $message = get_session_variable('vr_messages');
    clear_session_variable('vr_messages');
    
	display_notification_centered($message);
        
	display_note(print_document_link($trans_no, _("&Print this Vehicle Request"), true, $trans_type), 0, 0);

	hyperlink_no_params("$path_to_root/transport/vehicle_requests.php", _("Create another &Vehicle Request"));
    
    hyperlink_no_params("$path_to_root/transport/inquiry/vehicle_requests_inquiry.php", _("Select another &Vehicle 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_vr($vr_id)
{	
    if($vr_id > 0){
        $vr = get_vehicle_request($vr_id);
        if ($vr['closed'] == 1)
        {
            $message = "This vehicle request has been closed already. No futher updates allowed";
            $set_focus = 'project_id';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
        
        if(!($vr['approval_status'] == AS_NEW || $vr['approval_status'] == AS_WITH_THE_APPROVER || $vr['approval_status'] == AS_AWAITING_APPROVAL)){
            $message = ("This Vehicle Request status does not allow further updating.");
            $set_focus = 'amount';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }

        $ced_msg = can_edit_document(ST_VEHICLE_REQUEST, $vr['project_id'], $vr['next_approval_group_id'], 
                            $_SESSION['wa_current_user']->user, $vr['created_by'], $vr_id);
        if($ced_msg['success'] !== true){
            $message = $ced_msg['message'];
            $set_focus = 'amount';
            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);
    }
    
    $project_id = get_post('project_id');    
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($project_id, $user_id);
    if($cap['success'] !== true) 
    {
        $message = $cap['message'];
        $set_focus = 'project_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    if(!($_POST['task_id'] > 0))
    {
        $input_error = 1;
        $message = "Please select a budget.";
        $set_focus = 'task_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    if(!($_POST['vehicle_type'] > 0))
    {
        $input_error = 1;
        $message = "Please select vehicle type.";
        $set_focus = 'vehicle_type';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }

    if(!($_POST['package_id'] > 0))
    {
        $input_error = 1;
        $message = "Please select a package.";
        $set_focus = 'package_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
        
//    if (!check_num('amount',0))
//   	{
//        $message = "Amount entered is not numeric or negative.";
//        $set_focus = 'amount';
//        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
//   	}

    if (!is_date($_POST['from_date']))
   	{
        $message = "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 = "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']))
        {
            $input_error = 1;
            display_error( _("From date can not be greater than to date"));
            set_focus('to_date');
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);            
        }       
        
        $t2s = time2seconds($_POST['from_time'], $format = "hh:mm");
        if($t2s["success"] === true){     
            $_POST['from_time_s'] = $t2s["message"];           
        }
        else{
            return array("success" => false, "message" => "From time is not valid ", "focus_to" => "from_time");
        }
       
        $t2s = time2seconds($_POST['to_time'], $format = "hhh:mm");
        if($t2s["success"] === true){ 
            $_POST['to_time_s'] = $t2s["message"];
        }
        else{
            return array("success" => false, "message" => "To Time is not valid ", "focus_to" => "to_time");
        }         
        
     return array("success" => true, "message" => "");    
}

function add_vr()
{
    $cd = can_process_vr(-1);
    if($cd["success"] !== true) 
    {          
        return array("success" => false, "message" => $cd["message"]);
    }
    
    $from_date_time['from_date_time'] = date2sql($_POST['from_date'])." ".$_POST['from_time'];
    $to_date_time['to_date_time'] = date2sql($_POST['to_date'])." ".$_POST['to_time'];
    
    $package_cost = get_vehicle_package_cost($_POST['package_id']);
    
    $rec_id = add_vehicle_requests($_POST['project_id'],  $_POST['task_id'],$_POST['vehicle_type'],  $_POST['package_id'], 
                                   $package_cost, $from_date_time['from_date_time'],                               
                                   $to_date_time['to_date_time'], $_POST['passengers'], 
                                    $_POST['route'], $_POST['vehicle_id'], $_POST['comment']);
    if($rec_id > 0){
        return array("success" => true, "trans_no" => $rec_id, "message" => "Vehicle request $rec_id has been added.");
    }
    else{
        return array("success" => false, "message" => "Vehicle request could not be added.");
    }
}

function update_vr($selected_id)
{
    $cd = can_process_vr($selected_id);
    if($cd["success"] !== true) 
    {
        return array("success" => false, "message" => $cd["message"]);
    }
    
    $from_date_time['from_date_time'] = date2sql($_POST['from_date'])." ".$_POST['from_time'];
    $to_date_time['to_date_time'] = date2sql($_POST['to_date'])." ".$_POST['to_time'];
    $package_cost = get_vehicle_package_cost($_POST['package_id']);
    
    $recs = update_vehicle_requests($selected_id, $_POST['project_id'],  $_POST['task_id'],$_POST['vehicle_type'],  $_POST['package_id'], 
                                   $package_cost, $from_date_time['from_date_time'],                               
                                   $to_date_time['to_date_time'], $_POST['passengers'], 
                                    $_POST['route'], $_POST['vehicle_id'], $_POST['comment']);
     
    
    if($recs == 1){
        return array("success" => true, "trans_no" => $selected_id, "message" => "Vehicle request $selected_id has been updated.");
    }
    else{
        return array("success" => false, "message" => "Vehicle request $selected_id could not be updated.");
    }
}

function release_vr_for_approval($vr_id){
    
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    begin_transaction();
    $vr = get_vehicle_request($vr_id);
    add_to_task_cost($task_costs_summary, $vr['task_id'], $vr['amount'], $vr['amount'], 0);
    
    $info = approve_document(ST_VEHICLE_REQUEST, $vr_id, $vr['project_id'], $task_costs_summary, 
                                        $vr['next_approval_group_id'], $current_user_id, $vr['row_state'], $vr['created_by']);
    if($info['success'] !== true)
    {
        cancel_transaction();
        return array("success" => $info['success'],"trans_no" => $vr_id, "message" => $info['message']);
    }

    if($info['approval_status'] == AS_APPROVED)
    {            
        $msg = allocate_to_tasks(ST_VEHICLE_REQUEST, $vr_id, 
                                    $task_costs_summary, $current_user_id);
        if($msg['success'] !== true)
        {
            cancel_transaction();
            return array("success" => $msg['success'], "trans_no" => $vr_id, "message" => $info['message']);
        }
    }
    
    commit_transaction();
    return array("success" => true, "trans_no" => $vr_id, "message" => $info['message']);
}

function add_vr_and_release_for_approval(&$Mode){

    $vr_msg = add_vr();
    if($vr_msg["success"] !== true){
        return $vr_msg; 
    }

    $rec_id = $vr_msg["trans_no"];

    $Mode = 'RESET';
        
    $vr_msg = release_vr_for_approval($rec_id);
    return $vr_msg;
}

function update_vr_and_release_for_approval(&$Mode, $rec_id){

    $vr_msg = update_vr($rec_id);
    if($vr_msg["success"] !== true){
        return $vr_msg;
    }
    
    $Mode = 'RESET';


    $vr_msg = release_vr_for_approval($rec_id);
    return $vr_msg; 
    
}

function send_vr_back_to_originator(&$Mode, $rec_id)
{
    if(!can_process_vr()){
        return;
    }
    
    $vr = get_vehicle_request($rec_id);
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rd_msg = send_back_to_document_originator(ST_VEHICLE_REQUEST, $rec_id, $vr['project_id'],
                                    $vr['next_approval_group_id'], $current_user_id, $vr['row_state'], 
                                    $vr['created_by']);
    
    return $rd_msg; 
}

function reject_vr(&$Mode, $rec_id)
{
    if(!can_process_vr($rec_id)){
        return;
    }
    
    $vr = get_vehicle_request($rec_id);
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rd_msg = reject_document(ST_VEHICLE_REQUEST, $rec_id, $vr['project_id'],
                    $vr['next_approval_group_id'], $current_user_id, $vr['row_state']);
    
    return $rd_msg; 
}


function close_vr($selected_id)
{
    if(!can_process_vr($selected_id)){
        return;
    }
    $line = array();
    
    $vr_row = get_vehicle_request($selected_id);
    $line['vehicle_request_id'] = $vr_row["id"];
    $line['from_date'] = $vr_row['from_date'];
    $line['from_time'] = $vr_row['from_time'];
    $line['to_date'] = $vr_row['to_date'];
    $line['to_time'] = $vr_row['to_time'];
    $line['project_id'] = $vr_row['project_id'];
    $line['task_id'] = $vr_row['task_id'];
    $line['package_id'] = $vr_row['package_id'];
    $line['vehicle_id'] = $vr_row['vehicle_id'];
    $line['driver_id'] = $vr_row['driver_id'];
    $line['passengers'] = $vr_row['passengers'];
    $line['route'] = $vr_row['route'];
    $line['comment'] = $vr_row['comment'];

    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $msg = close_vehicle_request($line, $current_user_id);
    
    return $msg; 
    
}




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

if(isset($_POST['Add_VR'])){
    $avr = add_vr();
    if($avr["success"] !== true){
        if(isset($avr["focus_to"])){
            set_focus($avr["focus_to"]);
        }
        display_error($avr["message"]);
    }
    else{
        $Mode = 'RESET';
        set_session_variable('vr_messages', $avr["message"]);
        meta_forward($_SERVER['PHP_SELF'], "VR_ID=".$avr["trans_no"]);   
    }
}    
 
if(isset($_POST['Update_VR'])){
    $uvr = update_vr($selected_id);
    if($uvr["success"] !== true){
        if(isset($uvr["focus_to"])){
            set_focus($uvr["focus_to"]);
        }
        display_error($uvr["message"]);
    }
    else{
        $Mode = 'RESET';
        set_session_variable('vr_messages', $uvr["message"]);
        meta_forward($_SERVER['PHP_SELF'], "VR_ID=".$uvr["trans_no"]);     
    }
 }

if(isset($_POST['Add_VR_Release'])){
    $avrr = add_vr_and_release_for_approval($Mode);
    if($avrr["success"] !== true){
        if(isset($avrr["focus_to"])){
            set_focus($avrr["focus_to"]);
        }
        display_error($avrr["message"]);
    }
    else{
        $Mode = 'RESET';
        set_session_variable('vr_messages', $avrr["message"]);
        meta_forward($_SERVER['PHP_SELF'], "VR_ID=".$avrr["trans_no"]);     
    }
}

if(isset($_POST['Update_VR_Release'])){
    $uvrr = update_vr_and_release_for_approval($Mode, $selected_id);
    if($uvrr["success"] !== true){
        if(isset($uvrr["focus_to"])){
            set_focus($uvrr["focus_to"]);
        }
        display_error($uvrr["message"]);
    }
    else{
        $Mode = 'RESET';
        set_session_variable('vr_messages', $uvrr["message"]);
        meta_forward($_SERVER['PHP_SELF'], "VR_ID=".$uvrr["trans_no"]);     
    }
}

if(isset($_POST['Back_To_VR_Originator'])){
    $svrb = send_vr_back_to_originator($Mode, $selected_id);
    if($svrb["success"] !== true){
        if(isset($svrb["focus_to"])){
            set_focus($svrb["focus_to"]);
        }
        display_error($svrb["message"]);
    }
    else{
        $Mode = 'RESET';
        set_session_variable('vr_messages', $svrb["message"]);
        meta_forward($_SERVER['PHP_SELF'], "VR_ID=".$svrb["trans_no"]);
    }
    
}

if (isset($_POST['Reject_VR'])){
    $rvr = reject_vr($Mode, $selected_id);
    if($rvr["success"] !== true){
        if(isset($rvr["focus_to"])){
            set_focus($rvr["focus_to"]);
        }
        display_error($rvr["message"]);
    }
    else{
        $Mode = 'RESET';
        set_session_variable('vr_messages', $rvr["message"]);
        meta_forward($_SERVER['PHP_SELF'], "VR_ID=".$rvr["trans_no"]);
    }
} 

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

if (isset($_POST['Close_VR'])){
    $cvr = close_vr($selected_id);
    if($cvr["success"] !== true){
        if(isset($cvr["focus_to"])){
            set_focus($cvr["focus_to"]);
        }
        display_error($cvr["message"]);
    }
    else{
        $Mode = 'RESET';
        set_session_variable('vr_messages', $cvr["message"]);
        meta_forward($_SERVER['PHP_SELF'], "VR_ID=".$cvr["trans_no"]);
    }
} 

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

if ($Mode == 'Delete')
{
        $recs = delete_vehicle_requests($selected_id);
        
        if($recs == 1){
                display_notification(_("Vehicle Request has been deleted."));
        }
        else{
                display_error(_("Vehicle Request could not be deleted."));
        }
	$Mode = 'RESET';
}

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

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

//if (!@$_GET['popup'])	
//    
//$result = get_unapproved_vehicle_requests();   
//
    
global $Ajax;

start_form();

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

if(!isset($_POST['amount'])){
    $_POST['amount'] = 0;
}
if(!isset($_POST['tran_date'])){
    $_POST['tran_date'] = '';
}
if(!isset($_POST['comments'])){
    $_POST['comments'] = '';
}
    
$_POST['from_time'] = "08:00";
$_POST['to_time'] = "17:00";

$dec2 = 6;
if($selected_id > 0){
    $Mode = 'Edit';
}


if ($Mode =='Edit')   
{
    $myrow = get_vehicle_request($selected_id);
    
    $project_id = $myrow['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;
    }
    
    $_POST['id'] = $myrow["id"];
    
    if(!(isset($_POST['project_id']) && $_POST['project_id'] > 0)){
        $_POST['project_id'] = $myrow["project_id"];
    }
    
    if(!isset($_POST['task_id'])){
        $_POST['task_id'] = $myrow["task_id"];
    }
    
    if(!isset($_POST['vehicle_type'])){
        $_POST['vehicle_type'] = $myrow["vehicle_type_id"];
    }
    
    if(!isset($_POST['package_id'])){
        $_POST['package_id'] = $myrow["package_id"];    
    }
    
    $_POST['amount'] = $myrow["amount"];
    $_POST['from_date'] = sql2date($myrow["from_date_time"]);  
    $_POST['from_time'] = sql2time($myrow["from_date_time"]);
    $_POST['to_date'] = sql2date($myrow["to_date_time"]);  
    $_POST['to_time'] = sql2time($myrow["to_date_time"]);
    $_POST['passengers'] = $myrow["passengers"];
    $_POST['route'] = $myrow["route"];
    $_POST['vehicle_id'] = $myrow["vehicle_id"];
    $_POST['comment'] = $myrow["comment"];
    
//    $selected_id = $_POST['ModifyMRNumber']; 
    
}

hidden('selected_id', $selected_id );

br();
//hidden('selected_id', $selected_id);

$Ajax->activate('v_request');

div_start('v_request');
start_table(TABLESTYLE2);

    if($selected_id > 0){
        $project = get_project($_POST['project_id']);
        label_row("Project:", $project['description']);
        hidden('project_id', $_POST['project_id']);
//        project_list_row(_("Project:"), 'project_id', $_POST['project_id'], _('Select a project'), true);      
    }
    else{
        project_list_row(_("Project:"), 'project_id', null, _('Select a project'), true);  
    }
    tasks_list_row(_("Budget:"), 'task_id', $_POST['project_id'], null, _('Select a Budget')); 
    value_list_row("Vehicle Type:", 'vehicle_type', 'VEHICLE_TYPES', null, 'Select', true);
    
    vehicle_type_packages_list_row("Package:", 'package_id',$_POST['vehicle_type'], null, ('Select a package'));
    date_row("From Date:", "from_date");
    time_row("From Time:", 'from_time', null, 5);
    date_row("To Date:", "to_date");
    time_row("To Time:", 'to_time', null, 5);
    text_row("Passengers:", 'passengers', null, null, null);
    text_row("Route:", 'route', null, null, null);  
    vehicle_type_vehicles_list_row("Vehicle:",'vehicle_id', $_POST['vehicle_type'], null, ('Select a vehicle'),false);
    textarea_row('Comments:', 'comment', null, 35, 2); 

end_table(1);
div_end();
br();



if($selected_id > 0){
    submit_center_first('Update_VR', _("Update Vehicle Request"), '', 'default');
    submit('Update_VR_Release', 'Update and Release for Approval', true, '', 'default');
    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
//    
    br();
    
    submit_center_first('Back_To_VR_Originator', "Back To Originator", '', 'default');
    submit('Reject_VR', "Reject", true, '', 'default');
    submit_center_last('Close_VR', "Close Vehicle Request", '', 'default');
}
else{
        
    submit_center_first('Add_VR', _("Create Vehicle Request"), '', 'default');
    submit('Add_VR_Release', 'Save and Release for Approval', true, '', 'default');
    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
}

br();

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

?>
