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



/*
 *	get_discrepancy_part_callback()
 *
 *  AJAX call from the browser, retrieves part record from part_id
 */
function get_discrepancy_part_callback($part_id = 0) {
  
  try {
    
    if ( $part_id ) {
      $part = _get_discrepancy_part($part_id);
          

      if ( isset($part->part_id) ) {
        return drupal_json_output(
                  array( 'part_id' => $part->part_id, 
                         'part_no' => _st_convert_symbols($part->part_no),
                         'quantity' => $part->quantity,
                         'part_description' => _st_convert_symbols($part->description),
                         'part_sn_in' => _st_convert_symbols($part->serial_number_in),
                         'part_sn_out' => _st_convert_symbols($part->serial_number_out),
                       ));	
      }
    }
    return drupal_json_output(
            array( 'part_id' => 0, 
                   'part_no' => '',
                   'quantity' => 0,
                   'part_description' => '',
                   'part_sn_in' => '',
                   'part_sn_out' => '',
								 ));	
    
  }
  catch (Exception $e) {
		watchdog('sabreQMS', 'get_discrepancy_part_callback()' . $e->getMessage(), 
             array(), WATCHDOG_ERROR);
	}
}


/*
 *	discrepancy_part_submit_callback()
 *
 *  AJAX call to save a new part or update an existing part record
 */

function discrepancy_part_submit_callback() {
  try {
    $bEdit = (user_access('administer sabreQMS') || 
              user_access('edit discrepancy parts'));

    $part = (object) Null;

    $part->discrepancy_id = (int)$_POST['discrepancy_id'];
    $part->part_id = (int)$_POST['part_id'];
    $part->part_no = $_POST['part_no'];
    $part->quantity = (int)$_POST['quantity'];
    $part->description = $_POST['part_description'];
    $part->serial_number_in = $_POST['part_sn_in'];
    $part->serial_number_out = $_POST['part_sn_out'];
    $currtimestamp = REQUEST_TIME;

    $msg = '';

    if ( isset($part->part_id) && ($part->part_id > 0)) {
      // update existing part
      if ( False == drupal_write_record('qms_discrepancy_parts', 
                                        $part, array('part_id')) ) {
        $msg = "Oops!  Something went wrong updating the part record in the database.";
        drupal_set_message(t($msg));
      }
    }
    else {
      // add new part
      if ( False == drupal_write_record('qms_discrepancy_parts', $part)) {
        $msg = "Oops!  Something went wrong saving the part record to the database.";
        drupal_set_message(t($msg));			
      }
    }

    // make sure the discrepancy parts flag has been set on the DR
    // only update if the flag is off
    if ( ($part->part_id > 0) && $msg == '') {
      $num_rows = db_update('qms_discrepancy_log')
            ->fields(array(
                      'parts_used' => 1,
                      'updated_date' => $currtimestamp,
                    ))
            ->condition('discrepancy_id', $part->discrepancy_id)
            ->condition('parts_used', 0)
            ->execute();
    }

    $content = _get_discrepancy_parts_table($part->discrepancy_id, $bEdit);
    die($content);
  }
  catch (Exception $e) {
		watchdog('sabreQMS', 'discrepancy_part_submit_callback()' . $e->getMessage(), 
             array(), WATCHDOG_ERROR);
	}
}

/*
 *	discrepancy_part_delete_callback()
 *
 *  AJAX call from the browser, deletes part by part_id
 */

function discrepancy_part_delete_callback($part_id) {
  
  try {
	
    $bEdit = (user_access('administer sabreQMS') || 
              user_access('edit discrepancy parts'));

    $num_rows = db_delete('qms_discrepancy_parts')
          ->condition('part_id', $part_id)
          ->execute();

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

    $result = db_query("SELECT part_id FROM {qms_discrepancy_parts} 
                        WHERE discrepancy_id = :did LIMIT 1",
                        array(':did' => $discrepancy_id));

    if ( $result->rowCount() == 0 ) {
      // no more parts left for this discrepancy, unset flag
      $num_rows = db_update('qms_discrepancy_log')
            ->fields(array(
                      'parts_used' => 0,
                      'updated_date' => time(),
                    ))
            ->condition('discrepancy_id', $discrepancy_id, '=')
            ->execute();
    }


    $content = _get_discrepancy_parts_table($discrepancy_id, $bEdit);
    die($content);
  }
  catch (Exception $e) {
		watchdog('sabreQMS', 'discrepancy_part_delete_callback()' . $e->getMessage(), 
             array(), WATCHDOG_ERROR);
	}
}


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

function _get_discrepancy_parts_table($discrepancy_id, $edit = False, $view_only = False) {
	
	$content = '';
	
	// this returns empty for new discrepancies
	$parts = _get_discrepancy_parts($discrepancy_id);
	
	if ( $view_only && !count($parts) ) {
		// there are no parts and it's view only, return nothing
		return $content;
	}
	
	$admin = user_access('administer sabreQMS');	
	
	$table_rows = array();
	$table_headers = array(
											array('data' => 'Part No', 'class' => 'qms-parts-tbl-col1'),
		 									array('data' => 'Qty', 'class' => 'qms-parts-tbl-col2'),
											array('data' => 'Description', 'class' => 'qms-parts-tbl-col3')
										);
										
	if ( !$view_only ) {
		// this only applies to editing parts
		// new discrepancies will always have an Options col
		
		if ( ( $discrepancy_id && ( $admin || $edit ) )  ||	// EDIT EXISTING
			   ( !$discrepancy_id ) ) 										{   // NEW
			$table_headers[] = array('data' => 'Options', 'class' => 'qms-parts-tbl-col4');
		}
	}
	
	$i = 0;
	foreach( $parts as $pt) {
    
    $descrip = $pt->description . '<br />' . 
               t('S/N In') . ': ' . $pt->serial_number_in . '<br />' . 
               t('S/N Out') . ': ' . $pt->serial_number_out;
		
		$table_rows[] = array( 'data' => array( 
                                      $pt->part_no, 
                                      $pt->quantity, 
                                      $descrip )	);
																					
		if ( !$view_only && ( $admin || $edit ) ) {
			// admin can edit/delete comments, all done through ajax calls
			$table_rows[$i]['data'][] = 
				 l( t('Edit'), "discrepancy/part/get/" . $pt->part_id, 
					array('attributes' => array('class' => array('qms-discrepancy-part-get')) )) . 
				 l( t('Delete'), "discrepancy/part/delete/" . $pt->part_id,
								array('attributes' => array('class' => array('qms-discrepancy-part-delete'))));					
		}																																							
		$i++;
	}
	if ( $i == 0 ) {
			$table_rows = array('data' => array('None', '', ''));
			if ( ( $discrepancy_id && ( $admin || $edit ) )  ||	// EDIT EXISTING
				   ( !$discrepancy_id ) ) 										{   // NEW
			
				$table_rows['data'][] = '';
			}
	}							
	
	
	// refresh table
	$content = '<div id="qms-parts-tbl-div">';
	$content .= theme( 'table', array(
		'header' => $table_headers,
		'rows' => $table_rows,
	));
	$content .= '</div>';
		
	return $content;
}


/*
 *	theme_add_parts_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 part record is added or deleted.
 *	No DB interaction, strictly theme formatting
 *	Data is retained in a hidden textfield
 */

function theme_add_parts_table_callback() {
	
	// break parts list into individual part records '|' delimited
	// each part record is further delimited by '~' for part_no + ~ + quantity + ~ + description
	$pl = trim($_POST['parts_list']);
	$part_list = array();
	$table_rows = array();
	
	if ( strlen($pl) > 0 ) {
		$part_list = explode('|', $pl);
	}
	
	$i = 0;
	foreach($part_list as $precord) {
		$link_options = l( t('Delete'), "",  array('attributes' => array('class' => array('qms-parts-delete'),
																																		 'row' => $i)) ) ;
		$part_array = explode('~', $precord);	
    
    // combine descrip, SN IN and SN Out into one field
    // unset individ cols
    $descrip = $part_array[2] . '<br />' . 
               t('S/N In') . ': ' . $part_array[3] . '<br />' . 
               t('S/N Out') . ': ' . $part_array[4];
    $part_array[2] = $descrip;
    unset($part_array[3]);
    unset($part_array[4]);
    
		$part_array[] = $link_options;																														
		$table_rows[] = array('data' => $part_array);
		unset($part_array);
	}
  $table_header = 
    array(
      array('data' => t('Part No'), 'class' => array('qms-parts-tbl-col1')),
      array('data' => t('Qty'), 'class' => array('qms-parts-tbl-col2')),
      array('data' => t('Description'), 'class' => array('qms-parts-tbl-col3')),
      array('data' => t('Options'), 'class' => array('qms-parts-tbl-col4')),
    );

	// rebuild table
	$content = '<div id="qms-parts-tbl-div">';
	$content .= theme( 'table', array(
								'header' => $table_header,
								'rows' => $table_rows,
                'empty' => t('None'),
              ));
	$content .= '</div>';
		
	die($content);
}



/*
 * _get_discrepancy_parts($discrepancy_id)
 */
function _get_discrepancy_parts($discrepancy_id) {
  try {
	
    if ( $discrepancy_id == 0 ) {
      return array();
    }

    $sql = "SELECT part_id, part_no, quantity, description, 
                   serial_number_in, serial_number_out 
            FROM {qms_discrepancy_parts} p 
            WHERE discrepancy_id = :did ORDER BY part_id";
    return db_query($sql, array(':did' => $discrepancy_id))->fetchAll();		
  }
  catch (Exception $e) {
		watchdog('sabreQMS', '_get_discrepancy_parts()' . $e->getMessage(), 
             array(), WATCHDOG_ERROR);
	}
}

/*
 * _get_discrepancy_part($part_id)
 */
function _get_discrepancy_part($part_id) {
  try {
    
    $part = (object) Null;
	
    if ( $part_id == 0 ) {
      return $part;
    }

    $sql = "SELECT part_id, part_no, quantity, description, 
                   serial_number_in, serial_number_out 
            FROM {qms_discrepancy_parts} p 
            WHERE part_id = :pid";
    
    $result = db_query($sql, array(':pid' => $part_id));
    if ( $result->rowCount() ) {
      $part = $result->fetchObject();
    }
    return $part;
  }
  catch (Exception $e) {
		watchdog('sabreQMS', '_get_discrepancy_part()' . $e->getMessage(), 
             array(), WATCHDOG_ERROR);
	}
}



