<?php
/**
 * @file
 * Enables modules and site configuration for a standard site installation.
 */

require('profiles/simmetry/simmetry.utils.inc');

/*
 * Implements:  example_profile_details()
 *
 * Returns:  a description of the profile for the initial installation screen
 *
 * @return
 *   An array with keys 'name' and 'description' describing this profile,
 *   and optional 'language' to override the language selection for
 *   language-specific profiles. 
 */
function simmetry_profile_details() {
  
  $simmetryApp = which_app();
  
	return array(
		'name' => 'Sabre Updates SIMmetry Installation',
		'description' => 'Install Sabre QMS or Scheduler Application',
	);
}



/**
 * Implements hook_form_FORM_ID_alter() for install_configure_form().
 *
 * Allows the profile to alter the site configuration form.
 */
function simmetry_form_install_configure_form_alter(&$form, $form_state) {
  //echo 'simmetry_form_install_configure_form_alter'."<br/>\n";
  
  // Pre-populate the site name with the server name.
	shell_exec ( "chmod -R 755 sites" );
  
  $simmetryApp = which_app();
  
  $site_name =  ($simmetryApp == PROFILE_APP_SCHEDULER) ? 'SIMmetry Scheduler' : 'Quality Management System';
  
  $form['site_information']['site_name']['#default_value'] = $site_name;
	$form['server_settings']['site_default_country']['#default_value'] = 'US';
	
	$themes = list_themes();
	$opts = array();
	foreach ($themes as $t) {
		$opts[$t->name] = $t->name;
	}
	
	$form['server_settings']['theme'] = array(
		'#type' => 'select',
		'#title' => t('Default Theme'),
		'#options' => $opts,		
    '#default_value' => 'bartik_sabre',
		'#attributes' => array( 'style' => 'width:200px;'),
	);
	
	$form['#submit'][] = 'store_simmetry_extra_data_handler';
}




function store_simmetry_extra_data_handler(&$form, &$form_state) {

    
	// get the theme selection from the form
	$default_theme = $form_state['values']['theme'];
	
	if ( $default_theme == '' ) {
		$default_theme = 'bartik_sabre';
	}
	
  // Any themes without keys here will get numeric keys and so will be enabled,
  // but not placed into variables.
  $enable = array(
    'theme_default' => $default_theme,
    'admin_theme' => 0,  // set to whatever theme is the default theme
  );
  theme_enable($enable);

  foreach ($enable as $var => $theme) {
    if (!is_numeric($var)) {
      variable_set($var, $theme);
    }
  }

  // Disable the default Seven theme
  theme_disable(array('seven'));
	
	
  variable_set('clean_url', '1');

	// Disable default logo and enter new logo path
  variable_set('theme_' . $default_theme . '_settings', array(
    'default_logo' => 0,
    'logo_path' => '', /*'profiles/simmetry/themes/' . $default_theme . '/images/logo.png', */
		'toggle_logo' => 1,
    'toggle_name' => 1,
    'toggle_slogan' => 0,
    'toggle_mission' => 0,
    'toggle_primary_links' => 1,
    'toggle_secondary_links' => 1,
    'toggle_node_user_picture' => 0,
    'toggle_comment_user_picture' => 0,
		'default_favicon' => 0,
		'toggle_favicon' => 1,
		'favicon_path' => 'profiles/simmetry/themes/' . $default_theme . '/images/favicon.ico',
    'toggle_search' => 0,
  ));
  
}





/*
 * Implements:  hook_install_tasks()
 *
 * Returns:  an assoc. array of tasks the installation process needs to include
 *
 * @return
 *   $task['task_name'] = array(
 * 											'display_name' => st('Human-readable task name'),
 * 											'display' => TRUE,
 * 											'type' => 'normal',
 * 											'run' => INSTALL_TASK_RUN_IF_REACHED,
 * 											'function' => 'function_to_execute',
 *                      );
 *
 *  explained in:  http://drupal.org/node/1022020
 */
function simmetry_install_tasks($install_state) {
  //echo "simmetry_install_tasks"."<br/>\n";
  
	$tasks = array(
		'populate_simmetry_tables' => array(
        'display_name' => st('Final SIMmetry Config'),
        'display' => True,
        'type' => 'normal',
        'run' => INSTALL_TASK_RUN_IF_REACHED,
        'function' => 'do_final_simmetry_config_steps',
      ),
	); 
	return $tasks;
}


function do_final_simmetry_config_steps() {
  //echo 'do_final_simmetry_config_steps'."<br/>\n";
 
  $simmetryApp = which_app();
  
  // we can't do this in schema so we add it afterward
  _create_fulltext_indexes($simmetryApp);  
    
  _create_front_page_content($simmetryApp);
  _adjust_system_menus($simmetryApp);
  _set_app_root($simmetryApp);
  
  if ( PROFILE_APP_QMS == $simmetryApp) {
  
    _qms_roles_permissions();
    _qms_ata_chapters();
    _qms_corrective_actions();	
    _qms_eng_load();
    _qms_trouble_causes();
    _qms_simulator_statuses();
    _qms_example_records();
 
    
  } else if ( PROFILE_APP_SCHEDULER == $simmetryApp) {
    
    _scheduler_roles_permissions();
    _scheduler_example_customer();
    _scheduler_example_simulator();
    _scheduler_sim_base_types();
    _scheduler_calendar();
    _scheduler_load_holidays(); 
  }
}


/*
 * _qms_ata_chapters()
 * 
 * populates the sabreQMS table:  AtaChapters
 *
 */


function _qms_ata_chapters() {
	$values = array(
		array('code' => 21, 'chapter' => 'Air Conditioning'),
		array('code' => 22, 'chapter' => 'Autoflight'),
		array('code' => 23, 'chapter' => 'Communication'),
		array('code' => 24, 'chapter' => 'Electrical Power'),
		array('code' => 25, 'chapter' => 'Equipment & Furn.'),
		array('code' => 27, 'chapter' => 'Flight Controls'),
		array('code' => 28, 'chapter' => 'Fuel'),
		array('code' => 29, 'chapter' => 'Hydraulic Power'),
		array('code' => 30, 'chapter' => 'Ice & Rain Protection'),
		array('code' => 31, 'chapter' => 'Instruments'),
		array('code' => 32, 'chapter' => 'Landing Gear'),
		array('code' => 33, 'chapter' => 'Lights'),
		array('code' => 34, 'chapter' => 'Navigation'),
		array('code' => 35, 'chapter' => 'Oxygen'),
		array('code' => 36, 'chapter' => 'Pneumatics'),
		array('code' => 49, 'chapter' => 'APU'),
		array('code' => 70, 'chapter' => 'Powerplant'),
		array('code' => 78, 'chapter' => 'Thrust Reversers'),
		array('code' => 99, 'chapter' => 'Preventative Maintenance'),
		array('code' => 10, 'chapter' => 'Visual System'),
		array('code' => 26, 'chapter' => 'Fire'),
		array('code' => 98, 'chapter' => 'Host Computer'),
		array('code' => 0,  'chapter' => 'Other'),
    array('code' => 1,  'chapter' => 'Preflight'),
	);

	$query = db_insert('qms_ata_chapters')
					 ->fields(array('code', 'chapter'));
  foreach ($values as $record) {
    $query->values($record);
  }
  $query->execute();
}

/*
 * _qms_corrective_actions()
 * 
 * populates the sabreQMS table:  CorrectiveActions
 *
 */

function _qms_corrective_actions() {
	$values = array(
		array('action' => 'Corrected by adjusting unit.'),
		array('action' => 'Corrected by loading new database.'),
		array('action' => 'Corrected by relamping.'),
		array('action' => 'Corrected by reloading host computer.'),
		array('action' => 'Corrected by reloading visual computer.'),
		array('action' => 'Corrected by repairing unit.'),
		array('action' => 'Corrected by replacing unit.'),
		array('action' => 'Corrected by resetting unit.'),
		array('action' => 'Corrected simulator software program.'),
		array('action' => 'Duplicate'),
		array('action' => 'Hardware Modification Completed.'),
		array('action' => 'Installation in progress.'),
		array('action' => 'Modification in progress.'),				
		array('action' => 'Open - Hardware Modification (Site / In Progress).'),
		array('action' => 'Open - Parts'),
		array('action' => 'Open - Software / Hardware Eng.'),
		array('action' => 'Open - Software Modification (Site / In progress).'),
		array('action' => 'Open - Maintenance'),
		array('action' => 'Preventative maintenance item cleared.'),
		array('action' => 'Ready for recheck.'),
		array('action' => 'Request for additional info from aircrew.'),
		array('action' => 'Simulator not in service.'),
		array('action' => 'Unable to duplicate.'),
		array('action' => 'Works in accordance with software specifications.'),
		array('action' => 'Works in accordance with technical data.'),
	);

	$query = db_insert('qms_corrective_actions')
					 ->fields(array('action'));
  foreach ($values as $record) {
    $query->values($record);
  }
  $query->execute();
}


/*
 * _qms_eng_load()
 * 
 * populates the sabreQMS table:  qms_eng_load_updated
 *
 */

function _qms_eng_load() {
	
	$values = array(
		array('eng_load_updated_desc' => 'Normal'),
	);

	$query = db_insert('qms_eng_load_updated')
					 ->fields(array('eng_load_updated_desc'));
  foreach ($values as $record) {
    $query->values($record);
  }
  $query->execute();
}

/*
 * _qms_eng_load()
 * 
 * populates the sabreQMS table:  qms_eng_load_updated
 *
 */

function _qms_trouble_causes() {
	
	$values = array(
		array(
			'trouble_cause_code' => 1,
			'trouble_cause_desc' => 'Undetermined / Not Applicable / Other',
		),
		array(
			'trouble_cause_code' => 2,
			'trouble_cause_desc' => 'Human error - caused by the operator',
		),
		array(
			'trouble_cause_code' => 3,
			'trouble_cause_desc' => 
					'Human error - caused by other users not properly trained ' . 
					'in the operation of the simulator.',
		),
		array(
			'trouble_cause_code' => 4,
			'trouble_cause_desc' => 
					'Input power/environmental conditions exceeded simulator specification',
		),
		array(
			'trouble_cause_code' => 5,
			'trouble_cause_desc' => 
				'Simulator peripheral equipment failure - training not directly affected',
		),

	);

	$query = db_insert('qms_trouble_causes')
					 ->fields(array('trouble_cause_code', 'trouble_cause_desc'));
  foreach ($values as $record) {
    $query->values($record);
  }
  $query->execute();
}


/*
 * _create_fulltext_indexes()
 * 
 * create fulltext indexes on the following tables:columns
 * qms_discrepancy_log.discrepancy
 * qms_discrepancy_comments.comment
 * qms_shift_log.comment
 * qms_engineering.module_updated
 *
 */

function _create_fulltext_indexes($appcode) {
  
  if ( PROFILE_APP_SCHEDULER == $appcode) {
    
  } else {
    db_query("CREATE FULLTEXT INDEX dr_discrepancy_text_idx ON qms_discrepancy_log (discrepancy)");
    db_query("CREATE FULLTEXT INDEX dc_comment_text_idx ON qms_discrepancy_comments (comment)");
    db_query("CREATE FULLTEXT INDEX eng_module_updated_text_idx ON qms_engineering (module_updated)");
    db_query("CREATE FULLTEXT INDEX sl_comment_text_idx ON qms_shift_log (comment)");
    db_query("CREATE FULLTEXT INDEX tc_trouble_text_idx ON qms_trouble_call_log (trouble_text)");
    db_query("CREATE FULLTEXT INDEX tc_comment_text_idx ON qms_trouble_call_comments (comment)");
    db_query("CREATE FULLTEXT INDEX v_vendor_note_text_idx ON qms_vendors (note)");
  }
}


/*
 * _qms_simulator_statuses
 */
function _qms_simulator_statuses() {
  /* 'order' is a reserved word.... workaround
  $values = array(
		array('status_code' => 'D', ' order ' => 1),
		array('status_code' => 'C', ' order ' => 2),
    array('status_code' => 'B', ' order ' => 3),
    array('status_code' => 'A', ' order ' => 4),
    array('status_code' => '8', ' order ' => 0),
    array('status_code' => '7', ' order ' => 0),
		array('status_code' => '6', ' order ' => 7),
    array('status_code' => '5', ' order ' => 8),
    array('status_code' => '4', ' order ' => 9),
	);


	$query = db_insert('qms_simulator_statuses')
					 ->fields(array('status_code', ' order '));
  foreach ($values as $record) {
    $query->values($record);
  }
  $query->execute();
   * 
   */
  
  $sql = "INSERT INTO {qms_simulator_statuses} (`status_code`, `order`) 
          VALUES ('D', 1),('C', 2), ('B', 3), ('A', 4), ('8', 0), ('7', 0),
          ('6', 7), ('5', 8), ('4', 9)";
  $result = db_query($sql);

}


/*
 * _create_front_page_content()
 * 
 * The default front page content - role based
 *
 */

function _create_front_page_content($appcode) {
  
  $anon_page = '';
  $values = array();
	
	// Create Home Pages for Front Page module by role
	variable_set('front_page_enable', '1');
	
	
	// authenticated user & administrators	
  $host = $_SERVER['HTTP_HOST'];
  $other_url = $host;
  if (False !== stripos($host, 'scheduler')) {
    $other_url = str_replace('scheduler', 'qms', $host);
  } else {
    $other_url = str_replace('qms', 'scheduler', $host);
  }
  
  if ($appcode == PROFILE_APP_SCHEDULER) {
    // SCHEDULER
    // anonymous user
    $anon_page = '<h1 class="title" id="page-title">Welcome to SIMmetry Scheduler</h1>' . 
                 '<p>SIMmetry Scheduler is designed to manage training sessions for multiple simulators, ' . 
                 'users, and schedules.&nbsp; It provides a centralized point of information for students, ' . 
                 'instructors, and administrators.</p>' . 
                 '<p>Please login to begin.</p><br /><br />' . 
                 '<p>For simulator maintenance information:</p>' . 
                 '<a href="' . url($other_url) . '">Login to SIMmetry QMS</a></p>';
    
    	$values = array(
        array(
              'rid' => 1, 
              'mode' => 'themed',
              'data' => $anon_page,
              'filter_format'	=> 'full_html',
              'weight' => 6,
              ),
         array(
              'rid'	=> 2,   // authenticated
              'mode' => 'redirect',
              'data' => 'user/home',
              'filter_format'	=> '',
              'weight' => 5,
              ),
         array(
              'rid' => 3, 		//admin
              'mode' => 'redirect',
              'data' => 'manager/home',
              'filter_format'	=> '',
              'weight' => 1,
              ),
         array(
              'rid' => 4, 		//student
              'mode' => '',
              'data' => '',
              'filter_format'	=> '',
              'weight' => 4,
              ),
         array(
              'rid' => 5, 		//instructor
              'mode' => '',
              'data' => '',
              'filter_format'	=> '',
              'weight' => 3,
              ),
         array(
              'rid' => 6, 		//manager
              'mode' => 'redirect',
              'data' => 'manager/home',
              'filter_format'	=> '',
              'weight' => 2,
              ),
      );

    
  } else {
    
    // QMS
    // anonymous user
    $anon_page = '<h1 class="title" id="page-title">Welcome to SIMmetry QMS</h1>' . 
                '<p>SIMmetry QMS is a maintenance management resource.  ' . 
                'It provides a central point of information for tracking, updating, ' . 
                'and notifying about the operational status of your organization\'s flight simulators. </p>' . 
                '<p>Please login.</p><br /><br />' . 
                '<p>For simulator scheduling information:</p>' . 
                '<a href="' . url($other_url) . '">Login to SIMmetry Scheduler</a></p>';
    
    $values = array(
        array(
              'rid' => 1, 
              'mode' => 'themed',
              'data' => $anon_page,
              'filter_format'	=> 'full_html',
              'weight' => 8,
              ),
        array(
              'rid'	=> 2,   // authenticated
              'mode' => 'redirect',
              'data' => 'home/employee',
              'filter_format'	=> '',
              'weight' => 7,
              ),
        array(
              'rid' => 3, 		//admin
              'mode' => 'redirect',
              'data' => 'home/employee',
              'filter_format'	=> '',
              'weight' => 1,
              ),
        array(
              'rid'	=> 4,   // customer
              'mode' => '',
              'data' => '',
              'filter_format'	=> '',
              'weight' => 6,
              ),
        array(
              'rid'	=> 5,   // employee
              'mode' => '',
              'data' => '',
              'filter_format'	=> '',
              'weight' => 4,
              ),
        array(
              'rid'	=> 6,   // technician
              'mode' => '',
              'data' => '',
              'filter_format'	=> '',
              'weight' => 2,
              ),
        array(
              'rid'	=> 7,   // instructor
              'mode' => '',
              'data' => '',
              'filter_format'	=> '',
              'weight' => 3,
              ),
        array(
              'rid'	=> 8,   // contractor
              'mode' => '',
              'data' => '',
              'filter_format'	=> '',
              'weight' => 5,
              ),
    );
  
  }

	$query = db_insert('front_page')
	         ->	fields(array( 'rid', 'mode', 'data', 'filter_format'));
  foreach ($values as $record) {
    $query->values($record);
  }
  $query->execute();

}


/*
 * _adjust_system_menus()
 * 
 * does some menu housekeeping:  disables the native user menu in lieu of the QMS version,
 * sets up a 'Front Page' menu link
 */

function _adjust_system_menus($appcode) {

	// disable the native user-menu links
	
  db_update('menu_links')
    ->fields(array('hidden' => 1, 'customized' => 1))
 		->condition('menu_name', 'user-menu')
		->condition('link_path', 'user')
    ->execute();

  db_update('menu_links')
    ->fields(array('hidden' => 1, 'customized' => 1))
		->condition('menu_name', 'user-menu')
		->condition('link_path', 'user/logout')
    ->execute();
  
  db_update('menu_links')
    ->fields(array('hidden' => 1, 'customized' => 1))
    ->condition('link_path', 'node/add/article')
		->condition('menu_name', 'navigation')
    ->execute();

  db_update('menu_links')
    ->fields(array('hidden' => 1, 'customized' => 1))
    ->condition('link_path', 'node/add/page')
		->condition('menu_name', 'navigation')
    ->execute();
  
// Update Content link to User Alerts
  db_update('menu_links')
    ->fields(array(
        'link_title' => st('User Alerts'), 
        'customized' => 1,
        'plid' => 1,
        'weight' => -49,
      ))			
		->condition('menu_name', 'main-menu')
		->condition('link_path', 'admin/content')
    ->execute();

  // Create a link in the admin-menu for the Front Page settings link
	
//  $admin_menu = array(
//    'link_title' => st('Front Page'),
//    'link_path' => 'admin/config/front',
//    'menu_name' => 'management',
//		'plid' => 1,
//		'weight' => -50,
//  );
//	menu_link_save($admin_menu);
  


  if ($appcode == PROFILE_APP_QMS) {
    
    db_update('menu_links')
      ->fields(array('hidden' => 1, 'customized' => 1))
      ->condition('link_title', 'Home')
      ->condition('menu_name', 'main-menu')
      ->execute();
    
    db_update('menu_links')
    ->fields(array('hidden' => 1, 'customized' => 1))			
		->condition('menu_name', 'management')
		->condition('link_path', 'admin/content/node')
    ->execute();
    
    
    // QMS New Menu
    $menu_QMS_new = array();
    $menu_QMS_new['menu_name'] = "qms-menu";
    $menu_QMS_new['title'] = "QMS New Entry";
    $menu_QMS_new['description'] = "QMS New Entry Functions";
    menu_save($menu_QMS_new);

    // QMS Search Menu
    $menu_QMS_search = array();
    $menu_QMS_search['menu_name'] = "qms-search-menu";
    $menu_QMS_search['title'] = "QMS Search";
    $menu_QMS_search['description'] = "QMS Search Functions";
    menu_save($menu_QMS_search);

    // QMS Administration Menu
    $menu_QMS_admin = array();
    $menu_QMS_admin['menu_name'] = "qms-admin-menu";
    $menu_QMS_admin['title'] = "QMS Administration";
    $menu_QMS_admin['description'] = "QMS Administrative Functions";
    menu_save($menu_QMS_admin);


    $qms_logout = array(
      'link_title' => st('Log out'),
      'link_path' => 'user/logout',
      'menu_name' => 'qms-menu',
      'weight' => 50,
    );
    menu_link_save($qms_logout);


    $system_admin = array(
      'link_title' => st('System Administration'),
      'link_path' => 'admin',
      'menu_name' => 'qms-admin-menu',
      'weight' => 9,
    );
    menu_link_save($system_admin);

    
  } else if ($appcode == PROFILE_APP_SCHEDULER) {
    
    db_insert('menu_links')
    ->fields(array('hidden','customized'))
    ->values(array(
              'hidden' => 0,
              'customized' => 1,
            ))
    ->execute();
  }


	menu_rebuild();
	
	// block assignments are handled in sabreQMS.module  hook_block_list_alter()
}


/*
 * _qms_roles_permissions()
 * 
 * creates the special QMS roles and turns on permissions as required
 */

function _qms_roles_permissions() {
	
	$role = new stdClass();
	
	
	// Customer = 4
	
	$role->name = 'customer';
	$role->weight = 2;
	unset($role->rid);  // unset from previous save -- creating a new role
	user_role_save($role);

  user_role_change_permissions($role->rid, 
                                array(
                                    // sabreQMS
                                    'access sabreQMS' => True,
                                    'add discrepancy comments' => True,
                                    'add discrepancy files' => True,
                                    'create discrepancy' => True,
                                    'add trouble call comments' => True,
                                    'create trouble call log' => True,
                                    'search view logs' => True,
                                    'search view reports' => True,
                                    'user feedback' => True,
                                    'view admin lists' => True,
                                ));

	
	
	// Employee = 5
	$role->name = 'employee';
	$role->weight = 3;
	unset($role->rid);  // unset from previous save -- creating a new role
	user_role_save($role);

  user_role_change_permissions($role->rid, 
                                    array(
                                        // sabreQMS
                                        'access sabreQMS' => True,
                                        'punch clock' => True,
                                        'search view logs' => True,
                                        'search view reports' => True,
                                        'user feedback' => True,
                                        'view admin lists' => True,
                                    ));
	
    // Technician = 6
    $role->name = 'technician';
    $role->weight = 5;
    unset($role->rid);  // unset from previous save -- creating a new role
    user_role_save($role);

    user_role_change_permissions($role->rid, 
                                    array(
                                        // sabreQMS
                                        'access sabreQMS' => True,
                                        'add discrepancy comments' => True, 
                                        'add discrepancy files' => True, 
                                        'add discrepancy parts' => True,
                                        'add trouble call comments' => True,
                                        'close discrepancy' => True, 
                                        'create discrepancy' => True, 
                                        'create trouble call log' => True,
                                        'create engineering log' => True, 
                                        'create shift log' => True, 
                                        'create simulator downtime' => True,
                                        'create vendor' => True,
                                        'edit discrepancy' => True, 
                                        'edit discrepancy parts' => True,
                                        'edit trouble call log' => True,
                                        'edit qtg event' => True,
                                        'edit vendor' => True,
                                        'punch clock' => True, 
                                        'search view logs' => True, 
                                        'search view reports' => True, 
                                        'set discrepancy flags' => True, 
                                        'user feedback' => True, 
                                        'view admin lists' => True, 
                                    ));
	
	
    // Instructor = 7
    $role->name = 'instructor';
    $role->weight = 4;
    unset($role->rid);  // unset from previous save -- creating a new role
    user_role_save($role);

    user_role_change_permissions($role->rid, 
                                array(
                                    // sabreQMS
                                    'access sabreQMS' => True, 
                                    'add discrepancy comments' => True, 
                                    'add discrepancy files' => True, 
                                    'add discrepancy parts' => True,
                                    'add trouble call comments' => True,
                                    'create discrepancy' => True, 
                                    'create trouble call log' => True,
                                    'create simulator downtime' => True,
                                    'edit discrepancy parts' => True,
                                    'edit qtg event' => True,
                                    'punch clock' => True, 
                                    'search view logs' => True, 
                                    'search view reports' => True, 
                                    'view admin lists' => True, 
                                ));
  
	
    // Contractor = 8
    $role->name = 'contractor';
    $role->weight = 3;
    unset($role->rid);  // unset from previous save -- creating a new role
    user_role_save($role);
  
    user_role_change_permissions($role->rid, 
                                array(
                                    // sabreQMS
                                    'access sabreQMS' => True, 
                                    'add discrepancy comments' => True, 
                                    'add discrepancy files' => True, 
                                    'add trouble call comments' => True,
                                    'create discrepancy' => True, 
                                    'create trouble call log' => True,
                                    'create engineering log' => True, 
                                    'create shift log' => True, 
                                    'punch clock' => True, 
                                    'search view logs' => True, 
                                    'search view reports' => True, 
                                    'user feedback' => True, 
                                    'view admin lists' => True, 
                                ));

}


/*
 * _scheduler_roles_permissions()
 * 
 * creates the special Scheduler roles and turns on permissions as required
 */

function _scheduler_roles_permissions() {
	
	$role = new stdClass();
	
	// Student = 4
	$role->name = 'student';
	$role->weight = 2;
	unset($role->rid);  // unset from previous save -- creating a new role
	user_role_save($role);

  user_role_change_permissions($role->rid, 
															array(
																'access sabreScheduler' => True,
															));
	
	// Instructor = 5
	$role->name = 'instructor';
	$role->weight = 3;
	unset($role->rid);  // unset from previous save -- creating a new role
	user_role_save($role);

  user_role_change_permissions($role->rid, 
															array(
																'access sabreScheduler' => True,
															));
	
	// Manager = 6
	$role->name = 'manager';
	$role->weight = 4;
	unset($role->rid);  // unset from previous save -- creating a new role
	user_role_save($role);

  user_role_change_permissions($role->rid, 
															array(
																'access sabreScheduler' => True,
																'view manage menu' => True, 
                                'edit schedules' => True,
                                'edit settings' => True,
                                'administer users' => True,
															));
	
}





/*
 * _qms_example_records()
 * 
 * inserts one example record in each of 'Simulator' and 'Customer' tables as the system expects at least one to exist
 * and system will function properly.
 */

function _qms_example_records() {


	$customer = (object) NULL;
	
	$customer->customer = t('Example Customer');
	$customer->active = 1;
	$customer->notify_employee_user_id = 0;
	
	// Table:  {qms_customers}
	if ( False == drupal_write_record('qms_customers', $customer)) {
		$msg = "Error saving the Example Customer record to the database.";
		drupal_set_message(t($msg));
	}
	
	
	$simulator = (object) NULL;
	
	$simulator->active = 1;
	$simulator->customer_id = $customer->customer_id;
	$simulator->sim_name = t('Example Simulator');
  $simulator->faa_id = '';
  $simulator->device_id_internal = '1';
	
	
	// Table:  {qms_simulators}
	if ( False == drupal_write_record('qms_simulators', $simulator)) {
		$msg = "Error saving the Example Simulator record to the database.";
		drupal_set_message(t($msg));
	}
  
}


/*
 * _scheduler_example_customer()
 * 
 * inserts one example record in each of 'Simulator' and 'Customer' tables as the system expects at least one to exist
 * and system will function properly.
 */

function _scheduler_example_customer() {


	$customer = new stdClass();
	
	// Make the first customer, the organization getting the install
	$customer->customer = variable_get('organization_name', 'Example Customer');
	$customer->customer_code = substr($customer->customer, 0, 5);
	$customer->active = 1;
	$customer->created_date = time();
	$customer->created_by_user = 1;  // admin user
	
	// Table:  {qms_customers}
	if ( False == drupal_write_record('sch_customers', $customer)) {
		$msg = "Error saving the Example Customer record to the database.";
		drupal_set_message(t($msg));
	}
	
}

/*
 * _scheduler_example_simulator()
 * 
 * loads an example simulator
 */

function _scheduler_example_simulator() {
	
	$values = array(
		array(
			'simulator_id' => 1,
			'sim_name' => 'Example Simulator', 
      //'faa_id' => '',
      'device_id_internal' => '1',
			'active' => 1, 
			'created_date' => time(), 
			'created_by_user' => 1 
		),
	);

	$query = db_insert('sch_simulators')
					 ->fields(array('simulator_id', 'sim_name', 'active', 
                          'device_id_internal', 
                          'created_date', 'created_by_user'));
  foreach ($values as $record) {
    $query->values($record);
  }
  $query->execute();
	
}

/*
 * _scheduler_sim_base_types()
 * 
 * preloads utility tables
 */

function _scheduler_sim_base_types() {
	
	// sch_session_types
	$values = array(
		array( 'session_type' => 1, 'session_type_desc' => 'Full Motion' ),
		array( 'session_type' => 2, 'session_type_desc' => 'Fixed Base' ),
	);

	$query = db_insert('sch_session_types')
					 ->fields(array('session_type', 'session_type_desc'));
  foreach ($values as $record) {
    $query->values($record);
  }
  $query->execute();
	
	
	// sch_flight_roles
	$values = array(
		array( 'flight_role_code' => 'PF', 'flight_role_name' => 'Pilot' ),
		array( 'flight_role_code' => 'PNF', 'flight_role_name' => 'Support Pilot' ),
		array( 'flight_role_code' => 'INS', 'flight_role_name' => 'Instructor' ),
    array( 'flight_role_code' => 'CHK', 'flight_role_name' => 'Checkairman' ),
		array( 'flight_role_code' => 'OBS', 'flight_role_name' => 'Observer' ),
		array( 'flight_role_code' => 'OBS2', 'flight_role_name' => 'Observer' ),
		array( 'flight_role_code' => 'FAA', 'flight_role_name' => 'Observer' ),
		array( 'flight_role_code' => 'DGAC', 'flight_role_name' => 'Observer' ),
	);

	$query = db_insert('sch_flight_roles')
					 ->fields(array('flight_role_code', 'flight_role_name'));
  foreach ($values as $record) {
    $query->values($record);
  }
  $query->execute();
	
	
	// sch_session_names
	$values = array(
		array( 'session_name' => 'Session A'),
		array( 'session_name' => 'Session B'),
		array( 'session_name' => 'Session C'),
		array( 'session_name' => 'Session D'),
		array( 'session_name' => 'Session E'),
		array( 'session_name' => 'Session F'),
	);

	$query = db_insert('sch_session_names')
					 ->fields(array('session_name'));
  foreach ($values as $record) {
    $query->values($record);
  }
  $query->execute();
	
	
	// sch_schedule_patterns
	$now = time();
	$values = array(
		array( 'pattern_name' => 'No Gaps', 'created_date' => $now, 'created_by_user' => 1),
		array( 'pattern_name' => 'Gaps-15min', 'created_date' => $now, 'created_by_user' => 1),
	);

	$query = db_insert('sch_schedule_patterns')
					 ->fields(array('pattern_name', 'created_date', 'created_by_user'));
  foreach ($values as $record) {
    $query->values($record);
  }
  $query->execute();
	
	
	// sch_pattern_sessions
	$now = time();
	$values = array(
		array( 
			'schedule_pattern_id' => 1, 
			'session_name_id' => 1, 
			'begin_time' => '0200',
			'end_time' => '0600',
		),
		array( 
			'schedule_pattern_id' => 1, 
			'session_name_id' => 2, 
			'begin_time' => '0600',
			'end_time' => '1000',
		),
		array( 
			'schedule_pattern_id' => 1, 
			'session_name_id' => 3, 
			'begin_time' => '1000',
			'end_time' => '1400',
		),
		array( 
			'schedule_pattern_id' => 1, 
			'session_name_id' => 4, 
			'begin_time' => '1400',
			'end_time' => '1800',
		),
		array( 
			'schedule_pattern_id' => 1, 
			'session_name_id' => 5, 
			'begin_time' => '1800',
			'end_time' => '2200',
		),
		array( 
			'schedule_pattern_id' => 1, 
			'session_name_id' => 6, 
			'begin_time' => '2200',
			'end_time' => '0200',
		),
		array( 
			'schedule_pattern_id' => 2, 
			'session_name_id' => 1, 
			'begin_time' => '0215',
			'end_time' => '0615',
		),
		array( 
			'schedule_pattern_id' => 2, 
			'session_name_id' => 2, 
			'begin_time' => '0630',
			'end_time' => '1030',
		),
		array( 
			'schedule_pattern_id' => 2, 
			'session_name_id' => 3, 
			'begin_time' => '1045',
			'end_time' => '1445',
		),
		array( 
			'schedule_pattern_id' => 2, 
			'session_name_id' => 4, 
			'begin_time' => '1500',
			'end_time' => '1900',
		),
		array( 
			'schedule_pattern_id' => 2, 
			'session_name_id' => 5, 
			'begin_time' => '1915',
			'end_time' => '2315',
		),
		array( 
			'schedule_pattern_id' => 2, 
			'session_name_id' => 6, 
			'begin_time' => '2330',
			'end_time' => '0200',
		),
	);

	$query = db_insert('sch_pattern_sessions')
					 ->fields(array('schedule_pattern_id', 'session_name_id', 'begin_time', 'end_time'));
  foreach ($values as $record) {
    $query->values($record);
  }
  $query->execute();
	
}

/*
 * _scheduler_calendar()
 * 
 * preloads calendar reference table
 */

function _scheduler_calendar() {
	
	// create reference 'ints' records
	$query_i = db_insert('sch_ints')
					 ->fields(array('i'));
  for($i=0; $i<10; $i++) {
    $query_i->values(array($i));
  }
  $query_i->execute();

	//db_query("ALTER TABLE sch_calendar DROP PRIMARY KEY");
	
	// create the calendar timeline
	$sql = "INSERT INTO sch_calendar (calendar_date) 
						SELECT UNIX_TIMESTAMP(STR_TO_DATE('2016-10-01', '%Y-%m-%d') + INTERVAL (th.i*1000 + h.i*100 + t.i*10 + o.i) DAY) AS `calendar_date` 
						FROM sch_ints AS th
						JOIN sch_ints AS h
						JOIN sch_ints AS t
						JOIN sch_ints AS o
						WHERE (th.i*1000 + h.i*100 + t.i*10 + o.i) <10000
            HAVING calendar_date IS NOT NULL";
	$result = db_query($sql);
	
	// remove calendar dates that exceed the unix date limitation
	//$sql = "DELETE FROM sch_calendar WHERE calendar_date = 0 or calendar_date is null;";
	//$result = db_query($sql);
	
	
	// after table loaded, create the primary key index
	//db_query("ALTER TABLE sch_calendar ADD PRIMARY KEY(calendar_date)");

	
	// add the display dates 
	$sql = "UPDATE sch_calendar
					SET display_date = FROM_UNIXTIME(calendar_date, '%Y-%m-%d') 
					WHERE calendar_date > 0 and calendar_date is not null";
	$result = db_query($sql);

	
}




function _set_app_root($appcode) {
  
  $var_name = ($appcode == PROFILE_APP_SCHEDULER) ? 'sabre_scheduler_root' : 'sabre_qms_root';
  variable_set($var_name, DRUPAL_ROOT);
}


