<?php

/*
 *	Trouble Causes record functions for sabreQMS module
 */



/*
 *	trouble_causes_display()
 *
 *	returns:  Displays table list of simulators
 *
 */

function trouble_causes_display() {
	
	if (user_access('view admin lists') == False) {
		return;
	}
	
	
	// Check permissions -- only allow editing capabilities if 'administer officers' enabled
	$bAllowAdmin = user_access('administer sabreQMS');

	$table_header = array( 
		array( 'data' => 'Trouble Cause' ),
	);
	
	if ( $bAllowAdmin == True ) {
		$table_header[] = array(
			'data' => 'Admin',
			//'class' => 'sorttable_nosort',
		);
	}
	
	
	// Get list of chapters
	$result = db_query("SELECT trouble_cause_code, trouble_cause_desc 
                      FROM {qms_trouble_causes} ORDER BY trouble_cause_desc ASC");

	$i = 0;
	$table_rows = array();
	
	foreach ($result as $row) {
		
		
		$row_data = array(
			$row->trouble_cause_desc,
		);
		
		if ( $bAllowAdmin == True ) {
			$row_data[] = _st_generate_options('trouble_cause', $row->trouble_cause_code);
		}
		
		$table_rows[] = array( 'data' => $row_data	);
		$i++;
	}

	$content = '';

	if ( $bAllowAdmin )
	{
		$content = l( t('Add Trouble Cause'), 'trouble_cause/add', array('class' => 'trouble_cause_add') );
	}
	
	$content .= theme('table', array(
		'header' => $table_header,
		'rows' => $table_rows,
		'empty' => t('None'),
	));

	return $content;
}

/*
 *	trouble_cause_form()
 *
 *  overloads:  hook_form()
 *
 *	Displays the customer form for adding/updating
 */

function trouble_cause_form($form, $form_state, $trouble_cause_code = 0) {

	if ( user_access('administer sabreQMS') == FALSE ) {
    drupal_set_message( t('Unauthorized.  Administrator access required'));
    drupal_goto('');
    return;
  }
  
	$trouble_cause_desc = '';
  
  if ( $trouble_cause_code ) {   // Edit existing record
		
		// get the record
		$sql = "SELECT trouble_cause_desc 
            FROM {qms_trouble_causes} 
            WHERE trouble_cause_code = :cid";
		$result = db_query($sql, array(':cid' => $trouble_cause_code));
		
		if ( $result->rowCount() == 0 ) {
	    drupal_set_message( t('Oops!  Something seems to have gone wrong.  ' . 
                          'Trouble Cause not found.'));
			drupal_goto('qmssettings/trouble_causes');
			return;
	  }
		
		$trouble_cause_desc = $result->fetchField();
	}
	
	$form['trouble_cause_desc'] = array(
		'#type' => 'textfield',
		'#title' => t('Trouble Cause Description'),
		'#maxlength' => 255,
    '#size' => 70,
		'#default_value' => $trouble_cause_desc,
	);		
	
	$form['trouble_cause_code'] = array(
		'#type' => 'value',
		'#value' => $trouble_cause_code,
	);				
		
	
	
	
	$form['actions'] = array('#type' => 'actions');
	$form['actions']['submit'] = array(
		'#type' => 'submit',
		'#value' => t('Submit'),
    '#attributes' => array('class' => array('qms-btn-submit')),
	);
  $form['actions']['done'] = array(
		'#type' => 'button',
		'#value' => t('Done'),
		'#attributes' => array('class' => array('qms-btn-done', 'qms-btn-extra'),
                           'onclick' => 'window.location="' . 
                                url('qmssettings/trouble_causes') . '"; return false;'),
	);
	

	return $form;
}

/*
 *	trouble_cause_form_validate()  
 *
 *  overloads:  hook_form_validate()
 *
 *	Validates form after it is submitted
 */

function trouble_cause_form_validate($form, $form_state) {
	if ( trim($form_state['values']['trouble_cause_desc']) == '' ) {
		form_set_error('trouble_cause_desc', t('Trouble Cause Description is a required field.'));
	}
}

/*
 *	simulator_form_submit()  
 *
 *  overloads:  hook_form_submit()
 *
 *	Saves customer_form data upon successful submit
 */

function trouble_cause_form_submit($form, $form_state) {
  
	$trouble_cause = new stdClass();
  $id_field = '';
	
	$trouble_cause_code = (int)$form_state['values']['trouble_cause_code'];
	$trouble_cause->trouble_cause_desc = trim($form_state['values']['trouble_cause_desc']);
	

	if  ( $trouble_cause_code )  {  
    // update existing
    $id_field = 'trouble_cause_code';
    $trouble_cause->trouble_cause_code = $trouble_cause_code;
  }
  else {
    $id_field = array();
  }
  
  // save record
  // Table:  {qms_trouble_causes}
  if ( False == drupal_write_record('qms_trouble_causes', $trouble_cause, $id_field) ) {
    $msg = "Oops!  Something went wrong saving the Trouble Cause record.";
    drupal_set_message(t($msg));
    drupal_goto('qmssettings/trouble_causes');
    return;
  }
	
//	global $chapter_list;
//	$chapter_list->reload();
  
	drupal_set_message(t('Trouble Cause saved successfully.'));
	drupal_goto('qmssettings/trouble_causes');
}



/*
 *	trouble_cause_delete_confirm()  
 *
 *	Validate and Ask for confirmation before deleting record
 */

function trouble_cause_delete_confirm($form, $form_state, $trouble_cause_code = 0) {
  
  try{
	
    if ( user_access('administer sabreQMS') == FALSE ) {
      form_set_error( t('Unauthorized Access'), t('Administrator access required.'));
      drupal_goto('qmssettings/trouble_causes');
      return;	
    }
    
    if ( !$trouble_cause_code ) {
      drupal_set_message( t('Oops!  Something seems to have gone wrong.  ' . 
                        'Trouble Cause not found. Invalid ID.'));
      drupal_goto('qmssettings/trouble_causes');
      return;
    }

    // Get record by id
    $sql = "SELECT trouble_cause_desc FROM {qms_trouble_causes} 
            WHERE trouble_cause_code = :id";
    $result = db_query($sql, array(':id' => $trouble_cause_code));

    if ( $result->rowCount() == 0 ) {
      drupal_set_message( t('Oops!  Something seems to have gone wrong.  ' . 
                        'Trouble Cause not found.'));
      drupal_goto('qmssettings/trouble_causes');
      return;
    }


    $trouble_cause_desc = $result->fetchField();


    // check if the Trouble Cause is linked to a TC record
    $sql = "SELECT trouble_call_id FROM {qms_trouble_call_log} 
            WHERE trouble_cause_code = :id LIMIT 1";
    $result = db_query($sql, array(':id' => $trouble_cause_code));
    if ( $result->rowCount() ) {
      // cannot delete, customer linked to discrepancy records
      $msg = "Unable to delete.  Trouble Cause is linked to Trouble Call Log records.";
      drupal_set_message(t($msg));	
      drupal_goto('qmssettings/trouble_causes');
      return;	
    }	

    $form['trouble_cause_code'] = array(
      '#type' => 'value',
      '#value' => $trouble_cause_code,
    );

    $form['trouble_cause_desc'] = array(
      '#type' => 'value',
      '#value' => $trouble_cause_desc,
    );

    $title = t('Delete Trouble Cause') . '?';
    $question = t('Are you sure you want to delete?') . 
                '<h2>' . $trouble_cause_desc . '</h2><br />' . 
                t('This action cannot be undone.');
    $goto_if_canceled = 'qmssettings/trouble_causes';
    $yes_btn = 	t('Delete');
    $no_btn = t('Cancel');

    return confirm_form($form, $title,	$goto_if_canceled, $question, $yes_btn, $no_btn);	
  }
  catch(Exception $e) {
    watchdog('sabreQMS', 'trouble_cause_delete_confirm()' . $e->getMessage(), 
            array(), WATCHDOG_ERROR);
	
  }
}

/*
 *	trouble_cause_delete_confirm_submit()  
 *
 *	Submit after confirmation, delete the specified record
 */

function trouble_cause_delete_confirm_submit($form, $form_state) {
	
	if ( $form_state['values']['confirm']) {
		$trouble_cause_code = (int)$form_state['values']['trouble_cause_code'];
		$trouble_cause_desc = $form_state['values']['trouble_cause_desc'];
	
	
		// delete from database
		$num_rows = db_delete('qms_trouble_causes')
								->condition('trouble_cause_code', $trouble_cause_code, '=')
								->execute();
	
		$msg = '';					
		if ( $num_rows == 1 ) {
			$msg = 'Trouble Cause, "' . $trouble_cause_desc . '", has been deleted.';
		}
		else {
			$msg = 'Oops!  Unable to delete record for, "' . $trouble_cause_desc . '".';
		}
	
		drupal_set_message(t($msg));

    _clear_qms_cache(QMS_TROUBLE_CAUSE_LIST);
		_clear_qms_cache(QMS_TROUBLECALL_SEARCH_FORM); 
	}
	
	drupal_goto('qmssettings/trouble_causes');
}

