<?php
/**
 *
 *		sabreQMS Module for plugin to Drupal 7 Framework
 *
 *		Discrepancy & Trouble Call Comment handling
 *
*/




/*
 *	get_comment_callback()
 *
 *  AJAX call from the browser, retrieves comment from
 *  discrepancy_comment_id or trouble_call_comment_id
 */
function get_comment_callback($report_code, $comment_id) {

  try {

    if ( !$comment_id ) {
      return drupal_json_output(array(
                          'comment_id' => $comment_id,
                          'comment' => '',
                        ));
    }

    // 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

    $sql = '';

    if ( 'DR' == $report_code ) {
      $sql = 'SELECT comment FROM {qms_discrepancy_comments}
              WHERE discrepancy_comment_id = :cid';
    }
    else if ( 'TC' == $report_code ) {
      $sql = 'SELECT comment FROM {qms_trouble_call_comments}
              WHERE trouble_call_comment_id = :cid';
    }

    $result = db_query($sql, array(':cid' => $comment_id));
    $comment = $result->fetchField();


    $comment = _st_convert_symbols($comment);

    if ( !$ckeditor_activated ) {
      $comment = trim(strip_tags($comment));
    }

    return drupal_json_output(array(
                          'comment_id' => $comment_id,
                          'comment' => $comment
                         ));
  }
  catch(Exception $e) {
    watchdog('sabreQMS', 'get_comment_callback()' . $e->getMessage(),
            array(), WATCHDOG_ERROR);
  }
}


/*
 *	comment_submit_callback()
 *
 *  AJAX call to save a new comment or update an existing
 */

function comment_submit_callback($report_code) {
	$comment = (object) Null;
  global $user;
  $table = '';
  $cmt_table = '';
  $key_val = '';
  $key_field = '';
  $id_field = array();

  $comment->user_id = $user->uid;  // currently logged in user
	$comment->timestamp = time();

	// comment length is controlled from the browser,
  // but if that fails for some reason, trim it here
	$comment->comment = _st_clean_ckeditor_text($_POST['comment'], QMS_TEXTAREA_MAX);

  if ( 'DR' == $report_code ) {
    $bEdit = ( user_access('administer sabreQMS') || user_access('edit discrepancy comments'));
    $comment->discrepancy_id = (int)$_POST['discrepancy_id'];
    $comment->discrepancy_comment_id = (int)$_POST['comment_id'];

    if ( $comment->discrepancy_comment_id  && !$bEdit ) {
      // don't allow comments to be edited unless by someone with edit permission
      return;
    }

    $table = 'qms_discrepancy_log';
    $cmt_table = 'qms_discrepancy_comments';
    $key_field = 'discrepancy_id';
    $key_val = $comment->discrepancy_id;

    if ( isset($comment->discrepancy_comment_id) && $comment->discrepancy_comment_id > 0    ) {
      $id_field = array('discrepancy_comment_id');
    }
  }
  else if ( 'TC' == $report_code ) {
    $bEdit = ( user_access('administer sabreQMS') || user_access('edit trouble call comments'));
    $comment->trouble_call_id = (int)$_POST['trouble_call_id'];
    $comment->trouble_call_comment_id = (int)$_POST['comment_id'];

    if ( $comment->trouble_call_comment_id  && !$bEdit ) {
      // don't allow comments to be edited unless by someone with edit permission
      return;
    }

    $table = 'qms_trouble_call_log';
    $cmt_table = 'qms_trouble_call_comments';
    $key_field = 'trouble_call_id';
    $key_val = $comment->trouble_call_id;

    if ( isset($comment->trouble_call_comment_id) &&
      $comment->trouble_call_comment_id > 0    ) {
      $id_field = array('trouble_call_comment_id');
    }

  }

  if ( drupal_write_record($cmt_table, $comment, $id_field) ) {
    $num_rows = db_update($table)
				->fields(array(
									'has_comments' => 1,
									'updated_date' => $comment->timestamp
								))
				->condition($key_field, $key_val, '=')
				->condition('has_comments', 0, '=')
        ->execute();

    // SEND EMAIL NOTIFICATIONS
    //if (!empty($comment->discrepancy_id)){
    //  _discrepancy_add_update_post_processing($comment->discrepancy_id);
    //}

  }

  $content = _get_comments_table($report_code, $key_val);
	die($content);
}

/*
 *	discrepancy_comment_delete_callback()
 *
 *  AJAX call from the browser, deletes comment by discrepancy_comment_id
 */

function discrepancy_comment_delete_callback($comment_id) {

  try {

    $discrepancy_id = (int)$_POST['discrepancy_id'];

    $num_rows = db_delete('qms_discrepancy_comments')
          ->condition('discrepancy_comment_id', $comment_id, '=')
          ->execute();

    $result = db_query("SELECT discrepancy_comment_id
                        FROM {qms_discrepancy_comments} c
                        WHERE discrepancy_id = :did LIMIT 1",
                        array(':did' => $discrepancy_id));
    if ( $result->rowCount() == 0 ) {
      // no more comments left for this discrepancy, unset flag
      $num_rows = db_update('qms_discrepancy_log')
            ->fields(array(
                      'has_comments' => 0,
                      'updated_date' => REQUEST_TIME,
                    ))
            ->condition('discrepancy_id', $discrepancy_id, '=')
            ->execute();
    }

    $content = _get_comments_table('DR', $discrepancy_id);
    die($content);
  }
  catch(Exception $e) {
    watchdog('sabreQMS', 'discrepancy_comment_delete_callback()' . $e->getMessage(),
            array(), WATCHDOG_ERROR);
  }
}


/*
 *	trouble_call_comment_delete_callback()
 *
 *  AJAX call from the browser, deletes comment by trouble_call_comment_id
 */

function trouble_call_comment_delete_callback($comment_id) {

  try {

    $trouble_call_id = (int)$_POST['trouble_call_id'];

    $num_rows = db_delete('qms_trouble_call_comments')
                  ->condition('trouble_call_comment_id', $comment_id, '=')
                  ->execute();

    $result = db_query("SELECT trouble_call_comment_id
                        FROM {qms_trouble_call_comments}
                        WHERE trouble_call_id = :id LIMIT 1",
                        array(':id' => $trouble_call_id));
    if ( $result->rowCount() == 0 ) {
      // no more comments left for this discrepancy, unset flag
      $num_rows = db_update('qms_trouble_call_log')
            ->fields(array(
                      'has_comments' => 0,
                      'updated_date' => REQUEST_TIME,
                    ))
            ->condition('trouble_call_id', $trouble_call_id, '=')
            ->execute();
    }

    $content = _get_comments_table('TC', $trouble_call_id);
    die($content);
  }
  catch(Exception $e) {
    watchdog('sabreQMS', 'discrepancy_comment_delete_callback()' . $e->getMessage(),
            array(), WATCHDOG_ERROR);
  }
}



/*
 *	_get_comments_table()
 *
 *	refreshes and reformats the comments table
 */

function _get_comments_table($report_code, $id, $bViewMode = False) {

	$content = '';

  $bEdit = False;

  if ( 'DR' == $report_code ) {
    // this returns empty for new discrepancies
    $comments = _get_discrepancy_comments($id);
    $bEdit = user_access('administer sabreQMS') ||
             user_access('edit discrepancy comments');
  }
  else if ( 'TC' == $report_code ) {
    // this returns empty for new discrepancies
    $comments = _get_trouble_call_comments($id);
    $bEdit = user_access('administer sabreQMS') ||
             user_access('edit trouble call comments');
  }

	if ( !$bEdit && !count($comments) ) {
		// there are no comments and it's view only, return empty container div
    $content = '<div id="qms-comments-tbl-div"></div>';
		return $content;
	}



	// WYSIWYG EDITOR??  If enabled, we format differently for textareas than for the editor
	$ckeditor_activated = variable_get(QMS_VAR_WYSIWYG_EDITOR, 1);  // if not set, default to ON


	$table_rows = array();
	$table_headers =
    array(
      array('data' => 'Comments', 'class' => 'qms-comment-tbl-col1')
    );

	if ( !$bViewMode ) {
		// this only applies to editing comments
		// new discrepancies will always have an Options col

		if ( ( $id && $bEdit )  ||	// EDIT EXISTING
			   ( !$id ) ) 				{   // NEW
			$table_headers[] = array('data' => 'Options');
		}
	}

	// this foreach loop will be skipped for new discrepancies
	$i = 0;
	foreach( $comments as $cmt) {
		$col1text = '<div class="qms-comment-hdr">' .
                  $cmt->name . ' - ' . _st_format_date($cmt->timestamp, 'short') .
                '</div>';

		// check here if ckeditor is enabled
		if ( $ckeditor_activated ) {
			$col1text .= _st_convert_symbols($cmt->comment);
		}
		else {
			$col1text .= nl2br(_st_convert_symbols($cmt->comment));
		}

		$table_rows[] = array( 'data' => array($col1text) );
		if ( !$bViewMode && $bEdit ) {

      $type = (('DR' == $report_code) ? 'discrepancy' : 'troublecall');
      $cmt_id = (('DR' == $report_code) ?
                $cmt->discrepancy_comment_id : $cmt->trouble_call_comment_id);

			// admin can edit/delete comments, all done through ajax calls
			$table_rows[$i]['data'][] =
				 l( t('Edit'), $type . "/comment/get/" . $cmt_id,
					array('attributes' => array('class' => array('qms-comment-get')) )) .
				 l( t('Delete'), $type . "/comment/delete/" . $cmt_id,
								array('attributes' => array('class' => array('qms-comment-delete'))));
		}
		$i++;
	}


	// refresh table
	$content = '<div id="qms-comments-tbl-div">';
	$content .= theme( 'table', array(
		'header' => $table_headers,
		'rows' => $table_rows,
    'empty' => t('None'),
	));
	$content .= '</div>';

	return $content;
}


/*
 *	theme_comments_table_callback()
 *
 *  AJAX call from the browser, only replaces the existing table <div>
 *  Does not refresh the whole screen
 *	Rebuilds the table display when a comment is added or deleted.
 *  Data is retained in a hidden textfield
 *	No DB interaction, strictly theme formatting
 */

function theme_comments_table_callback() {

	// WYSIWYG EDITOR??  If enabled, we format differently for textareas than for the editor
	$ckeditor_activated  = variable_get(QMS_VAR_WYSIWYG_EDITOR, 1);  // if not set, default to ON

	// break comment list into individual comment records
	$cl = trim($_POST['comment_list']);
	$comment_list = array();
	$comment_row_data = array();

	if ( strlen($cl) > 0 ) {
		$comment_list = explode('|', $cl);
	}


	$i = 0;
	foreach($comment_list as $comment) {
    $comment_data = ( $ckeditor_activated ? $comment : nl2br($comment) );

		$link_options = l( t('Delete'), "",
                       array('attributes' =>
                          array('class' => array('qms-comment-delete'),
																'qms-row' => $i) )
                    );

    // do not put the attributes -> class into an array (as you would expect)
    // triggers an error:
    //Notice: Array to string conversion in drupal_attributes() (line 2369 includes/common.inc).
		$comment_row_data[$i++] = array('data' => array($comment_data, $link_options),
																		'attributes' => array('class' => 'qms-comment-tbl-row'));
	}

	// rebuild table
	$content = '<div id="qms-comments-tbl-div">';
	$content .= theme( 'table', array(
		'header' => array(array('data' => 'Comments', 'class' => array('qms-comment-tbl-col1')),
											array('data' => 'Options', 'class' => array('qms-comment-tbl-col2'))),
		'rows' => $comment_row_data,
    'empty' => t('None'),
	));
	$content .= '</div>';

	die($content);
}


/*
 * _get_discrepancy_comments($discrepancy_id)
 *
 * returns an array of discrepancy comment records
 */
function _get_discrepancy_comments($discrepancy_id) {

  try{

    if ( $discrepancy_id == 0 ) {
      return array();
    }

    $sql = "SELECT c.discrepancy_comment_id, u.name, c.`timestamp`, c.comment
            FROM {qms_discrepancy_comments} c, {users} u
            WHERE c.discrepancy_id = :did AND c.user_id = u.uid
            ORDER BY c.discrepancy_comment_id";
    return db_query($sql, array(':did' => $discrepancy_id))->fetchAll();
  }
  catch(Exception $e) {
		watchdog('sabreQMS', '_get_discrepancy_comments()' . $e->getMessage(),
            array(), WATCHDOG_ERROR);
  }
}


/*
 * _get_trouble_call_comments($trouble_call_id)
 *
 * returns an array of discrepancy comment records
 */
function _get_trouble_call_comments($trouble_call_id) {

  try{

    if ( $trouble_call_id == 0 ) {
      return array();
    }

    $sql = "SELECT c.trouble_call_comment_id, u.name, c.`timestamp`, c.comment
            FROM {qms_trouble_call_comments} c, {users} u
            WHERE c.trouble_call_id = :id AND c.user_id = u.uid
            ORDER BY c.trouble_call_comment_id";
    return db_query($sql, array(':id' => $trouble_call_id))->fetchAll();
  }
  catch(Exception $e) {
		watchdog('sabreQMS', '_get_trouble_call_comments()' . $e->getMessage(),
            array(), WATCHDOG_ERROR);
  }
}




