<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_VEHICLE_RUNNING_CHART_ENTRY';
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 . "/payroll/includes/db/salary_advances_db.inc");
//include_once($path_to_root . "/payroll/includes/db/salary_advances_accounts_setup_db.inc");
include_once($path_to_root . "/transport/includes/db/vehicle_running_chart_entry_db.inc");
include_once($path_to_root . "/transport/includes/db/vehicle_allocation_db.inc");
include_once($path_to_root . "/transport/includes/db/vehicle_packages_db.inc");
include_once($path_to_root . "/transport/includes/db/vehicles_db.inc");

include_once($path_to_root . "/projects/includes/db/projects_db.inc");
include_once($path_to_root . "/projects/includes/db/tasks_db.inc");

include_once($path_to_root . "/includes/db/module_settings_db.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 Running-Chart Entries"), false, false, "", $js);


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

if (isset($_GET['vehicle_id']))
{
    $_POST['vehicle_id'] = $_GET['vehicle_id'];
}

//function make_payment($id)
//{
//    $myrow = get_salary_advance_details($id);
//    
//    $account_codes = get_salary_advance_account_detail($myrow['type_id']);
//    if(!$account_codes){
//        display_error( _("Could not retrieve payment account details for this slary advance type. Not possible to make the payment."));
//    }
//    
//    if(($account_codes['debit_code'] == "" || $account_codes['credit_code'] == ""))
//    {
//        display_error( _("Account definition for this salary advance type is not complete. Not possible to make the payment."));
//
//    }
//    elseif($myrow['status_code'] == "D"){
//        display_error( _("Payment has been already processed for this salary advance."));
//    }
//    elseif($myrow['status_code'] != "A"){
//        display_error( _("This salary advance has not been approved."));
//    }
//    else{
//        pay_salary_advance($id, $_POST['asset_type'], $myrow['salary_advance'], 
//                        $account_codes['debit_code'], $account_codes['credit_code']);
//    }
//    
//}

function check_data($line)
{	
    if (!($line['vehicle_id'] > 0)) 
    {
        $message = ( _('Please select a vehicle.'));
        $set_focus = ('vehicle_id');
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    } 
    
    if (!(strlen($line['plate_no']) > 0)) 
    {
        $message = ( _('Please enter vehicle plate number.'));
        $set_focus = ('plate_no');
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    } 
    
    if (!($line['project_id'] > 0)) 
    {
        $message = ( _('Please select a project.'));
        $set_focus = ('project_id');
         return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    } 

//    $project_id = $line['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 (!($line['task_id'] > 0)) 
    {
        $message = ( _('Please select a task.'));
        $set_focus = ('task_id');
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    if (!($line['package_id'] > 0)) 
    {
        $message = ( _('Select a package.'));
        $set_focus = ('package_id');
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    } 
    
    if (!$line['hired'] && !($line['driver_id'] > 0)) 
    {
        $message = ( _('Select a driver.'));
        $set_focus = ('driver_id');
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    } 
    
    if (!is_date($line['start_date']))
   	{
            $message = ( _("Start date entered is not a valid date."));
            $set_focus = ('start_date');
             return array("success" => false, "focus_to" => $set_focus, "message" => $message);
   	}
        
    if (!is_date($line['end_date']))
   	{
            $message = ( _("End date entered is not a valid date."));
            $set_focus = ('end_date');
             return array("success" => false, "focus_to" => $set_focus, "message" => $message);
   	}
        
    if (date1_greater_date2($line['start_date'], $line['end_date']))
    {
        $message = ( _("Start date can not be greater than End date"));
        $set_focus = ('start_date');
         return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }     
            
    if(!is_time($line['start_time'])){
        $message = ( _("Start time is not in valid time format"));
        $set_focus = ('start_time');
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    if(!is_time($line['end_time'])){
        $message = ( _("End time is not in valid time format"));
        $set_focus = ('end_time');
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }        
    
    if($line['start_date'] == $line['end_date'] && $line['start_time'] > $line['end_time'])
    {
        $message = ( _("Start time can not be greater than End time"));
        $set_focus = ('start_time');
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);            
    }  
    
    if (!$line['hired'] && check_num2($line['meter_start'], 0) == false)
   	{
            $message = ( _("Meter Start must be a numeric value and can not be a negative value."));
            $set_focus = ('meter_start');
             return array("success" => false, "focus_to" => $set_focus, "message" => $message);
   	}
        
    if (!$line['hired'] && check_num2($line['meter_end'], 0) == false)
   	{
            $message = ( _("Meter End must be a numeric value and can not be a negative value."));
            $set_focus = ('meter_end');
             return array("success" => false, "focus_to" => $set_focus, "message" => $message);
   	}   
        
    if (check_num2($line['cost'], 0) == false)
   	{
            $message = ( _("Cost must be a numeric value and can not be a negative value."));
            $set_focus = ('cost');
             return array("success" => false, "focus_to" => $set_focus, "message" => $message);
   	} 
        
 

        

        
        
  
        
         return array("success" => true, "message" => "");   
}


function can_delete_running_chart_entry($vrc_id)
{	
    $vrce = get_vehicle_running_chart_record($vrc_id);
    if (!(isset($vrce['id']) && $vrce['id'] > 0)) 
    {
        display_error( _('No record found.'));
        set_focus('');
        return false;
    } 
    
    if ($vrce['batch_no'] != 0) 
    {
        display_error( _('This vehicle running chart entry has been posted. It can not be deleted.'));
        set_focus('');
        return false;
    } 
    
    if ($vrce['payment_source_no'] != 0) 
    {
        display_error( _('This vehicle running chart entry has a payment assiciated with it. It can not be deleted.'));
        set_focus('');
        return false;
    } 
    
    return true;
}
//--------------------------------------------------------------------------------------------------

        
function add_running_chart_entry($line)
{
    $cd = check_data($line);
    if($cd["success"] !== true) 
    {          
        return array("success" => false, "message" => $cd["message"]);
    }

    if(isset($line['vehicle_allocation_id']) && $line['vehicle_allocation_id'] == -1){
        $vehicle_allocation_id = 0;
    }
    else{
        $vehicle_allocation_id = $line['vehicle_allocation_id'];
    }
    
    if(isset($line['driver_id']) && $line['driver_id'] > 0){
        $driver_id = $line['driver_id'];
    }
    else{
        $driver_id = 0;
    }
    
    if(isset($line['supplier_id']) && $line['supplier_id'] > 0){
        $supplier_id = $line['supplier_id'];
    }
    else{
        $supplier_id = 0;
    }
   
    $start_date_time['start_date_time'] = date2sql($line['start_date'])." ".$line['start_time'];
    $end_date_time['end_date_time'] = date2sql($line['end_date'])." ".$line['end_time'];

    $rec_id = add_vehicle_running_chart_entry($vehicle_allocation_id, $line['project_id'], 
                                                $line['task_id'], $line['package_id'], $line['vehicle_id'], 
                                                $line['plate_no'], $start_date_time['start_date_time'], 
                                                input_num2($line['meter_start']), $end_date_time['end_date_time'], 
                                                input_num2($line['meter_end']), $line['bill_name'], 
                                                $line['passengers'], $line['route'], 
                                                $driver_id, input_num2($line['cost']), 
                                                $supplier_id, $line['comment']);                                                     

    if($rec_id > 0){
        return array("success" => true, "trans_no" => $rec_id, "message" => "Vehicle running chart entry $rec_id has been added.");
    }
    else{
        return array("success" => false, "message" => "Vehicle running chart entry could not be added.");
    }
}


function add_running_chart_entry_and_close_va($Mode, $selected_id)
{

    $iou_msg = add_running_chart_entry($Mode, $selected_id);
    if($iou_msg["success"] !== true){
        if(isset($iou_msg["focus_to"])){
            set_focus($iou_msg["focus_to"]);
        }
        return $iou_msg;
    }
    else{
        $rce_id = $iou_msg["trans_no"];
    }    

    close_vehicle_allocation(get_post('vehicle_allocation_id'));

    return array("success" => true, "trans_no" => $rce_id, "message" => "Vehicle  running chart entry $rce_id has been created and allocation ".get_post('vehicle_allocation_id')." has been closed.");
}

function update_running_chart_entry($line)
{
    $cd = check_data($line);
    if($cd["success"] !== true) 
    {          
        return array("success" => false, "message" => $cd["message"]);
    }

    if(isset($_POST['vehicle_allocation_id']) && $line['vehicle_allocation_id'] == -1){
        $vehicle_allocation_id = 0;
    }
    else{
        $vehicle_allocation_id = $line['vehicle_allocation_id'];
    }
    
    if(isset($line['driver_id']) && $line['driver_id'] > 0){
        $driver_id = $line['driver_id'];
    }
    else{
        $driver_id = 0;
    }
    
    if(isset($line['supplier_id']) && $line['supplier_id'] > 0){
        $supplier_id = $line['supplier_id'];
    }
    else{
        $supplier_id = 0;
    }
    
    $rce_id = $line['vehicle_rce_id'];
    
    $start_date_time['start_date_time'] = date2sql($line['start_date'])." ".$line['start_time'];
    $end_date_time['end_date_time'] = date2sql($line['end_date'])." ".$line['end_time'];

    $recs = update_vehicle_running_chart_entry($rce_id, $vehicle_allocation_id, 
                                                $line['project_id'], $line['task_id'],$line['package_id'],
                                                $line['vehicle_id'], $line['plate_no'], 
                                                $start_date_time['start_date_time'], input_num2($line['meter_start']), 
                                                $end_date_time['end_date_time'],input_num2($line['meter_end']),
                                                $line['bill_name'], $line['passengers'],
                                                $line['route'], $driver_id, input_num2($line['cost']), 
                                                $supplier_id, $line['comment']);                                                                                         

    
    if($recs == 1){
        return array("success" => true, "trans_no" => $rce_id, "message" => "Vehicle running chart entry $rce_id has been updated.");
    }
    else{
        return array("success" => false, "message" => "Vehicle running chart entry $rce_id could not be updated.");
    }
}


function update_running_chart_entry_and_close_va($Mode, $selected_id)
{
    $iou_msg = update_running_chart_entry($Mode, $selected_id);
    if($iou_msg["success"] !== true){
        if(isset($iou_msg["focus_to"])){
            set_focus($iou_msg["focus_to"]);
        }
        return $iou_msg;
    }

    close_vehicle_allocation(get_post('vehicle_allocation_id'));

    return array("success" => true, "trans_no" => $selected_id, "message" => "Vehicle running chart entry $selected_id has been updated and allocation ".get_post('vehicle_allocation_id')." has been closed.");
}

function clear_data()
{
    //    $_POST['plate_no'] = $asset['asset_serial'];
//    $_POST['id'] = "";
//    $_POST['vehicle_id'] = "";
//    $_POST['start_date'] = "";
//    $_POST['start_time'] = "";
//    $_POST['meter_start'] = "";
//    $_POST['end_date'] = "";
//    $_POST['end_time'] = "";
//    $_POST['meter_end'] = "";  
//    $_POST['bill_name'] = "";
//    $_POST['passengers'] = "";
//    $_POST['route'] = "";
//    $_POST['driver'] = "";
//    $_POST['cost'] = "";
    
        
}

function display_vehicle_running_chart_edit_cotrols($Mode, $selected_id)
{

    $vehicle = get_vehicle($_POST['vehicle_id']);

    $_POST['project_description'] = '';
    $_POST['task_description'] = '';
    $_POST['vehicle_allocation_description'] = '';
    
    if ($Mode =='Edit') 
    {
        $myrow = get_vehicle_running_chart_entry($selected_id);

        $_POST['id'] = $myrow["id"];
        
        if($myrow["vehicle_allocation_id"] > 0){
            $link = $a = get_trans_view_str(ST_VEHICLE_ALLOCATION, $myrow["vehicle_allocation_id"], $myrow["vehicle_allocation_id"]);;
            $t = $link." (from ".substr($myrow['from_date_time'],0,16)." - to ".substr($myrow['to_date_time'],0,16).")";
        }
        else{
            $t = "";
        }
        $_POST['vehicle_allocation_description'] = $t;
        $_POST['project_id'] = $myrow["project_id"];
        $_POST['project_description'] = $myrow["project_description"];
        
        $_POST['task_id'] = $myrow["task_id"];
        $_POST['task_description'] = $myrow["task_description"];
        
        $_POST['package_id'] = $myrow["package_id"];
        $_POST['vehicle_id'] = $myrow["vehicle_id"];
        $_POST['plate_no'] = $myrow['plate_no'];
        
        $_POST['start_date'] = sql2date($myrow["start_date_time"]);
        $_POST['start_time'] = sql2time($myrow["start_date_time"]);   
        
        $_POST['end_date'] = sql2date($myrow["end_date_time"]);
        $_POST['end_time'] = sql2time($myrow["end_date_time"]);
        
        $_POST['meter_start'] = $myrow["meter_start"];
        $_POST['meter_end'] = $myrow["meter_end"];    
        $_POST['bill_name'] = $myrow["bill_name"];    
        $_POST['passengers'] = $myrow["passengers"];    
        $_POST['route'] = $myrow["route"];    
        $_POST['driver_id'] = $myrow["driver_id"];    
        $_POST['cost'] = $myrow["cost"];    
        
        $_POST['comment'] = $myrow["comment"];  
        
        if(!(isset($_POST['supplier_id']) && $_POST['supplier_id'] > 0)){
            $_POST['supplier_id'] = $myrow["supplier_id"];  
        }
    
        if(!(isset($_POST['vehicle_allocation_id']) && $_POST['vehicle_allocation_id'] > 0)){
            $_POST['vehicle_allocation_id'] = $myrow["vehicle_allocation_id"];    
            
        }

        hidden('id', $_POST['id']); 
    }
    

    if(list_updated('vehicle_allocation_id') && $_POST['vehicle_allocation_id'] > 0){
        $vehicle_allocation = get_vehicle_allocation($_POST['vehicle_allocation_id']);
        $_POST['project_id'] = $vehicle_allocation["project_id"];
        $_POST['task_id'] = $vehicle_allocation["task_id"];
        $_POST['package_id'] = $vehicle_allocation["package_id"];
        $_POST['cost'] = $vehicle_allocation["amount"];
    }
    elseif(!isset($_POST['project_id']) && isset($_POST['vehicle_allocation_id']) && $_POST['vehicle_allocation_id'] > 0){
        $vehicle_allocation = get_vehicle_allocation($_POST['vehicle_allocation_id']);
        $_POST['project_id'] = $vehicle_allocation["project_id"];
        $_POST['task_id'] = $vehicle_allocation["task_id"];
        $_POST['package_id'] = $vehicle_allocation["package_id"];
    }

    if(list_updated('package_id') && $_POST['package_id'] > 0){
        $package_cost = get_vehicle_package_cost($_POST['package_id']);
        $_POST['cost'] = $package_cost;
    }


    if(!isset($_POST['vehicle_allocation_id'])){
        $_POST['vehicle_allocation_id'] = -1;
    }

    if(!isset($_POST['project_id'])){
        $_POST['project_id'] = -1;
    }

    if(!isset($_POST['plate_no']) || $_POST['plate_no'] == '' || list_updated('vehicle_id')){
        $_POST['plate_no'] = $vehicle['plate_number'];
    }

    br();

    hidden('selected_id', $selected_id);

    start_table(TABLESTYLE2);

//    if(isset($_POST['status_code']) && $_POST['status_code'] == "A"){
//        label_row("Start Date:", $_POST['start_date']);
//        label_row('Start Time:', $_POST['start_time']);
//        label_row("Milage Meter Start:", $_POST['meter_start']);
//        label_row('End Date:', $_POST['end_date']);
//        label_row('End Time:', $_POST['end_time']);
//        label_row('Milage Meter End:', $_POST['meter_end']);
//    }
//    else{
    if($vehicle['hired']){
        text_row("Plate Number:", 'plate_no', $_POST['plate_no'], 20, 20);
    }
    else{
        label_row("Plate Number:", $_POST['plate_no']);
        hidden("plate_no", $_POST['plate_no']);
    }
    //    asset_list_row(_("Select a Vehicle:"), 'vehicle_id', null,_('Select a vehicle'), true, AT_VEHICLE, check_value('show_inactive'));  
        
    if($selected_id > 0){
        label_row("Vehicle Allocation:", $_POST['vehicle_allocation_description']);
        label_row("Project:", $_POST['project_description']);
        label_row("Budget:", $_POST['task_description']);
        

        hidden("vehicle_allocation_id", $_POST['vehicle_allocation_id']);
        hidden("project_id", $_POST['project_id']);
        hidden("task_id", $_POST['task_id']);

    }
    else{                        
        vehicle_allocations_list_row("Vehicle Allocation", 'vehicle_allocation_id', null, "", true);
        if($_POST["vehicle_allocation_id"] > 0){
            $vehicle_allocation = get_vehicle_allocation($_POST['vehicle_allocation_id']);
            $va_project = get_project_record($vehicle_allocation['project_id']);
            label_row("Project:", $va_project['description']);
            hidden("project_id", $va_project['project_id']);
            
//            $va_task = get_task_record($vehicle_allocation['task_id']);
//            label_row("Budget:", $va_task['description']);
//            hidden("task_id", $va_task['task_id']);
        }
        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'));     
        
    }
    
    vehicle_packages_list_row("Package:", "package_id", null, "Select a package", true);
    if($vehicle['hired']){
        hidden("driver_id", 0);
    }
    else{
        drivers_list_row("Driver:", 'driver_id', null, "Select a driver");
    }
        date_row("Start Date:", "start_date", null);
        time_row("Start Time (24 hr): ", "start_time", null, 5); 
    //    label_row("", " ");
        date_row("End Date:", "end_date", null);
        time_row("End Time (24 hr): ", "end_time", null, 5);
    
        amount_row("Milage Meter Start:", 'meter_start', null, null, null, 0);   
        amount_row("Milage Meter End:", 'meter_end', null, null, null, 0);   

        if($vehicle['hired']){
            hidden("bill_name", "");
        }
        else{
            text_row("Bill Details:", 'bill_name', null, 50, 200);
        }

        text_row("Passengers:", 'passengers', null, 50, 200);
        text_row("Route:", 'route', null, 50, 500);
//        text_row("Driver", 'driver', null, null, null);
        amount_row("Cost:", 'cost');      
        supplier_list_row("Supplier", 'supplier_id', null, '');
        textarea_row('Comments:', 'comment', null, 35, 2); 

    //}
    end_table(1);
    
}

function display_open_vehicle_allocations($vehicle_id)
{
    $result = get_open_vehicle_allocations($vehicle_id);   

    start_form();
    
    display_heading2("Open Vehicle Allocations");
//    br();
    
    start_table(TABLESTYLE, "width=99%");
    $th = array(_('VA #'), _("Package"),  _("Vehicle"), "H/V Plate No", "Driver",_('From Date'),
                _('From Time'),_('To Date'), "To Time", "Cost", 
                 ""); 
//"Meter Start", "Meter End", "Route"
    table_header($th);
    $k = 0; //row colour counter

    while ($myrow = db_fetch($result))
    {
        $prefix = "va_".$myrow["id"]."_";
        
        alt_table_row_color($k);
        $a = get_trans_view_str(ST_VEHICLE_ALLOCATION, $myrow['id'],$myrow['id']);
        label_cell($a, "align=center");
        

        
//        label_cell("");
        $text = "Project: <b>".$myrow["project_description"]."</b>".spaces(10);
        $text .="Budget: <b>".$myrow["task_description"]."</b>".spaces(10);
        
        $text .="Route: ".$myrow["route"]."<b></b>".spaces(10);
        $text .="Passenagers: <b>".$myrow["passengers"]."</b>".spaces(10);
        $text .="Cost: <b>".$myrow["cost"]."</b>".spaces(10);
        $text .="Comment: <b>".$myrow["comment"]."</b>".spaces(10);
        label_cell($text, "colspan=9");
        label_cell("");
        
//        hidden($prefix.'package_id', $myrow['package_id']);
//        hidden($prefix.'plate_no', $myrow['plate_number']);
//            label_cell($myrow["id"]);
        end_row();
            
//        $k--;
        alt_table_row_color($k);
//        start_row();
        

//        label_cell($myrow["project_description"]);
        label_cell("");   
        
//        $_POST[$prefix.'package_id'] = $myrow['package_id'];
//        vehicle_packages_list_cells(null, $prefix.'package_id');

        if(list_updated('vehicle_id') || !isset($_POST[$prefix.'package_id'])){
            $_POST[$prefix.'package_id'] = $myrow['package_id'];
        }
        vehicle_packages_list_cells(null, $prefix.'package_id', null, false, true);
        
        if(!(isset($_POST[$prefix.'vehicle_id']) && $_POST[$prefix.'vehicle_id'] > 0)){
            $_POST[$prefix.'vehicle_id'] = $myrow['vehicle_id'];
        }
        vehicles_list_cells(null, $prefix.'vehicle_id', null, null, true);
        
        $vehicle = get_vehicle($_POST[$prefix.'vehicle_id']);
        
        
        if($vehicle['hired'] > 0){
            text_cells(null, $prefix.'hired_vehicle_plate_no', $vehicle['plate_number'], 10);
        }
        else{
            label_cell($vehicle['plate_number']);
        }
        
        hidden($prefix.'hired', $vehicle['hired'] == 1 ? 1 : 0);
        hidden($prefix.'plate_no', $vehicle['plate_number']);        
        
        $_POST[$prefix.'driver_id'] = $myrow['driver_id'];
        drivers_list_cells(null, $prefix.'driver_id', null, '');
        
        $_POST[$prefix.'start_date'] = sql2date($myrow['from_date_time']);
        date_cells(null, $prefix.'start_date');
        
        $_POST[$prefix.'start_time'] = substr($myrow['from_date_time'], 11, 5);
        time_cells(null, $prefix.'start_time', null, 5);
        
        $_POST[$prefix.'end_date'] = sql2date($myrow['to_date_time']);
        date_cells(null, $prefix.'end_date');
        
        $_POST[$prefix.'end_time'] = substr($myrow['to_date_time'], 11, 5);
        time_cells(null, $prefix.'end_time', null, 5);
        
        if(list_updated('vehicle_id')){
            $_POST[$prefix.'cost'] = $myrow['cost'];
        }
        if(list_updated($prefix.'package_id')){
            $package_cost = get_vehicle_package_cost($_POST[$prefix.'package_id']);
            $_POST[$prefix.'cost'] = $package_cost;
        }
        amount_cells(null, $prefix.'cost');
        
        end_row();
            
//        $k--;
        alt_table_row_color($k);
        label_cell("");
        label_cell("Supplier:", "align=right");
        echo "<td>".
        supplier_list($prefix.'supplier_id', null, '')
        ."</td>";
        
        
        label_cell("Route:", "align=right");
        
        $_POST[$prefix.'route'] = $myrow['route'];
        text_cells(null, $prefix.'route', $myrow['route']);

        label_cell("Meter Start:", "align=right");
        
        
        if(list_updated('vehicle_id') || !isset($_POST[$prefix.'meter_start'])){
            $_POST[$prefix.'meter_start'] = 0;
        }
        amount_cells_ex(null, $prefix.'meter_start', 10, 10, null, null, null, 0);
        
        label_cell("Meter End:", "align=right");
        if(list_updated('vehicle_id') || !isset($_POST[$prefix.'meter_end'])){
            $_POST[$prefix.'meter_end'] = 0;
        }
        amount_cells_ex(null, $prefix.'meter_end', 10, 10, null, null, null, 0);
        

        
        $_POST[$prefix.'passengers'] = $myrow['passengers'];
//        text_cells(null, $prefix.'passengers', $myrow['passengers']);
        hidden($prefix.'passengers', $myrow['passengers']);
        
        label_cell("");
        check_cells(null, $prefix.'check_va_item');

//        edit_button_cell("Edit".$myrow["id"], _("Edit"));    
//        delete_button_cell("Delete".$myrow["id"], _("Delete"));
        
        

        end_row();
        
        start_row();
        label_cell("");
        label_cell("-");
        label_cell("", "colspan=7 align=center");
        label_cell("-", "align=right");
        label_cell("");

        end_row();
    }
    //inactive_control_row($th);
    end_table(1);
}



function display_open_running_chart_entries()
{
    $result = get_vehicle_running_chart_entries($_POST['vehicle_id']);
    
    div_start('price_table');
    
    if (db_num_rows($result) == 0)
    {
    	display_note(_("There are no Vehicle running chart entries for the selected vehicle"));
        return;
    }

    display_heading2("Open Running Chart Entries");
//    br();
    
    start_table(TABLESTYLE, "width=99%");

    $th = array(_('#'), _("Package / Vehicle"), "H/V Plate No", "Driver",_('From Date'),
            _('From Time'),_('To Date'), "To Time", "Cost", 
            "Meter Start", "Meter End", "Route", "", "", ""); 

    table_header($th);

    $k = $j = 0; //row colour counter

    while ($myrow = db_fetch($result))
    {
        $prefix = "rce_".$myrow["id"]."_";
        
        alt_table_row_color($k);
        label_cell($myrow["id"], "align=center");
//        label_cell($prefix, "align=center");
        
        if(list_updated('vehicle_id') || !isset($_POST[$prefix.'package_id'])){
            $_POST[$prefix.'package_id'] = $myrow['package_id'];
        }
        vehicle_packages_list_cells(null, $prefix.'package_id', null, false, true);
        
//        label_cell("");
        $vehicle_allocation_id = '';
        if($myrow["vehicle_allocation_id"] > 0){
            $vehicle_allocation_id = $myrow["vehicle_allocation_id"];
        }
        $a = get_trans_view_str(ST_VEHICLE_ALLOCATION, $vehicle_allocation_id, $vehicle_allocation_id);
        $text = "VA #: ".$a.spaces(10);
        $text .= "Project: <b>".$myrow["project_description"]."</b>".spaces(10);
        $text .="Budget: <b>".$myrow["task_description"]."</b>".spaces(10);
        
        $text .="Route: <b>".$myrow["route"]."</b>".spaces(10);
        $text .="Passenagers: <b>".$myrow["passengers"]."</b>".spaces(10);
        $text .="Cost: <b>".$myrow["cost"]."</b>".spaces(10);
        $text .="Comment: <b>".$myrow["comment"]."</b>".spaces(10);
        label_cell($text, "colspan=10");
        label_cell("");
        label_cell("");
        label_cell("");
        
//        hidden($prefix.'package_id', $myrow['package_id']);
//        hidden($prefix.'plate_no', $myrow['plate_number']);
//            label_cell($myrow["id"]);
        end_row();
            
//        $k--;
        alt_table_row_color($k);
//        start_row();
        

//        label_cell($myrow["project_description"]);
        label_cell("");   
        
//        $_POST[$prefix.'package_id'] = $myrow['package_id'];
//        vehicle_packages_list_cells(null, $prefix.'package_id');

        if(list_updated('vehicle_id') || $_POST['selected_id'] == $myrow["id"]){
            $_POST[$prefix.'cost'] = $myrow['cost'];
            $_POST[$prefix.'driver_id'] = $myrow['driver_id'];
            $_POST[$prefix.'start_date'] = sql2date($myrow['start_date_time']);
            $_POST[$prefix.'start_time'] = substr($myrow['start_date_time'], 11, 5);
            $_POST[$prefix.'end_date'] = sql2date($myrow['end_date_time']);
            $_POST[$prefix.'end_time'] = substr($myrow['end_date_time'], 11, 5);
            $_POST[$prefix.'route'] = $myrow['route'];
            $_POST[$prefix.'passengers'] = $myrow['passengers'];
            $_POST[$prefix.'meter_start'] = $myrow['meter_start'];
             $_POST[$prefix.'meter_end'] = $myrow['meter_end'];
        }
        
        $_POST[$prefix.'vehicle_id'] = $myrow['vehicle_id'];
        vehicles_list_cells(null, $prefix.'vehicle_id');
        
        text_cells(null, $prefix.'hired_vehicle_plate_no', $myrow['plate_number'], 10);
        hidden($prefix.'plate_no', $myrow['plate_number']);
        hidden($prefix.'hired', $myrow['hired']);
        
        
        drivers_list_cells(null, $prefix.'driver_id', null, '');
        
        date_cells(null, $prefix.'start_date');
        
        time_cells(null, $prefix.'start_time', null, 5);
        
        date_cells(null, $prefix.'end_date');
        
        time_cells(null, $prefix.'end_time', null, 5);
        
        if(list_updated($prefix.'package_id')){
            $package_cost = get_vehicle_package_cost($_POST[$prefix.'package_id']);
            $_POST[$prefix.'cost'] = $package_cost;
        }

        amount_cells(null, $prefix.'cost');
        
        amount_cells_ex(null, $prefix.'meter_start', 10, 10, null, null, null, 0);
        
        amount_cells_ex(null, $prefix.'meter_end', 10, 10, null, null, null, 0);
        
        text_cells(null, $prefix.'route', $myrow['route']);
        
        
//        text_cells(null, $prefix.'passengers', $myrow['passengers']);
        hidden($prefix.'passengers', $myrow['passengers']);
        
        check_cells(null, $prefix.'check_rce_item');

        edit_button_cell("Edit".$myrow["id"], _("Edit"));    
        delete_button_cell("Delete".$myrow["id"], _("Delete"));
        
        

        end_row();
        
        start_row();
        label_cell("");
        label_cell("-");
        label_cell("", "colspan=9 align=center");
        label_cell("-", "align=right");
        label_cell("");
        label_cell("");

        end_row();
    }
    //inactive_control_row($th);
    end_table();
    
    div_end();
}

function display_open_running_chart_entries2()
{
    $result = get_vehicle_running_chart_entries($_POST['vehicle_id']);
    
    div_start('price_table');
    
    if (db_num_rows($result) == 0)
    {
    	display_note(_("There are no Vehicle running chart entries for the selected vehicle"));
        return;
    }

    display_heading2("Open Running Chart Entries");
//    br();
    
    start_table(TABLESTYLE, "width=99%");

    $th = array(_('#'), "VA",_("Package"), "Plate No", "Driver",_('From Date'),
            _('To Date'),  "Cost", 
            "Meter Start", "Meter End", "Route", "Passengers", "Supplier", "", ""); 

    table_header($th);

    $k = $j = 0; //row colour counter

    while ($myrow = db_fetch($result))
    {
        $prefix = "rce_".$myrow["id"]."_";
        
        alt_table_row_color($k);
        $v = get_trans_view_str(ST_VEHICLE_RUNNING_CHART, $myrow["id"]);
        label_cell($v, "align=center");
        
        $vehicle_allocation_id = '';
        if($myrow["vehicle_allocation_id"] > 0){
            $vehicle_allocation_id = $myrow["vehicle_allocation_id"];
        }
        $a = get_trans_view_str(ST_VEHICLE_ALLOCATION, $vehicle_allocation_id, $vehicle_allocation_id);
        label_cell($a);

        
        label_cell($myrow['package_description']);
//        label_cell($myrow['vehicle_description']);
        label_cell($myrow['plate_no']);
        label_cell($myrow['driver_name']);
        label_cell(substr($myrow['start_date_time'],0,16));
        label_cell(substr($myrow['end_date_time'],0,16));
        amount_decimal_cell($myrow['cost']);
        qty_cell($myrow['meter_start'], false, 1);
        qty_cell($myrow['meter_end'], false, 1);
        label_cell($myrow['route']);
        label_cell($myrow['passengers']);
        label_cell($myrow['supp_name']);
        
//        check_cells(null, $prefix.'check_rce_item');
        edit_button_cell("Edit".$myrow["id"], _("Edit"));    
        delete_button_cell("Delete".$myrow["id"], _("Delete"));
    }

    end_table();
    
    div_end();
}


function build_rce_line_array($rce_id = 0)
{
    $line = array();

    if($rce_id > 0){
        
    }
    else{
        $rce_id = 0;
    }
    $line['vehicle_id'] = $_POST['vehicle_id'];
    $line['vehicle_allocation_id'] = $_POST["vehicle_allocation_id"];
    $line['vehicle_rce_id'] = $rce_id;
    $line['start_date'] = $_POST['start_date'];
    $line['start_time'] = $_POST['start_time'];
    $line['end_date'] = $_POST['end_date'];
    $line['end_time'] = $_POST['end_time'];
    $line['plate_no'] = $_POST['plate_no'];
    $line['project_id'] = $_POST['project_id'];
    $line['task_id'] = $_POST['task_id'];
    $line['package_id'] = $_POST['package_id'];
    $line['vehicle_id'] = $_POST['vehicle_id'];
    
    $vehicle = get_vehicle($line['vehicle_id']);
    if($vehicle){
        $line['hired'] = $vehicle['hired'];
    }
    
    if($line['hired'] ){
        $line['driver_id'] = 0;
    }
    else{
        $line['driver_id'] = $_POST['driver_id'];
    }

    $line['meter_start'] = $_POST['meter_start'];
    $line['meter_end'] = $_POST['meter_end'];
    $line['bill_name'] = $_POST['bill_name'];
    $line['cost'] = $_POST['cost'];
    
    $line['passengers'] = $_POST['passengers'];
    $line['route'] = $_POST['route'];
    $line['supplier_id'] = $_POST['supplier_id'];
    
    $line['comment'] = $_POST['comment'];

    return $line;
}

function build_va_array($vehicle_id)
{
    $data = array();
    
    $result = get_open_vehicle_allocations($vehicle_id);   

    while ($myrow = db_fetch($result))
    {
        $line = array();
        
        $prefix = "va_".$myrow["id"]."_";
        
        if(!(isset($_POST[$prefix.'check_va_item']) && $_POST[$prefix.'check_va_item'] > 0)){
            continue;
        }
        
        $line['vehicle_allocation_id'] = $myrow["id"];
        $line['vehicle_request_id'] = $myrow["vehicle_request_id"];
        $line['start_date'] = $_POST[$prefix.'start_date'];
        $line['start_time'] = $_POST[$prefix.'start_time'];
        $line['end_date'] = $_POST[$prefix.'end_date'];
        $line['end_time'] = $_POST[$prefix.'end_time'];
        $line['project_id'] = $myrow['project_id'];
        $line['task_id'] = $myrow['task_id'];
        $line['package_id'] = $_POST[$prefix.'package_id'];
        $line['vehicle_id'] = $_POST[$prefix.'vehicle_id'];
        
        $vehicle = get_vehicle($line['vehicle_id']);
        $line['hired'] = $vehicle['hired'];
        
        if($line['hired'] ){
            $line['plate_no'] = $_POST[$prefix.'hired_vehicle_plate_no'];
        }
        else{
            $line['plate_no'] = $_POST[$prefix.'plate_no'];
        }
        $line['driver_id'] = $_POST[$prefix.'driver_id'];
        $line['cost'] = $_POST[$prefix.'cost'];
        $line['meter_start'] = $_POST[$prefix.'meter_start'];
        $line['meter_end'] = $_POST[$prefix.'meter_end'];
        $line['passengers'] = $_POST[$prefix.'passengers'];
        $line['route'] = $_POST[$prefix.'route'];
        $line['comment'] = $myrow['comment'];
        
        $line['supplier_id'] = $_POST[$prefix.'supplier_id'];
        $line['bill_name'] = '';

//        $line['meter_start'] = $_POST['meter_start'];
//        $line['meter_end'] = $_POST['meter_end'];
//        $line['bill_name'] = $_POST['bill_name'];
//        $line['cost'] = $_POST['cost'];

    
        $data[] = $line;
    }
    
    return $data;
}


function build_rce_array($vehicle_id)
{
    $data = array();
    
    $result = get_vehicle_running_chart_entries($vehicle_id); 

    while ($myrow = db_fetch($result))
    {
        $line = array();
        
        $prefix = "rce_".$myrow["id"]."_";
        
        if(!(isset($_POST[$prefix.'check_rce_item']) && $_POST[$prefix.'check_rce_item'] > 0)){
            continue;
        }
        
        $line['vehicle_rce_id'] = $myrow["id"];
        $line['vehicle_allocation_id'] = $myrow["vehicle_allocation_id"];
        $line['start_date'] = $_POST[$prefix.'start_date'];
        $line['start_time'] = $_POST[$prefix.'start_time'];
        $line['end_date'] = $_POST[$prefix.'end_date'];
        $line['end_time'] = $_POST[$prefix.'end_time'];
        $line['project_id'] = $myrow['project_id'];
        $line['task_id'] = $myrow['task_id'];
        $line['package_id'] = $myrow['package_id'];
        $line['vehicle_id'] = $_POST[$prefix.'vehicle_id'];      
        
        $vehicle = get_vehicle($line['vehicle_id']);
        $line['hired'] = $vehicle['hired'];        
        $line['driver_id'] = $_POST[$prefix.'driver_id'];    
    
        if($line['hired'] ){
            $line['plate_no'] = $_POST[$prefix.'hired_vehicle_plate_no'];
        }
        else{
            $line['plate_no'] = $vehicle['plate_no'];
        }

        $line['cost'] = $_POST[$prefix.'cost'];
        $line['meter_start'] = $_POST[$prefix.'meter_start'];
        $line['meter_end'] = $_POST[$prefix.'meter_end'];
        $line['passengers'] = $_POST[$prefix.'passengers'];
        $line['route'] = $_POST[$prefix.'route'];
        $line['supplier_id'] = $_POST[$prefix.'supplier_id'];
        $line['comment'] = $myrow['comment'];
    
        $line['bill_name'] = '';

//        $line['meter_start'] = $_POST['meter_start'];
//        $line['meter_end'] = $_POST['meter_end'];
//        $line['bill_name'] = $_POST['bill_name'];
//        $line['cost'] = $_POST['cost'];

    
        $data[] = $line;
    }
    
    return $data;
}


function add_rce_multiple($close = false)
{
    $count = 0;
    
    $data = build_va_array($_POST["vehicle_id"]);

    foreach ($data as $line) {        
        $cva = add_running_chart_entry($line);
        if($cva['success'] !== true){
            $set_focus = "";
            if(isset($cva['set_focus'])){
                $set_focus = $cva['set_focus'];
            }
            return array("success" => false, "set_focus" => $set_focus, "message" => "Vehicle Allocation ".$line["vehicle_allocation_id"]." - ".$cva['message']);
        }
        
        unset($_POST["va_".$line["vehicle_allocation_id"]."_check_va_item"]);
        $count++;
        
        if($close){
            close_vehicle_allocation($line["vehicle_allocation_id"]);
        }
    }
    
    if($count == 0){
        return array("success" => false, "set_focus" => "", "message" => "No Vehicle Running Chart entries created.");
    }
    else{
        return array("success" => true, "set_focus" => "", "message" => "$count Vehicle Running Chart entries created.");
    }
}

function close_va_multiple()
{
    $count = 0;
    
    $data = build_va_array($_POST["vehicle_id"]);

    foreach ($data as $line) {        

        $count++;

        close_vehicle_allocation($line["vehicle_allocation_id"]);
        
    }
    
    if($count == 0){
        return array("success" => false, "set_focus" => "", "message" => "No Vehicle Allocations closed.");
    }
    else{
        return array("success" => true, "set_focus" => "", "message" => "$count Vehicle Allocations closed.");
    }
}


//function update_rce_multiple($close = false)
//{
//    $count = 0;
//    
//    $data = build_rce_array($_POST["vehicle_id"]);
//
//    foreach ($data as $line) {        
//        $cva = update_running_chart_entry($line);
//        if($cva['success'] !== true){
//            $set_focus = "";
//            if(isset($cva['set_focus'])){
//                $set_focus = $cva['set_focus'];
//            }
//            return array("success" => false, "set_focus" => $set_focus, "message" => "Running Chart Entry :".$line["vehicle_rce_id"]." - ".$cva['message']);
//        }
//        
//        unset($_POST["rce_".$line["vehicle_rce_id"]."_check_rce_item"]);
//        
//        $count++;
//        
//        if($close){
//            close_vehicle_allocation($line["vehicle_allocation_id"]);
//        }
//    }
//    
//    if($count == 0){
//        return array("success" => false, "set_focus" => "", "message" => "No Vehicle Allocations updated.");
//    }
//    else{
//        return array("success" => true, "set_focus" => "", "message" => "$count Vehicle Allocations updated.");
//    }
//}
//


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

if(isset($_POST['Add_RCE_Multiple'])){
    $aiou = add_rce_multiple();
    if($aiou["success"] !== true){
        if(isset($aiou["focus_to"])){
            set_focus($aiou["focus_to"]);
        }
        display_error($aiou["message"]);
    }
    else{
        $Mode = 'RESET';
        display_notification($aiou["message"]);
    }

}  

if(isset($_POST['Add_RCE_Multiple_Close'])){
    $aiou = add_rce_multiple(true);
    if($aiou["success"] !== true){
        if(isset($aiou["focus_to"])){
            set_focus($aiou["focus_to"]);
        }
        display_error($aiou["message"]);
    }
    else{
        $Mode = 'RESET';
        display_notification($aiou["message"]);
    }

}  

if(isset($_POST['Close_VA_Multiple'])){
    $aiou = close_va_multiple();
    if($aiou["success"] !== true){
        if(isset($aiou["focus_to"])){
            set_focus($aiou["focus_to"]);
        }
        display_error($aiou["message"]);
    }
    else{
        $Mode = 'RESET';
        display_notification($aiou["message"]);
    }

} 

//
//if(isset($_POST['Update_RCE_Multiple'])){
//    $aiou = update_rce_multiple();
//    if($aiou["success"] !== true){
//        if(isset($aiou["focus_to"])){
//            set_focus($aiou["focus_to"]);
//        }
//        display_error($aiou["message"]);
//    }
//    else{
//        $Mode = 'RESET';
//        display_notification($aiou["message"]);
//    }
//
//}  

//if(isset($_POST['Update_RCE_Multiple_Close'])){
//    $aiou = update_rce_multiple(true);
//    if($aiou["success"] !== true){
//        if(isset($aiou["focus_to"])){
//            set_focus($aiou["focus_to"]);
//        }
//        display_error($aiou["message"]);
//    }
//    else{
//        $Mode = 'RESET';
//        display_notification($aiou["message"]);
//    }
//
//} 


if(isset($_POST['Add_RCE']))
{
    $line = build_rce_line_array();
    
    $rce = add_running_chart_entry($line);
    if($rce["success"] !== true){
        display_error($rce["message"]);
    }
    else{
        display_notification($rce["message"]);
        $selected_id = -1;
        $Mode = "RESET";
    }
}

if(isset($_POST['Add_RCE_Close_VA']))
{
    $rce = add_running_chart_entry_and_close_va($Mode, $selected_id);
    if($rce["success"] !== true){
        display_error($rce["message"]);
    }
    else{
        display_notification($rce["message"]);
        $selected_id = -1;
        $Mode = "RESET";
    }
}

if(isset($_POST['Update_RCE']))
{
    $line = build_rce_line_array($selected_id);
    
    $rce = update_running_chart_entry($line);
    if($rce["success"] !== true){
        display_error($rce["message"]);
    }
    else{
        display_notification($rce["message"]);
        $selected_id = -1;
        $Mode = "RESET";
    }
}

if(isset($_POST['Update_RCE_Close_VA']))
{
    $rce = update_running_chart_entry_and_close_va($Mode, $selected_id);
    if($rce["success"] !== true){
        display_error($rce["message"]);
    }
    else{
        display_notification($rce["message"]);
        $selected_id = -1;
        $Mode = "RESET";
    }
}


if ($Mode == 'Delete')
{
    if(can_delete_running_chart_entry($selected_id)){
        $recs = delete_vehicle_running_chart_entry($selected_id, $_POST['vehicle_id']);
        
        if($recs == 1){
                display_notification(_("Vehicle Running chart entry has been deleted."));
        }
        else{
                display_error(_("Vehicle Running chart entry could not be deleted."));
        }
        $Mode = 'RESET';
    }
}

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

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

global $Ajax;

if (isset($_POST['_selected_id_update']) )
{
    $selected_id = $_POST['selected_id'];
    $Ajax->activate('_page_body');
}

//if (list_updated('vehicle_id')) 
	$Ajax->activate('_page_body');
    $Ajax->activate('details');
//--------------------------------------------------------------------------------------------------

if (!@$_GET['popup'])
	start_form();

div_start('details');

//      asset_list_cells(_("Select a Vehicle:"), 'vehicle_id', null,
//                _('Selct a vehicle'), true, AT_VEHICLE, check_value('show_inactive'));    
      vehicles_list_cells("Select a Vehicle:", 'vehicle_id', null, ('Selct a vehicle'), true);
//      vehicle_allocations_list_cells("Vehicle Allocations", 'vehicle_allocation_id');
      
br(2);	

if(!($_POST['vehicle_id'] > 0)){
    display_note(_("Please select a vehicle to create entries"));
    br(2);
}
else{
    display_open_vehicle_allocations($_POST['vehicle_id']);

    submit_center_first('Add_RCE_Multiple', _("Create Running Chart Entries"), '', 'default');
    submit('Add_RCE_Multiple_Close', 'Create RCEs and Close Allocations', true, '', 'default');
    submit_center_last('Close_VA_Multiple', _("Close Vehicle Allocations"), '', 'default');

    br();

    display_open_running_chart_entries2();

    br();
    
//    submit_center_first('Update_RCE_Multiple', _("Update Running Chart Entries"), '', 'default');
//    submit('Update_RCE_Multiple_Close', 'Update RCEs and Close Allocations', true, '', 'default');
//
//    br(2);

    br();
    //-----------------------------------------------------------------------------------------------

    display_vehicle_running_chart_edit_cotrols($Mode, $selected_id);

    //if(isset($_POST['status_code']) && $_POST['status_code'] == "A"){
    //    submit("pay_salary_advance", "Pay",true, _('Pay Salary Advance'), 'default');
    //    submit('RESET', _("Cancel"), true, _('Cancel edition'), 'cancel');
    //}
    //else{
    //    submit_add_or_update_center($selected_id == -1, '', 'both');
    //}

    if($selected_id > 0)
    {
        submit_center_first('Update_RCE', _("Update"), '', 'default');
        submit('Update_RCE_Close_VA', 'Update and Close Allocation', true, '', 'default');
        submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
    //    
    //    br();
    //    submit_center_first('Back_To_IOU_Originator', "Back To Originator", '', 'default');
    //    submit_center_last('Reject_IOU', "Reject", '', 'default');
    }
    else{

        submit_center_first('Add_RCE', _("Add"), '', 'default');
        submit('Add_RCE_Close_VA', 'Add and Close Allocation', true, '', 'default');
    //    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
    }
}

div_end();

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