<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_ASSET_ENTRY';
$path_to_root = "../..";
$path_to_root_2 = "..";
include($path_to_root . "/includes/session.inc");
add_access_extensions();

$js = "";
$js .= get_js_open_window(900, 500);
$js .= get_js_date_picker();

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

include_once($path_to_root . "/assets/includes/db/assets_db.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/transport/includes/db/vehicles_db.inc");

simple_page_mode(true);

function clear_data()
{
    unset($_POST['serial']);
    unset($_POST['description']);
    unset($_POST['long_description']);  
    unset($_POST['group_id']);
    unset($_POST['asset_category_id']);
    unset($_POST['cost']);
    unset($_POST['current_value']);
    unset($_POST['make']);
    unset($_POST['model']);
    unset($_POST['po_number']);
    unset($_POST['useful_life']);
    unset($_POST['extended_life']);         
    unset($_POST['rate_category_id']);
}

function can_process($selected_id)
{ 
    $input_error = 0;
    
    if (strlen($_POST['asset_code']) == 0){
        $input_error = 1;
        display_error( _("Asset code can not be empty."));
        set_focus('asset_code');
        return;
    } 
    
    if (strlen($_POST['description']) == 0) 
    {
        $input_error = 1;
        display_error(_('Description can not be empty.'));
        set_focus('description');
        return;
    } 

    if(!(strlen($_POST['type']) > 0))
    {
        $input_error = 1;
        display_error(_("Please select an Asset Type."));
        set_focus('type');
        return;
    } 
    
    if(!($_POST['group_id'] > 0))
    {
        $input_error = 1;
        display_error(_("Please select an Asset Group."));
        set_focus('group_id');
        return;
    } 
    
    if(!($_POST['subgroup_id'] > 0))
    {
        $input_error = 1;
        display_error(_("Please select an Asset Subgroup."));
        set_focus('subgroup_id');
        return;
    } 
    
    if(!($_POST['asset_category_id'] > 0)){
        $input_error = 1;
        display_error( _("Please select an Asset Category."));
        set_focus('asset_category_id');
        return;
    } 
   
    if($_POST['type'] == AT_TOOL){
        if(!($_POST['rate_category_id'] > 0)){
            $input_error = 1;
            display_error( _("Please select a Rate Category."));
            set_focus('rate_category_id');
            return;
        } 
    }
   
    
//     if ($_POST['asset_code'] < 0)
//    {
//	$input_error = 1;
//	display_error( _("Asset Code cannot be negative value."));
//	set_focus('asset_code');
//        return;
//    } 
    
//    if (is_date($_POST['warranty_from']) == FALSE)
//    {
//        $input_error = 1;w
//        display_error( _("Incorrect Warranty From date"));
//        set_focus('warranty_from');
//        return;
//    }
//    if (is_date($_POST['warranty_to']) == FALSE)
//    {
//        $input_error = 1;
//        display_error( _("Incorrect Warranty To date"));
//        set_focus('warranty_to');
//        return;
//    }
//    if (date1_greater_date2($_POST['warranty_from'], $_POST['warranty_to']))
//     {
//         $input_error = 1;
//         display_error( _("Warranty to date can not be greater than warranty from date"));
//         set_focus('warranty_to');
//         return;
//     }
     
    $count = get_existing_asset_code($selected_id, $_POST['asset_code']);
    if($count > 0) 
    { 
        $input_error = 1;
        display_error("Entered Asset code already exists.");
        set_focus('asset_code');
        return;                    
    } 
    
    if (! isset($_POST['status'])) {
        display_error("Asset ststus cannot empty.");
        set_focus('asset_code');
        return;                    
    }
    
    return true;    
}

if (isset($_POST['SAVE_VEHICLE'])) {
    $asset_id = get_post('asset_id');
    
    $row = get_vehicle($asset_id);
        if (is_array($row)) {
            $uvr = edit_vehicle($asset_id);
        } else {
            create_vehicle($asset_id);
        }
}    
 
function display_vehicle_controls($asset_id) {
    $row = get_vehicle_for_edit($asset_id);
        if (is_array($row)) {
            $_POST['id'] = $row["id"];
            $_POST['description'] = $row["description"];
            $_POST['hired'] = $row["hired"];
            $_POST['plate_number'] = $row["plate_number"];
            $_POST['chassis'] = $row["chassis_no"];
            $_POST['owner_details'] = $row["owner_details"];
            $_POST['model'] = $row["model_no"];
            $_POST['engine_no'] = $row["engine_no"];
            $_POST['vehicle_type'] = $row["vehicle_type"];
            $_POST['purchased_status'] = $row["purchased_status"];
            $_POST['cylinder_capacity'] = $row["cylinder_capacity"];
            $_POST['fuel_type'] = $row["fuel_type"];
            $_POST['manufacturer'] = $row["manufacturer"];
            $_POST['country'] = $row["country_of_origin"];
            $_POST['year_manufacture'] = $row["year_of_manufacture"];
            $_POST['inactive'] = $row["inactive"];
            $_POST['asset_id'] = $row["asset_id"];
        }
    
    start_outer_table(TABLESTYLE2);
        table_section(1);
            text_row("Description:", 'description', null, 50, 100);
            yesno_list_row("Hired:", 'hired', null, "Yes", "No", true);


            text_row("Plate Number:", 'plate_number', null, 20, 30);
            text_row("Chassis No:", 'chassis', null, 20, 20);
            textarea_row("Owner Details :", 'owner_details', null, 20, 10);
            text_row("Model:", 'model', null, 20, 20);
            text_row("Engine Number:", 'engine_no', null, 20, 20);
            value_list_row("Vehicle Type:", 'vehicle_type', 'VEHICLE_TYPES', null, 'Select', false);

        table_section(2);
            if($_POST['hired'] == '0')
            {
                value_list_row("Purchased Status:", 'purchased_status', 'VEHICLE_PURCHASED_STATUS', null, 'Select', false);
            }
            else
            {
                $_POST['purchased_status'] = 0;
            }

            text_row("Cylinder Capacity:", 'cylinder_capacity', null, 20, 20);
            value_list_row("Fuel Type:", 'fuel_type', 'VEHICLE_FUEL_TYPES', null, 'Select', false);
            value_list_row("Manufacturer:", 'manufacturer', 'VEHICLE_MANUFACTURERS', null, 'Select', false);
            value_list_row("Country of Origin:", 'country', 'COUNTRIES', null, 'Select', false);
            value_list_row("Year of Manufacture:", 'year_manufacture', 'YEAR', null, 'Select', false);
            record_status_list_row(_("status:"), 'inactive');
    end_outer_table(2);
    
    submit_center_first('SAVE_VEHICLE', _("SAVE VEHICLE"), '', 'default');    br(2);
}

function can_process_vehicle($asset_id)
{
    if (! ($asset_id > 0)) {
        set_focus('asset_id');
        display_error("Please select an asset.");
        return false;    
    }
    
    if(strlen($_POST['description']) == "")
    { 
        set_focus('description');
        display_error("Description can not be empty");
        return false;    
    }    
    if(strlen($_POST['plate_number']) == "")
    { 
        set_focus('plate_number');
        display_error("Plate Number can not be empty");
        return false;    
    }  
    
    if(!($_POST['vehicle_type'] > 0))
    { 
        set_focus('vehicle_type');
        display_error("Please select a vehicle type.");
        return false;    
    } 
    
    return true;    
}

function create_vehicle($asset_id)
{         

    if(!can_process_vehicle($asset_id)){
        return;
    }
    
    $_POST["incative"] = isset($_POST["incative"]) ? $_POST["incative"] : 0;
    
    $rec_id = add_vehicle_wms($_POST['description'], $_POST['hired'], $_POST['plate_number'],$_POST["chassis"],$_POST["owner_details"],
            $_POST["model"],$_POST["engine_no"],$_POST["vehicle_type"],$_POST["purchased_status"],$_POST["cylinder_capacity"],$_POST["fuel_type"],
            $_POST["manufacturer"],$_POST["country"],$_POST["year_manufacture"],$_POST["incative"], $asset_id);                                
                                  
    if($rec_id > 0){
        $Mode = "RESET";
        display_notification("New Vehicle has been added");
        clear_data();
    }
    else{
        display_error("New Vehicle could not be added" );
    }
}

function edit_vehicle($asset_id)
{       
    if(!can_process_vehicle($asset_id)){
        return;
    }
      if($_POST['hired'] == '1')
    {
        $_POST['purchased_status'] = 0;
    }
    
    $recs = update_vehicle_wms($asset_id, $_POST['description'],  $_POST['hired'], $_POST['plate_number'],$_POST["chassis"],$_POST["owner_details"],
            $_POST["model"],$_POST["engine_no"],$_POST["vehicle_type"],$_POST["purchased_status"],$_POST["cylinder_capacity"],$_POST["fuel_type"],
            $_POST["manufacturer"],$_POST["country"],$_POST["year_manufacture"],$_POST["inactive"],$asset_id);                             
                           
    if($recs == 1){
        display_notification("Selected Vehicle has been updated");
    }
    else{
        display_error("Selected Vehicle could not be updated");
    }
}

if(isset($_POST['AddAsset']))
{    
    if(can_process($selected_id) == true){
        if($_POST['owner_project_id'] < 0){
            $_POST['owner_project_id'] = 0;
        }
        add_asset($_POST['asset_code'] , $_POST['description'], $_POST['long_description'], $_POST['type'], $_POST['multiple_items'], $_POST['group_id'], $_POST['is_hired'], 
                  $_POST['asset_category_id'], $_POST['subgroup_id'], $_POST['serial'], $_POST['make'], $_POST['model'], $_POST['po_number'], input_num('cost'), 
                  input_num('current_value'), input_num('useful_life'), input_num('extended_life'), $_POST['rate_category_id'], $_POST['inactive'], 
                  input_num('owner_project_id'), input_num('next_service_days'), $_POST['status']); 

        $Mode = 'RESET';            

        display_notification(_('New Asset type has been added'));             
    }               
}

if(isset($_POST['Update'])) 
{    
    $asset_id = get_post('asset_id');
    if(can_process($asset_id) == true){        

        if($_POST['owner_project_id'] < 0){
            $_POST['owner_project_id'] = 0;
        }
        update_asset($asset_id, $_POST['asset_code'], $_POST['description'], $_POST['long_description'], $_POST['multiple_items'], $_POST['group_id'], $_POST['is_hired'], 
                     $_POST['asset_category_id'], $_POST['subgroup_id'], $_POST['serial'], $_POST['make'], $_POST['model'], $_POST['po_number'], input_num('cost'), 
                     input_num('current_value'), input_num('useful_life'), input_num('extended_life'), $_POST['rate_category_id'], $_POST['inactive'], 
                     input_num('owner_project_id'), input_num('next_service_days'), $_POST['status']);   
        
        
        
        $Mode = 'RESET';
    
        display_notification(_('Asset has been Updated'));                     
    }
}
//---------------------------------------------------------------------------------------------------------------
if (isset($_POST['delete']))
{
//	$asset_id = get_post('asset_id');
//		delete_asset($asset_id);
//		display_notification(_('Selected asset has been deleted'));
	
	$Mode = 'RESET';
}

if ($Mode == 'RESET')
{
	$selected_id = -1;
	$sav = get_post('show_inactive');
//	unset($_POST);
	$_POST['show_inactive'] = $sav;
}
if (get_post('cancel')) {
	
    clear_data();
	set_focus('serial');
	$Ajax->activate('_page_body');
}

if (list_updated('asset_id')) {
	$Ajax->activate('asset_id');
    $Ajax->activate('asset_details');
    
}

if (list_updated('group_id')) {
	$Ajax->activate('subgroup_id');
}
//---------------------------------------------------------------------------------------------

function asset_settings($asset_id)
{      
    global $asset_types, $Ajax, $asset_statuses;
    
    $Ajax->activate('asset_details');
    
//    div_start('asset_details');
    start_outer_table(TABLESTYLE2);
   
    table_section(1);     
   
    
    if (!(isset($asset_id) &&  $asset_id > 0))        
    {   
        if(list_updated('asset_id')){
            $_POST['owner_project_id'] = -1;
            $_POST['_owner_project_id_edit'] = -1;
        }
        

//        set_post_not_set_string('description', '');
        
        
        start_table(TABLESTYLE_NOBORDER);  
        table_section_title(_("Asset"));
            text_row("Code: ", 'asset_code', null, 35, 50);        
            text_row(_("Description :"), 'description', null, 35, 250);
            textarea_row(_('Long Description:'), 'long_description', null, 25, 3);
            
            asset_types_list_row(_("Type :"), 'type', null, 'Select an asset type', true);   
            yesno_list_row("Multiple Items :", 'multiple_items', null, 'yes', 'no');
            
            asset_categoris_list_row(_("Category :"), 'asset_category_id', null, 'Select an asset category', null);   
            asset_groups_list_row(_("Group:"), 'group_id', null, 'Select an asset group', true);
            asset_subgroups_list_row("Subgroup:", 'subgroup_id', $_POST['group_id'], null, 'Select an asset subgroup', false);
            
               
            yesno_list_row("Hired :", 'is_hired', null, 'yes', 'no');
            
            if($_POST['type'] == AT_TOOL){
                tool_rate_category_list_row(_("Rate Category:"), 'rate_category_id', null, 'Select an asset rate'); 
            }
            else{
//                unset($_POST['rate_category_id']);
                hidden('rate_category_id', 0);
            }
            
            text_row(_("Serial/Plate Number :"), 'serial', null, 15, 50);            
            text_row(_("Make :"), 'make', null, 25, 50);
            text_row(_("Model :"), 'model', null, 25, 50);
            
            project_list_row("Owner Project :", 'owner_project_id', null, "Select a project");
            
            amount_row(_("Useful Life (Years) :"), 'useful_life', null, null, null, 1);
            amount_row(_("Extended Life (Years) :"), 'extended_life', null, null, null, 1);
            
            amount_row(_("Next Service Days :"), 'next_service_days', null, null, null, 0);
            custom_values_list_row("Asset Status :", "status", $asset_statuses, null, "");
            
            yesno_list_row("Inactive :", 'inactive', null, 'yes', 'no');
            
        table_section_title(_("Value"));
            text_row(_("PO Number :"), 'po_number', null, 25, 50);
            amount_row(_("Purchased Value :"), 'cost', null, null, null, 2);
            amount_row(_("Current Value :"), 'current_value', null, null, null, 2);
                                      

//        end_table(1);
        end_outer_table(1);
        
        start_table();
            submit_center_last('AddAsset', _("Insert New Asset"), '',  @$_REQUEST['popup'] ? true : 'default');
            submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
        end_table(2);
    }
    else 
    {
//        if($asset_id != ''){
//        $myrow = get_asset($asset_id);
//        }

        $myrow = get_asset($asset_id);
        
        $_POST['asset_code'] = $myrow["asset_code"];
        $_POST['description'] = $myrow["description"];
        $_POST['long_description'] = $myrow["long_description"];
        
        $_POST['type'] = $myrow['type'];
        $_POST['multiple_items'] = $myrow["multiple_items"];

        if(list_updated('asset_id')){
            $_POST['group_id'] = $myrow["group_id"];
        }
        $_POST['group_id'] = !isset($_POST['group_id']) ? $myrow["group_id"]: $_POST['group_id'];            

        $_POST['is_hired'] = $myrow["is_hired"];
        $_POST['asset_category_id'] = $myrow["asset_category_id"];
        $_POST['subgroup_id'] = $myrow['subgroup_id'];
        $_POST['serial'] = $myrow["asset_serial"];            
        $_POST['make'] =  $myrow['make'];
        $_POST['model'] = $myrow['model'];
        $_POST['po_number'] = $myrow['po_number'];
        $_POST['cost'] = $myrow['purchase_value'];
        $_POST['current_value'] = $myrow['current_value'];
        
        if(list_updated('asset_id')){
            $_POST['owner_project_id'] = $myrow['owner_project_id'];
            $_POST['_owner_project_id_edit'] = $_POST['owner_project_id'];
        }
 
        if(!(isset($_POST['owner_project_id']) && $_POST['owner_project_id'] > 0)){
            $_POST['owner_project_id'] = $myrow['owner_project_id'];
        }
        
//        if(!(isset($_POST['_owner_project_id_edit']) && $_POST['_owner_project_id_edit'] > 0)){
//            $_POST['_owner_project_id_edit'] = $myrow['owner_project_id'];
//        }
        if(!(isset($_POST['owner_project_id']) && $_POST['owner_project_id'] > 0)){
            $_POST['_owner_project_id_edit'] = $myrow['owner_project_id'];
        }
        
        $_POST['useful_life'] = $myrow['useful_life'];
        $_POST['extended_life'] = $myrow['extended_life'];                
        $_POST['rate_category_id'] = $myrow['rate_category_id'];
        $_POST['next_service_days'] = $myrow['next_service_days'];
        $_POST['status'] = $myrow['status'];
        $_POST['inactive'] = $myrow["inactive"];

        start_table(TABLESTYLE_NOBORDER);
        table_section_title(_("Asset"));    
            text_row("Asset Code: ", 'asset_code', null, 35, 50); 
            text_row(_("Description :"), 'description', $_POST['description'], 35, 250);
            textarea_row(_('Long Description:'), 'long_description', $_POST['long_description'], 25, 3);
            
            label_row("Type", $asset_types[$_POST['type']]) ;
            hidden('type', $_POST['type']);
            
            yesno_list_row("Multiple Items", 'multiple_items', null, 'yes', 'no');
            
            asset_categoris_list_row("Asset Category", 'asset_category_id', null, false, false);
            asset_groups_list_row(_("Group:"), 'group_id', get_post('group_id'), 'Select an asset group', true); 
            asset_subgroups_list_row("Subgroup:", 'subgroup_id', $_POST['group_id'], $_POST['subgroup_id'], 'Select an asset subgroup', false);
            
            yesno_list_row("Hired", 'is_hired', $_POST['is_hired'], 'yes', 'no');
            
//            if($_POST['type'] == AT_TOOL){
                tool_rate_category_list_row(_("Rate Category:"), 'rate_category_id', $_POST['rate_category_id'], 'Select an asset rate'); 
//            }
//            else{
//                hidden('rate_category_id', 0);
//            }
            
            
            text_row(_("Serial Number :"), 'serial', $_POST['serial'], 15, 50);           
            text_row(_("Make :"), 'make', $_POST['make'], 25, 50);
            text_row(_("Model :"), 'model', $_POST['model'], 25, 50);
            
            project_list_row("Owner Project :", 'owner_project_id', $_POST['owner_project_id'], "Select a project");

            amount_row(_("Useful Life (Years) :"), 'useful_life', null, null, null, 1);
            amount_row(_("Extended Life (Years) :"), 'extended_life', null, null, null, 1);
            
            amount_row(_("Next Service Days :"), 'next_service_days', null, null, null, 0);
            
            $last_service_date = $next_service_date = '';
            if ($myrow['last_service_date'] > INFINITE_START_DATE) {
                $last_service_date = sql2date($myrow['last_service_date']);
                $date = date_create($myrow['last_service_date']);
                date_add($date, date_interval_create_from_date_string($myrow['next_service_days']." days"));
                $next_service_date = sql2date(date_format($date,"Y-m-d"));
            }
            label_row(_("Last Service Date :"), $last_service_date);
            label_row(_("Next Service Date :"), $next_service_date);
            
            yesno_list_row("Inactive :", 'inactive', null, 'yes', 'no');
            custom_values_list_row("Asset Status :", "status", $asset_statuses, null, "");
            
        table_section_title(_("Value"));
            text_row(_("PO Number :"), 'po_number', $_POST['po_number'], 25, 50);
            amount_row(_("Purchased Value :"), 'cost', $_POST['cost'], null, null, 2); 
            amount_row(_("Current Value :"), 'current_value', $_POST['current_value'], null, null, 2);
             
            
//            hidden('asset_id', $_POST['asset_id']);
                       
//        end_table(1);
        end_outer_table(1);
        
        
        start_table();
            submit_center_first('Update', _("Update"), '',  @$_REQUEST['popup'] ? true : 'default');
//            submit('delete', _("Delete This Asset"), true, '', true);
            submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
        end_table(2);
    }
    
//    div_end();
}    

start_form();

    start_table(TABLESTYLE_NOBORDER);
        start_row();
            asset_list_cells(_("Select an asset:"), 'asset_id', null,_('New asset'), true, check_value('show_inactive'));
            submit_cells('Refresh', 'Refresh', '', 'Refresh', false, ICON_SUBMIT);

            $new_item = get_post('asset_id')=='';

            if(get_post('asset_id') == -1 || get_post('asset_id') == ''){
                $new_item = TRUE;
            }

        end_row();
    end_table();

    $Ajax->activate('asset_details');
    div_start('asset_details');

    $asset_id = get_post('asset_id');

    tabbed_content_start('tabs', array(
                            'settings' => array(_('&General settings'), $asset_id),        
                            'asset_vehicle' => array(_('&Vehicle'), $asset_id),
//                            'asset_material' => array(_('&Material'), $asset_id),
//                            'asset_departments' => array(_('&Departments'), $asset_id), 
                        ));
    
    switch (get_post('_tabs_sel')) 
    {
            default:
            case 'settings':
                asset_settings($asset_id); 
                break;
            case 'asset_vehicle':
//                include_once($path_to_root_2."/assets/includes/ui/vehicles_ui.ui");
//                include_once($path_to_root."/assets/includes/ui/vehicles_ui.ui");
                display_vehicle_controls($asset_id);
                break;
            case 'asset_material':
                $_GET['asset_id'] = $asset_id;                           
                $_GET['popup'] = 1;
                include_once($path_to_root."/asset_register/asset_material.php");
                break;
            case 'asset_departments':
                $_GET['asset_id'] = $asset_id;                           
                $_GET['popup'] = 1;
                include_once($path_to_root."/asset_register/asset_departments.php");
                break;                  
    };

    br();
    tabbed_content_end();
div_end();
hidden('popup', @$_REQUEST['popup']);
end_form();
//---------------------------------------------------------------------------------------
end_page(@$_REQUEST['popup']);

?>