<?php
// $Id$

/**
 *		@file
 *		sabreQMS Module for plugin to Drupal 7 Framework
 *
 *		SHIFT LOG
*/

//require_once('sabreQMS.utils.inc');
require_once('sabreQMS.shiftloglist.inc');
require_once('sabreQMS.files.inc');
require_once('sabreQMS.shiftlogfiles.inc');


/*
 *	shift_log_form()
 *
 *  overloads:  hook_form()
 *
 *	Displays a Shift Log Entry form to accept user input
 */
function shift_log_form($form, $form_state, $shift_log_id = 0) {

  $bAdmin = user_access('administer sabreQMS');

  if ( (user_access('create shift log') == FALSE) && ($bAdmin == FALSE) ) {
    drupal_set_message( t('Unauthorized:  Permission required'), 'status');
    return;
  }

  // javascript loaded in the after_build function
  $form['#after_build'][] = 'shift_log_form_after_build';


  $shift_log = (object) Null;
  $sl_files = array();
  global $base_url;

  $destination = drupal_get_destination();
  $goto_url = $destination['destination'];

  if( !strlen($goto_url) || ($goto_url == current_path()) ) {
    $goto_url = 'search/shiftlog';
  }


  if ( $shift_log_id > 0 ) {
    // EDITING EXISTING LOG ENTRY  (Admin Only!!!)

    if ( !$bAdmin ) {
      drupal_set_message( t('Unauthorized:  Permission required to edit a shift log entry.'), 'status');
      drupal_goto($goto_url);
      return;
    }

    // get the shift log record
    $shift_log = _get_shift_log($shift_log_id);

    if ( $shift_log == (object) Null ) {
      drupal_set_message( t('Shift Log Not Found!'), 'warning');
      drupal_goto($goto_url);
      return;
    }

    $sl_files = _get_shift_log_files($shift_log_id);
  }


  global $simulator_list;
  global $tech_list;


  // storage field for the shift_log_id (edit) -- hidden
  $form['shift_log_id'] = array(
    '#type' => 'textfield',
    '#default_value' => $shift_log_id,
    '#attributes' => array('id' => 'qms-shift-log-id',
                            'class' => array('qms-hidden-field')),
  );

  $sldate = '';
  if ( $shift_log_id > 0 ) {

    $form['shift_log_timestamps'] = array(
      //'#markup' => '<div class="qms-desc">Last Updated:  ' . _st_format_date($shift_log->updated_date, 'medium') . '</div>',
      '#markup' => _st_format_record_timestamp_table($shift_log),
    );


    $sldate = _st_format_date($shift_log->datetime, 'short');

    // storage field for the shift_log_date (edit) -- hidden
    $form['original_datetime'] = array(
      '#type' => 'textfield',
      '#default_value' => $sldate,
      '#attributes' => array('id' => 'qms-original-datetime',
                              'class' => array('qms-hidden-field')),
    );

    $sldate = substr($sldate, 0, 10); // chop off the time portion for display purposes
  }

  $form['datetime'] = array(
    '#type' => 'date_popup',
    '#title' => t('Entry Date'),
    '#size' => 12,
    '#date_format' => 'm-d-Y',						// displayed format
      //default value has to be in this format
    '#default_value' => (($shift_log_id > 0) ? $sldate : date('Y-m-d')),
    '#required' => True,   // if no date entered, returns NULL
    '#attributes' => array('id' => 'qms-shift-log-date'),
    '#prefix' => '<table class="qms-plain-table" style="width:50%;"><tr style="vertical-align:bottom;"><td>',
    '#suffix' => '</td>',
  );

  global $user;

  // we don't need to save the tech user id on the form
  // new shift log, store the current user_id (logged-in)
  // editing shift log, user cannot be changed
  $form['tech_name'] = array(
    '#type' => 'item',
    '#title' => t('Technician/Instructor'),
    '#markup' => (($shift_log_id > 0) ? _get_user_name($shift_log->employee_user_id) : _get_user_name($user->uid)),
    '#prefix' => '<td>',
  );

  $form['simulator'] = array(
    '#type' => 'select',
    '#title' => t('Simulator'),
    '#options' => $simulator_list->getActive(),
    '#default_value' => (($shift_log_id > 0) ? $shift_log->simulator_id : 0),
    '#required' => True,
    '#attributes' => array('class' => array('qms-select'),
                           'id' => 'qms-simulator-select'),
    '#suffix' => '</td></tr></table>',
  );

  //------------- ADD SHIFTLOG COMMENT TEXTAREA  -----------

  $text_settings = array(
    'name' => 'comment_text',
    'title' => t('Comment'),
    'text' =>	(($shift_log_id > 0) ? $shift_log->comment : ''),
    'required' => True,
    'disabled' => False,
  );

  _st_add_text_editor($form, $text_settings);

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

  if ( $shift_log_id > 0 )  {

    // edit existing -- handle file interface differently
    // for existing shift log, display table of files attached.

    $table_headers = array(array('data' => 'Files', 'class' => 'qms-files-tbl-col1'),
                           array('data' => 'Uploaded By', 'class' => 'qms-files-tbl-col2'),
                          );
    $table_rows = array();

    //if ( $user_perms->admin || $user_perms->delete_discrepancy_files  ) {
    $table_headers[] = array('data' => 'Admin');
    //}

    $i = 0;
    foreach ( $sl_files as $f ) {
      $table_rows[] = array( 
        'data' => array( 
            l( t($f->file_name), 
               "shiftlog/file/download/" . $f->file_id,
               array('attributes' => array('target'=>'_blank')) ),
            $f->name . ' - ' . _st_format_date($f->uploaded_timestamp, 'short'),
        ) );
      //if ( $user_perms->admin || $user_perms->delete_discrepancy_files ) {
        // admin can edit/delete comments, all done through ajax calls
        $table_rows[$i]['data'][] =  l( t('Delete'), "shiftlog/file/delete/" . $f->file_id,
                                          array('attributes' => array('class' => 'qms-file-delete') ) );
      //}
      $i++;
    }



    $files_table = theme( 'table', array(
      'header' => $table_headers,
      'rows' => $table_rows,
      'empty' => t('None'),
    ));

    unset($table_headers);
    unset($table_rows);
  }

  $form['fs_files'] = array(
    '#type' => 'fieldset',
    '#title' => t('Files To Attach'),
    '#collapsible' => True,
    '#collapsed' => ( !count($sl_files) ),
  );

  $form['fs_files']['files_begin_div'] = array(
    '#markup' => '<div id="qms-files-div">',
  );


  if ( $shift_log_id > 0 ) {
    $form['fs_files']['files'] = array(
      '#markup' => $files_table,
      '#prefix' => '<div id="qms-files-tbl-div">',
      '#suffix' => '</div>',
    );
  }

  $form['fs_files']['chk_add_file'] = array(
    '#type' => 'checkbox',
    '#title' => t('Add Files to this Report') . '<span class="qms-waiting"><img class="qms-waiting-img" src="' .
                                                $base_url . QMS_IMAGES_DIR . 'waiting.gif" /></span>',
    '#suffix' => '<div class="qms-desc">You will be prompted to upload files on the next screen.</div>',
    '#default_value' => 0,
    '#attributes' => array('id' => 'qms-add-files-chk'),
    '#suffix' => '<div class="qms-desc">You will be prompted to upload files on the next screen.</div>',
  );


  $form['fs_files']['files_end_div'] = array(
    '#markup' => '</div>',
  );



  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#name' => 'submit',
    '#attributes' => array('class' => array('qms-btn-submit')),
  );


  if ( $shift_log_id > 0 ) {
    // if the user is an Admin, they are allowed to edit and to delete
    /*
    $form['actions']['delete'] = array(
      '#markup' => l(t('Delete'), 'shiftlog/delete/' . $shift_log_id,
                                  array('attributes' => array('id' => 'qms-btn-delete'),
                                        'query' => array('destination' => $goto_url))),
    );*/

    $form['actions']['delete'] = array(
      '#type' => 'submit',
      '#value' => t('Delete'),
      '#name' => 'delete',
      '#attributes' => array('class' => array('qms-btn-delete', 'qms-btn-extra')),
    );
  }

  $form['actions']['done'] = array(
    '#type' => 'button',
    '#value' => t('Done'),
    '#name' => 'done',
    '#attributes' => array('class' => array('qms-btn-done', 'qms-btn-extra'),
                           'onclick' => 'window.location="' .
                                        url($goto_url) . '"; return false;'),
  );

    /*
  $form['actions']['cancel'] = array(
    '#markup' => l(t('Cancel'), $goto_url,
                  array('attributes' => array('id' => 'qms-btn-cancel'))),
  );*/


  // storage area for dynamic dialog element
  $form['popup_dialog'] = array(
    '#markup' => '<div id="qms-message-box"></div>',
  );

  $form['report_changed'] = array(
    '#type' => 'textfield',
    '#default_value' => 0,
    '#attributes' => array('id' => 'qms-report-changed',
                            'class' => array('qms-hidden-field')),
  );

  return $form;
}

/*------ AFTER BUILD FUNCTION --------
*	 functions called, as it implies, after the form is built
*  this is necessary when custom javascript and/or css files are added as needed
*  at the page level for forms that go through validation with hook_form_validate()
*  Otherwise, if a form fails validation, the page/form is reloaded for the user to correct
*  but the accompanying javascript & css is not reloaded with it.
*  when $form['#after_build][] is used, the external scripts will be reloaded properly.
*/

/*
 * shift_log_form_after_build()
 *
 */
function shift_log_form_after_build($form, &$form_state)
{
  drupal_add_library('system','ui.datepicker');
  drupal_add_library('system','ui.dialog');
  $sabreTools = drupal_get_path('module', 'sabreTools');
  drupal_add_js($sabreTools . '/js/sabreTools.lib.js');
  drupal_add_js($sabreTools . '/js/sabreTools.ckeditor.js');

  drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.shiftlog.js');

  // WYSIWYG EDITOR??  Is this feature enabled allowing for the editor
  if ( isset( $form['ckeditor_module_path'])  ) {
    global $base_url;
    drupal_add_js( $base_url . QMS_CKEDITOR_PATH_CONFIG);
    // need to specify preprocess == false otherwise 'Aggregate Javascript' setting in drupal
    // causes ckeditor not to load properly
    // adding scope to footer speeds up the page load
    drupal_add_js( $base_url . QMS_CKEDITOR_LIB, array('type' => 'file', 'scope' => 'footer', 'preprocess' => FALSE));
  }

  return $form;
}


/*
 *	shift_log_form_validate()
 *
 *  overloads:  hook_form_validate()
 *
 *	Validates the Shift Log entry form
 */

function shift_log_form_validate($form, $form_state) {

  $button_clicked = $form_state['triggering_element']['#name'];

  if ( $form['actions']['submit']['#name'] != $button_clicked ){
    return $form;
  }

  $sl_datetime = trim($form_state['values']['datetime']);

  if ( !isset($sl_datetime) || ($sl_datetime == '') ) {
    form_set_error('datetime', t('Unable to add Shift Log entry.  Date is a required field'));
  }
  if ( (int) $form_state['values']['simulator'] == 0 ) {
    form_set_error('simulator', t('Unable to add Shift Log entry.  Simulator is a required field'));
  }

  // comment_editor_value is ALWAYS the field that the comment text field gets pushed to on submit
  // this is a kluge to deal with a CKEditor bug
  if ( trim($form_state['values']['comment_text_editor_value']) == '' ) {
    form_set_error('comment', t('Unable to add Shift Log entry.  Comment is a required field'));
  }

}

/*
 *	shift_log_form_submit()
 *
 *  overloads:  hook_form_submit()
 *
 *	Handles the Shift Log form submitted data, stores to db
 */
function shift_log_form_submit($form, $form_state) {

  //---------------- Button Handlers --------------------

  $button_clicked = $form_state['triggering_element']['#name'];

  if ( isset($form['actions']['delete']['#name']) &&
       ($form['actions']['delete']['#name'] == $button_clicked) ){

    $shift_log_id = isset($form_state['values']['shift_log_id']) ?
                        (int) $form_state['values']['shift_log_id'] : 0;

    if ( !$shift_log_id && isset($form['shift_log_id']['#default_value'])) {
      $shift_log_id = $form['shift_log_id']['#default_value'];
    }
    if ( $shift_log_id ) {
      $_GET['destination'] = 'shiftlog/delete/' . $shift_log_id .
                            '?destination=shiftlog/edit/' . $shift_log_id;
    }
  }
  else if ( isset($form['actions']['done']['#name']) &&
            ($form['actions']['done']['#name'] == $button_clicked) ){

    $destination = drupal_get_destination();
    $goto_url = $destination['destination'];

    if( !strlen($goto_url) || ($goto_url == current_path()) ) {
      $goto_url = 'search/shiftlog';
    }

    drupal_goto($goto_url);
  }
  else if ( $form['actions']['submit']['#name'] != $button_clicked ) {
    // if not delete & not done, then make sure its a submit click, otherwise, return
    return;
  }

  //---------------- SUBMIT:  Process Form --------------------

  $shift_log = (object) NULL;
  global $user;
  $bUpdate = False;
  $msg = '';

  $shift_log_id = (int) $form_state['values']['shift_log_id'];
  $shift_log->shift_log_id = $shift_log_id;  // we need to save this separately

  $add_files = (isset($form_state['values']['chk_add_file']) ? (int)$form_state['values']['chk_add_file'] : 0 );


  if ( (int)$form_state['values']['report_changed'] == 0 ) {
    // nothing changed in the SL, do not update... route
    if ( $add_files ) {
      // route to file upload form
      drupal_goto('shiftlog/file/add/' . $shift_log->shift_log_id);
    }
    else {
      if ( user_access('administer sabreQMS') == True ) {
        drupal_goto('shiftlog/edit/' . $shift_log->shift_log_id);
      }
      else if ( user_access('search view logs') == True ) {
        drupal_goto('shiftlog/view/' . $shift_log->shift_log_id);
      }
      else {
        drupal_goto(''); // go to home page if permissions don't allow a search
      }
    }
    return;
  }

  // WYSIWYG EDITOR??  Is this feature enabled allowing for the editor
  //$ckeditor_activated  = variable_get(QMS_VAR_WYSIWYG_EDITOR, 1);  // if not set, default to ON

  $shift_log->simulator_id = (int) $form_state['values']['simulator'];
  $currtimestamp = REQUEST_TIME;
  $append_time = _st_get_time();

  $sl_date = substr($form_state['values']['datetime'], 0, 10);


  if ( $shift_log->shift_log_id > 0 ) {  // editing shift log
    $bUpdate = True;

    // compare only the date portion of the datetime field to see if it changed
    $orig_date = $form_state['values']['original_datetime'];

    if ( $sl_date <> substr($orig_date, 0, 10) )  {
      // date changed from original, add a new time portion and
      // include it in the $shift_log record to save
      // add time to make it DATE_ISO format:  'YYYY-MM-DD HH24:MI:SS'
      $sl_date .= ' ' . $append_time;
    }
    else {
      $sl_date = substr($orig_date, 0, 10) . ' '  . $append_time;
    }
  }
  else {  // new shift log
    // add time to make it DATE_ISO format:  'YYYY-MM-DD HH24:MI:SS'

    // this can be different than the current time so don't set this to the 'created' or 'updated_date' date
    $sl_date .= ' ' . $append_time;

    // set the shift log user id to the current user (this doesn't get changed during an edit)

    $shift_log->employee_user_id = $user->uid;
    $shift_log->created_date = $currtimestamp;
    $shift_log->created_by_user = $user->uid;
    $shift_log->created_by_ip_address = _st_get_ip_address();
  }

  $shift_log->datetime = _st_format_timestamp($sl_date);   // convert to unix time
  $shift_log->updated_date = $currtimestamp;		// always update this, even at create time
  $shift_log->updated_by_user = $user->uid;
  $shift_log->updated_by_ip_address = _st_get_ip_address();

  // comment length is controlled from the browser, but if that fails for some reason, trim it here

  /*  The comment text field is being updated to the $form['comment_editor_value'] field
  **  whether the editor is enabled or not.  That is the field from which we''ll will always get the value of
  **  comment text, validate and save.
  **
  ** ----------- this code is no longer used----------------------
  if ( $ckeditor_activated ) {
    $shift_log->comment = substr(trim($_POST['qms_shift_log_comment']), 0, QMS_TEXTAREA_MAX);
  }
  else {
    $shift_log->comment = substr(trim($form_state['values']['comment']), 0, QMS_TEXTAREA_MAX);
  }
  */

  $shift_log->comment = _st_clean_ckeditor_text($form_state['values']['comment_text_editor_value'],
                                                      QMS_TEXTAREA_MAX);

  // save record
  // Table:  {qms_shift_log}
  if ( $shift_log->shift_log_id > 0 ) {
    if ( False == drupal_write_record('qms_shift_log', $shift_log, 'shift_log_id')) {
         // update
        $msg = 'Oops!  Something went wrong, updates to Shift Log were not saved.';
        drupal_set_message(t($msg));
        drupal_goto('shiftlog/edit/' . $shift_log->shift_log_id );
        return;
    }

    // Reload the cache
    // determine cache name
    $search = (object) Null;
    $key_cache_name = _get_qms_cache_name(QMS_SHIFTLOG_SEARCH_KEY);

    $key_cache = cache_get($key_cache_name);
    if ( isset($key_cache->data) && ($key_cache->data <> '') ) {
      $search = $key_cache->data;
      _get_shift_log_search_list($search, 0, True);
    }
  }
  else {

    // Save the NEW shift log entry
    if ( False == drupal_write_record('qms_shift_log', $shift_log)) {
      $msg = 'Oops!  Something went wrong, Shift Log entry was not saved.';
      drupal_set_message($msg);
      drupal_goto('shiftlog');
      return;
    }
  }

  $msg = "Shift Log was successfully saved.";
  drupal_set_message(t($msg));


  // WHERE ARE WE GOING NEXT???

  if ( $add_files ) {
    /*	route to file upload form
    ** Email Notifications will be sent after completion of File Upload Form
    ** whether or not files are uploaded
    */
    drupal_goto('shiftlog/file/add/' . $shift_log->shift_log_id);
  }
  else {
    // SEND EMAIL NOTIFICATIONS
    _send_shift_log_email_notifications($shift_log->shift_log_id);

    if ( user_access('administer sabreQMS') == True ) {
      drupal_goto('shiftlog/edit/' . $shift_log->shift_log_id);
    }
    else if ( user_access('search view logs') == True ) {
      drupal_goto('shiftlog/view/' . $shift_log->shift_log_id);
    }
    else {
      drupal_goto(''); // go to home page if permissions don't allow anything else
    }
  }
}





/*------ VIEW --------*/

/*
 *	view_shift_log_form()
 *
 *  Overloads hook_form()
 *  Engineering VIEW ONLY form
 */

function view_shift_log_form($form, $form_state, $shift_log_id) {

  if ( $shift_log_id == 0 ) {
    return;
  }

  drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.view.js');

  if (user_access('search view logs') == FALSE) {
    drupal_set_message( t('Unauthorized:  Permission is required'), 'status');
    return;
  }

  // WYSIWYG EDITOR??  Is this feature enabled allowing for the editor
  $ckeditor_activated  = variable_get(QMS_VAR_WYSIWYG_EDITOR, 1);  // if not set, default to ON



  // get the shift log record
  $shift_log = _get_shift_log($shift_log_id);

  if ( $shift_log == (object) Null ) {
    drupal_set_message( t('Shift Log Not Found!'), 'warning');
    drupal_goto('search/shiftlog');
    return;
  }

  $sl_files = _get_shift_log_files($shift_log_id);


  $form['shift_log_timestamps'] = array(
    //'#markup' => '<div class="qms-desc">Last Updated:  ' . _st_format_date($shift_log->updated_date, 'medium') . '</div>',
    '#markup' => _st_format_record_timestamp_table($shift_log),
  );

  // storage field for the shift_log_id (edit) -- hidden
  $form['shift_log_id'] = array(
    '#type' => 'textfield',
    '#default_value' => $shift_log_id,
    '#attributes' => array('id' => 'qms-shift-log-id',
                            'class' => array('qms-hidden-field')),
  );


  $form['datetime'] = array(
    '#type' => 'item',
    '#title' => t('Date'),
    '#markup' => _st_format_date($shift_log->datetime, 'short'),
    '#size' => 14,
    '#prefix' => '<table class="qms-plain-table" style="width:50%;"><tr style="vertical-align:bottom;"><td>',
  );

  global $simulator_list;
  //global $tech_list;


  $form['tech'] = array(
    '#type' => 'item',
    '#title' => t('Technician/Instructor'),
    '#markup' => _get_user_name($shift_log->employee_user_id),
  );

  $form['simulator'] = array(
    '#type' => 'item',
    '#title' => t('Simulator'),
    '#markup' => $simulator_list->getName($shift_log->simulator_id),
  );

  $form['comment'] = array(
    '#type' => 'item',
    '#title' => t('Comment'),
    '#markup' => ($ckeditor_activated ? _st_convert_symbols($shift_log->comment) : nl2br(_st_convert_symbols($shift_log->comment))),
    '#suffix' => '</td></tr></table>',
  );

  //------------------ FILES -----------------------

  if ( $shift_log->files_attached || count($sl_files) ) {
    $table_headers = array(array('data' => 'Files', 'class' => 'qms-files-tbl-col1'),
                           array('data' => 'Uploaded By', 'class' => 'qms-files-tbl-col2') );
    $table_rows = array();

    foreach ( $sl_files as $f ) {
      $table_rows[] = array( 
        'data' => array( 
            l( t($f->file_name), 
               "shiftlog/file/download/" . $f->file_id, 
               array('attributes' => array('target'=>'_blank')) ),
            $f->name . ' - ' . _st_format_date($f->uploaded_timestamp, 'short') )
      );
    }

    $files_table = theme( 'table', array(
      'header' => $table_headers,
      'rows' => $table_rows,
    ));

    $form['files'] = array(
      '#markup' => $files_table,
      '#prefix' => '<div id="qms-files-tbl-div">',
      '#suffix' => '</div>',
    );
  }

  $prev_report_link = '';
  $next_report_link = '';

  $destination = drupal_get_destination();
  $goto_url = $destination['destination'];

  if( !strlen($goto_url) || ($goto_url == current_path()) ) {
    $goto_url = 'search/shiftlog';
  }


  // determine the next or previous in the search results list of the current page
  $results_cache_name = _get_qms_cache_name(QMS_SHIFTLOG_SEARCH_RESULTS);
  $results_cache = cache_get($results_cache_name);

  if ( isset($results_cache->data) && ($results_cache->data <> '') ) {
    $sl_search_results = $results_cache->data;
    $sl_results_table_rows = $sl_search_results->getResults();

    // get key of previous item in currently loaded page of engineering search results
    $prev_id = _st_array_key_relative($sl_results_table_rows, $shift_log_id, -1);
    if ( $prev_id !== False ) {
//			$prev_report_link = l(t('View Previous'), 'shiftlog/view/' . $prev_id,
//			 												array('query' => array('destination' => 'search/shiftlog')));
      $form['view_previous_link'] = array(
        '#type' => 'textfield',
        '#default_value' => 'shiftlog/view/' . $prev_id,
        '#attributes' => array('class' => array('qms-hidden') ),
      );
    }
    // get key of next item in currently loaded page of engineering search results
    $next_id = _st_array_key_relative($sl_results_table_rows, $shift_log_id, 1);
    if ( $next_id !== False ) {
//			$next_report_link = l(t('View Next'), 'shiftlog/view/' . $next_id,
//															array('query' => array('destination' => 'search/shiftlog')));
      $form['view_next_link'] = array(
        '#type' => 'textfield',
        '#default_value' => 'shiftlog/view/' . $next_id,
        '#attributes' => array('class' => array('qms-hidden') ),
      );
    }
  }


  $form['actions'] = array( '#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Done'),
    '#name' => 'submit',
    '#attributes' => array('class' => array('qms-btn-submit')),
                            //'qms-url' => $goto_url),
  );
  $form['actions']['print'] = array(
    '#type' => 'button',
    '#value' => t('Print'),
    '#name' => 'print',
    '#attributes' => array('class' => array('qms-print', 'qms-btn-extra')),
  );

  if ( user_access('administer sabreQMS') == True ) {
//		$form['actions']['edit'] = array(
//			'#markup' => l(t('Edit') , 'shiftlog/edit/' . $shift_log_id,
//			 								array('query' => array('destination' => 'shiftlog/view/' . $shift_log_id))),
//		);


    $form['actions']['edit'] = array(
      '#type' => 'submit',
      '#value' => t('Edit'),
      '#name' => 'edit',
      '#attributes' => array('class' => array('qms-btn-edit', 'qms-btn-extra'),
                              'query' => array('destination' =>
                                                'shiftlog/view/' . $shift_log_id)),
    );
  }


  if ( isset($form['view_previous_link']) ) {
    $form['actions']['view_previous'] = array(
      '#type' => 'submit',
      '#value' => t('View Previous'),
      '#name' => 'view_previous',
      '#attributes' => array('class' => array('qms-btn-previous', 'qms-btn-extra'),
                              'query' => array('destination' =>
                                                'shiftlog/view/' . $shift_log_id)),
    );
  }

  if ( isset($form['view_next_link']) ) {
    $form['actions']['view_next'] = array(
      '#type' => 'submit',
      '#value' => t('View Next'),
      '#name' => 'view_next',
      '#attributes' => array('class' => array('qms-btn-next', 'qms-btn-extra'),
                              'query' => array('destination' =>
                                                'shiftlog/view/' . $shift_log_id)),
    );
  }


  return $form;
}

/*
 *	view_shift_log_form_submit()
 *
 *  Overloads hook_form_submit()
 *  Shift Log VIEW ONLY submit handler, just routes
 */


function view_shift_log_form_submit($form, $form_state) {

  $button_clicked = $form_state['triggering_element']['#name'];

  if ( $form['actions']['submit']['#name'] == $button_clicked ){
    drupal_goto('search/shiftlog');
  }
  else if ( isset($form['actions']['edit']['#name']) &&
            ($form['actions']['edit']['#name'] == $button_clicked)) {

    $shift_log_id = isset($form_state['values']['shift_log_id']) ?
                        (int) $form_state['values']['shift_log_id'] : 0;

    if ( !$shift_log_id && isset($form['shift_log_id']['#default_value'])) {
      $shift_log_id = $form['shift_log_id']['#default_value'];
    }

    if ( $shift_log_id ) {

      // we have to force $_GET['destination'] otherwise drupal_goto
      // ignores the supplied path and reverts to the destination setting
      $_GET['destination'] = 'shiftlog/edit/' . $shift_log_id .
                '?destination=shiftlog/view/' . $shift_log_id;
    }
  }
  else if ( isset($form['actions']['view_previous']['#name']) &&
            ($form['actions']['view_previous']['#name'] == $button_clicked)) {

    $prev_link = isset($form_state['values']['view_previous_link']) ?
                  $form_state['values']['view_previous_link'] : '';
    if ( !strlen($prev_link) ) {
      $prev_link = isset($form['view_previous_link']) ?
                    $form['view_previous_link']['#default_value'] : '';
    }
    if ( strlen($prev_link) ) {
      $_GET['destination'] = $prev_link . '?destination=search/shiftlog';
    }
  }
  else if ( isset($form['actions']['view_next']['#name']) &&
            ($form['actions']['view_next']['#name'] == $button_clicked)) {

    $next_link = isset($form_state['values']['view_next_link']) ?
                  $form_state['values']['view_next_link'] : '';
    if ( !strlen($next_link) ) {
      $next_link = isset($form['view_next_link']) ?
                    $form['view_next_link']['#default_value'] : '';
    }
    if ( strlen($next_link) ) {
      $_GET['destination'] = $next_link . '?destination=search/shiftlog';
    }
  }

}




/*
 *	_send_shift_log_email_notifications($shift_log_id)
 *
 *	Called from shift log submit, file upload submit, file upload cancel.
 */

function _send_shift_log_email_notifications($shift_log_id, $files_added = 0) {

  global $user;
  $updated_date = 0;
  $updated_by_user = $user->uid;


  // ----------- NOTIFICATIONS --------------
  $shift_log = _get_shift_log($shift_log_id);
  $sl_files = _get_shift_log_files($shift_log_id);

  $log_emails = _st_get_simulator_notification_email_list(QMS_APP, $shift_log->simulator_id, QMS_NOTIFY_SHIFT_LOG);

  $bUpdate = False;
  if ( $shift_log->created_date == $shift_log->updated_date ) {
    // Determine the timestamp
    if ( $files_added ) {
      $updated_date = time();
    }
    else {  // file upload cancelled
      // we will bump the updated_date timestamp by 1 second so that it will no longer exactly
      // match the created date and will no longer trigger a "New Discrepancy" Notice
      // but isn't significant to anything else
      $updated_date = $shift_log->updated_date + 1;
    }
  }
  else {
    $bUpdate = True;
    // Determine the timestamp
    if ($files_added) {  //update the timestamp
      $updated_date = time();
    }
    else {		// nothing uploaded, keep the same timestamp from the Edit-save
      $updated_date = $shift_log->updated_date;
      $updated_by_user = $shift_log->updated_by_user;
    }
  }

  // there are users to be notified about this, send out the notification emails
  if ( strlen($log_emails) > 0 )
  {
    // format an email message to send out
    global $simulator_list;

    $subject = 'QMS NOTICE -- ' . ( $bUpdate ? 'Updated' : 'New') . ' Shift Log for ' .
                $simulator_list->getName($shift_log->simulator_id);
    $body = _notify_shift_log_email($shift_log, $sl_files, $bUpdate);

    _st_send_drupal_email($shift_log->shift_log_id, $subject, $body, $log_emails);   // in sabreQMS.utils.inc
  }

  // UPDATE the SL Timestamps,
  $num_rows = db_update('qms_shift_log')
                ->fields(array(
                          'updated_date' => $updated_date,
                          'updated_by_user' => $updated_by_user,
                          ))
                ->condition('shift_log_id', $shift_log_id, '=')
                ->execute();
}



/*
 *	shift_log_delete_confirm()
 *
 *  Delete the shift log entry -- ADMIN ONLY
 */

function shift_log_delete_confirm($form, $form_state, $shift_log_id) {

  $bAdmin = user_access('administer sabreQMS');

  if ( $bAdmin == False ) {
    drupal_set_message(t('Administrator permissions required to delete a shift log entry.'));
    drupal_goto('shiftlog/edit/' . $shift_log_id);
    return;
  }

  // get the shift log record
  $shift_log = (object) Null;

  $result = db_query("SELECT datetime, employee_user_id, simulator_id
                      FROM {qms_shift_log} WHERE shift_log_id = :slid",
                    array(':slid' => $shift_log_id));
  if ( $result->rowCount() == 0 ) {
    drupal_set_message(t('Unable to delete shift log.  Record not found.'));
    drupal_goto('shiftlog/edit/' . $shift_log_id);
    return;
  }
  $shift_log = $result->fetchObject();

  // storage field for the discrepancy_id (edit) -- hidden
  $form['shift_log_id'] = array(
    '#type' => 'textfield',
    '#default_value' => $shift_log_id,
    '#attributes' => array('id' => 'qms-shift-log-id',
                            'class' => array('qms-hidden-field')),
  );

  global $tech_list;
  global $simulator_list;

  $title = t('Delete Shift Log Entry') . '?';
  $question =
      t('Are you sure you want to delete?') .
      '<h2>' . $tech_list->getName($shift_log->employee_user_id) . '</h2>' .               '<p>' . $simulator_list->getName($shift_log->simulator_id) . '<br />'.
      _st_format_date($shift_log->datetime, 'short') . '</p><br />' .
      t('This action cannot be undone.');
  $goto_if_canceled = 'shiftlog/edit/' . $shift_log_id;
  $yes_btn = 	t('Delete');
  $no_btn = t('Cancel');

  // force this here to avoid a problem with routing if cancelled
  $_GET['destination'] = 'search/shiftlog';

  return confirm_form($form, $title,	$goto_if_canceled, $question,
                      $yes_btn, $no_btn);


}

/*
 *	shift_log_delete_confirm_submit()
 *
 *  overloads:  hook_confirm_submit()
 *  Delete the shift log entry -- ADMIN ONLY
 */


function shift_log_delete_confirm_submit($form, $form_state) {

  if ($form_state['values']['confirm']) {
    $shift_log_id = (int) $form_state['values'] ['shift_log_id'];

    // DELETE SHIFT LOG FILES

    // need to delete physical files on the server
    // in addition to the db references

    // are there any shift log files?  We just need one for this shift log
    $results = db_query('SELECT file_id, file_uri FROM {qms_shift_log_files} f WHERE shift_log_id = :slid LIMIT 1',
                        array(':slid' => $shift_log_id));

    if ( $results->rowCount() ) {
      $file_rec = $results->fetchObject();

      // deletes the physical files from their server location + the subdirectory
      _delete_all_attached_files($file_rec->file_uri);

      // delete all of the shift log's file references from database
      $num_rows = db_delete('qms_shift_log_files')
            ->condition('shift_log_id', $shift_log_id)
            ->execute();
    }

    $num_rows = db_delete('qms_shift_log')
          ->condition('shift_log_id', $shift_log_id)
          ->execute();

    $msg = ( ($num_rows == 1) ? 'The shift log has been deleted.' : 'Error occurred deleting shift log.');
    drupal_set_message($msg);

    // Reload the cache

    // determine cache name
    $search = (object) Null;
    $key_cache_name = _get_qms_cache_name(QMS_SHIFTLOG_SEARCH_KEY);

    $key_cache = cache_get($key_cache_name);
    if ( isset($key_cache->data) && ($key_cache->data <> '') ) {
      $search = $key_cache->data;
      _get_shift_log_search_list($search, 0, True);
    }
  }
  drupal_goto('search/shiftlog');
}


/*
 * _get_shift_log($shift_log_id)
 * Returns and object pointing to the shift_log record data
 */

function _get_shift_log($shift_log_id) {

  $shift_log = (object) Null;

  // get the shift log record
  $sql = "SELECT shift_log_id, employee_user_id, simulator_id,
                 datetime, comment, files_attached, created_date, updated_date,
                 created_by_user, updated_by_user, created_by_ip_address, updated_by_ip_address
          FROM {qms_shift_log}
          WHERE shift_log_id = :slid";
  $result = db_query($sql, array(':slid' => $shift_log_id));

  if ( $result->rowCount() ) {
    $shift_log = $result->fetchObject();
  }
  return $shift_log;
}


/*
 *
 *
 *	_notify_shift_log_email()
 *
 */

function _notify_shift_log_email($shift_log, $sl_files, $bUpdated = False) {

  $cr_email = _st_get_user_email($shift_log->created_by_user);  // this may return '' if created_by_user==0
  $cr_user_link = ( strlen($cr_email) ? l(_get_user_name($shift_log->created_by_user),
                      'mailto:' . $cr_email) : _get_user_name($shift_log->created_by_user) );

  $upd_email = _st_get_user_email($shift_log->updated_by_user);  // this may return '' if created_by_user==0
  $upd_user_link = ( strlen($upd_email) ? l(_get_user_name($shift_log->updated_by_user),
                      'mailto:' . $upd_email) : _get_user_name($shift_log->updated_by_user) );


  $title = 'New Shift Log';
  if ( $bUpdated ) {
    $title = "Shift Log - Updated";
  }

  $body =
    '<h2><strong>' . $title . '</strong></h2>' .
    '<hr />' .
    '<p>Created:&nbsp;&nbsp;&nbsp;' .
    ( $shift_log->created_by_user ? $cr_user_link . ', ' : '' ) .
    ( $shift_log->created_date ? _st_format_date($shift_log->created_date, 'medium') : '');

  if ( $bUpdated ) {			// UPDATED SHIFT LOG
    $body .=
      '<br />Updated:&nbsp;&nbsp;' .
      ( $shift_log->updated_by_user ? $upd_user_link . ', ' : '' ) .
      ( $shift_log->updated_date ? _st_format_date($shift_log->updated_date, 'medium') : '');
  }

  $body .=	'</p><hr />';

  $body .= _format_shift_log_for_email($shift_log, $sl_files);

  return $body;
}

/*
 *   Format the report information for email
 *
 *	_format_shift_log_for_email()
 *
 */

function _format_shift_log_for_email($shift_log, $sl_files) {


  ///////////////////////////////////////////////
  // format the contents of the shiftlog for email  //
  ///////////////////////////////////////////////
  global $chapter_list;
  global $simulator_list;

  $email = _st_get_user_email($shift_log->employee_user_id);  // this may return '' if employee_user_id==0
  $employee_name = _get_user_name($shift_log->employee_user_id);
  $user_link = ( strlen($email) ? l($employee_name, 'mailto:' . $email) : $employee_name );



  // Header Information
  $body =
    '<table>' .
    '<tr><td colspan="2"><h2><strong>Shift Log Entry:  ' . _st_format_date($shift_log->datetime, 'medium') . '</strong></h2></td></tr>' .
    '<tr><td><strong>Technician/Instructor</strong></td><td>' . $user_link . '</td></tr>' .
    '<tr><td><strong>Simulator</strong></td><td>' . $simulator_list->getName($shift_log->simulator_id) . '</td></tr>';


  // Log Text
  $body .=
    '<tr><td colspan="2">&nbsp;</td></tr>' .
    '<tr><td colspan="2"><h3><strong>Comments</strong></h3></td></tr>' .
    '<tr><td colspan="2">' . $shift_log->comment . '</td></tr>' .
    '<tr><td colspan="2">&nbsp;</td></tr>';

  // Files
  if ( count($sl_files) ) {
    $body .=
      '<tr><td colspan="2">&nbsp;</td></tr>' .
      '<tr><td colspan="2"><h3><strong>Files</strong></h3></td></tr>' .
      '<tr><td colspan="2">You must log into the QMS to access the associated files</td></tr>';

    foreach ( $sl_files as $f ) {
      $body .= '<tr><td><strong>Uploaded:   </strong>' . $f->name . ' - ' .
                        _st_format_date($f->uploaded_timestamp, 'short') . '</td><td>' .
                $f->file_name . '</td></tr>' .
               '<tr><td colspan="2">&nbsp;</td></tr>';
    }
  }


  // End of Report
  $body .= '</table>';

  return $body;
}
