<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_POST_VEHICLE_RUNNING_CHART';
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_running_chart_entry_db.inc");
include_once($path_to_root . "/transport/includes/db/vehicle_allocation_db.inc");
include_once($path_to_root . "/assets/includes/db/assets_db.inc");

include_once($path_to_root . "/includes/db/module_settings_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 = "Post Vehicle Running Chart"));
//----------------------------------------------------------------------------------------
simple_page_mode(true);
//
//if (isset($_GET['vehicle_id']))
//{
//    $_POST['vehicle_id'] = $_GET['vehicle_id'];
//}




function validate_post_vehicle_running_chart_entries()
{	
   $result = get_unposted_vehicle_running_chart_entries($_POST['from_date'], $_POST['to_date'], $_POST['vehicle'],  $_POST['supplier_id'], true);
    $updates_count_1 = 0;
    
    while ($row = db_fetch($result))
    {
        if((isset($_POST["selected_".$row["id"]])) &&
                ($_POST["selected_".$row["id"]] == true))
        {
            if($result == true)
            {
                $updates_count_1++;
            }
            else{
                return false;
            }
        }
   
    }
  
    if($updates_count_1 == 0)
    {
        display_error(_("There are no lines selected."));
        return false;
    }
    
    return true;  
}
//--------------------------------------------------------------------------------------------------

        
function post_vehicle_running_chart_entries()
{
    if(!validate_post_vehicle_running_chart_entries()){
        return;
    }
    
    $task_costs_array = array();
    $count = 0;
    
    $result = get_unposted_vehicle_running_chart_entries($_POST['from_date'], $_POST['to_date'], $_POST['vehicle'],  $_POST['supplier_id'], true);
    
    begin_transaction();
    $batch_no = get_vehicle_running_chart_next_batch_no();
        
    while ($a_row = db_fetch($result))
    {
        if((isset($_POST["selected_".$a_row["id"]])) &&
                ($_POST["selected_".$a_row["id"]] == true))
        {
            $count++;
            
            $n = update_vehicle_running_chart_next_batch_no($batch_no ,$a_row["id"]);
            if($n != 1){
                cancel_transaction();
                return array("success" => false, "tran_no" => $batch_no, "message" => "Vehicle running chart record ".$a_row["id"]." has been updated by another user.");
            }

            $task_cost_line = array("task_id" => $a_row['task_id'], "cost" => $a_row["cost"], "batch_no"=>$batch_no);
            $task_costs_array[]= $task_cost_line;

        }
              
    }

    if($count == 0){
        cancel_transaction();
        return array("success" => false, "tran_no" => $batch_no, "message" => "No records selected.");
    }
    
    $msg = charge_transport_costs_to_tasks($task_costs_array);
    if($msg['success'] !== true)
    {
        cancel_transaction();
        return array("success" => false, "tran_no" => $batch_no, "message" => $msg['message']);
    }

    commit_transaction();
    return array("success" => true, "tran_no" => $batch_no, "message" => ""); 
     
}

function charge_transport_costs_to_tasks($batch_task_costs)
{
    $batch_no = $batch_task_costs[0]["batch_no"];
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    foreach ($batch_task_costs as $task_cost) {          

//        $a['row_id'] = $myrow['id'];
//        $a['task_id'] = $myrow['task_id'];
//        $a['amount'] = $myrow['amount'];
//        $task_costs_summary[] = $a;
     
        add_to_task_cost($task_costs_summary, $task_cost['task_id'], $task_cost['cost'], $task_cost['cost'], $task_cost['cost']);

    }
    
    get_task_cost_details($task_costs_summary);

    $cct_msg = charge_cost_to_tasks(ST_VEHICLE_RUNNING_CHART_BATCH, $batch_no, 
                    $task_costs_summary, $current_user_id);

    if($cct_msg['success'] !== true)
    {
        cancel_transaction();
        return array("success" => $cct_msg['success'], "tran_no" => $batch_no, "message" => $cct_msg['message']);
    }
        
    return array("success" => true, "tran_no" => $batch_no, "message" => "");
}

function display_open_running_chart_entries(){
    
    br();	

    $result = get_unposted_vehicle_running_chart_entries($_POST['from_date'], $_POST['to_date'], $_POST['vehicle'],  $_POST['supplier_id']);
    
    div_start('price_table');
    
    if (db_num_rows($result) == 0)
    {
    	display_note(_("There are no Vehicle running chart entries for the selected vehicle"));
    }
    else
    {
        start_table(TABLESTYLE, "width=98%");

        $th = array(_("Id"), _("Allo. Id"), _("Project"),_("Vehicle"), _("Plate No"),
                    _("Start Date Time"), _("End Date Time"),
                    _("Bill Details"),_("Passengers"),_("Route"),
                    _("Driver"),_("Cost"),"Supplier", "");

        table_header($th);

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

        while ($myrow = db_fetch($result))
        {
            alt_table_row_color($k);

            label_cell($myrow["id"]);
            
            $vehicle_allocation_id = '';
            if($myrow["vehicle_allocation_id"] > 0){
                $vehicle_allocation_id = $myrow["vehicle_allocation_id"];
            }
            label_cell($vehicle_allocation_id, "align=center");            
            label_cell($myrow["project_description"]); 
            label_cell($myrow["vehicle_description"]); 
            label_cell($myrow["plate_no"]); 
            label_cell(substr($myrow["start_date_time"],0,16), "align=center");          
            label_cell(substr($myrow["end_date_time"],0,16), "align=center");   
//            qty_cell($myrow["meter_start"], false, 0);
//            qty_cell($myrow["meter_end"], false, 0); 
            label_cell($myrow["bill_name"]); 
            label_cell($myrow["passengers"]); 
            label_cell($myrow["route"]); 
            label_cell($myrow["driver_name"]); 
            amount_decimal_cell($myrow["cost"]); 
            label_cell($myrow["supp_name"]);
            
            if(isset($_POST['selected_'.$myrow['id']])){
                $selected = 1;
            }
            else{
                $selected = 0;
            }
            check_cells(null, 'selected_'.$myrow['id'], $selected, false);
            end_row();
            
            $j++;
            If ($j == 20)
            {
            	$j = 1;
        		table_header($th);
            } 
        } //end of while loop

        end_table();
    }
    div_end();
}

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

    $pvrc_msg = post_vehicle_running_chart_entries();
    if($pvrc_msg['success'] !== true){
        display_error($pvrc_msg["message"]);
    }
    else{
        $text = "Batch No ".$pvrc_msg["tran_no"]." posted";
        display_notification($text);        
    }
}


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

global $Ajax;

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

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

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

start_table(TABLESTYLE_NOBORDER);
    start_row();
        date_cells(_("From:"), 'from_date', '', null, -30);
        date_cells(_("To:"), 'to_date', '', null, +1);
        vehicles_list_cells("Vehicle:", 'vehicle', null, 'All Vehicles');
        supplier_list_cells("Supplier", "supplier_id", null, "All Suppliers");
        submit_cells('ShowVRCE',_("Search"),'',_('Refresh Inquiry'), 'default');
    end_row();
end_table();


display_open_running_chart_entries();

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






    
//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');
//
//}
//else{
        
br();

submit_center_first('Post', _("Process"), '', 'default');

br(2);

//    submit('Add_RCE_Close_VA', 'Add and Close Allocation', true, '', 'default');
//}


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