<?php
// $ID$

/*
 *	@file
 *	Punch Clock functions for sabreQMS module
 */

//require_once('sabreQMS.utils.inc');

define('QMS_PUNCH_CLOCK_IN', 'CLOCK_IN');
define('QMS_PUNCH_CLOCK_OUT', 'CLOCK_OUT');

define('QMS_PUNCH_DISPLAY_STATUS_IN', 'CLOCKED IN');
define('QMS_PUNCH_DISPLAY_STATUS_OUT', 'NOT Clocked In');

define('QMS_PUNCH_CLOCK_BTN_CLOCK_IN', 'Clock IN');
define('QMS_PUNCH_CLOCK_BTN_CLOCK_OUT', 'Clock OUT');


/*
 *	punch_clock_form()
 *
 *	returns:  Displays punch clock form
 *
 */
function punch_clock_form($form, $form_state) {
	
	if (user_access('punch clock') == FALSE) {
		drupal_set_message( t('Unauthorized:  Permission is required'), 'status');
		return;
  }
	
  drupal_add_library('system','ui.dialog');
  
	drupal_add_js(drupal_get_path('module', 'sabreTools') . '/js/sabreTools.lib.js');
	drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.punchclock.js');
	
	// customer-user?
	global $user;
	$user_is_customer_id = _user_is_customer($user->uid);
	
	// get the job list
	$job_list = new JobList($user_is_customer_id);

	$bActive = True;
	if ( $job_list->get_count($bActive) == 0 ) {
		drupal_set_message('There are no active jobs defined for your punch clock.', 'Status');
	}
		
	// get the last punch clock entry for this user
	$pclock = Null;
	$status = '';
	$default_job_id = 0;
	$clocked_in = False;
	$punch_clock_id = 0;
  
  $query = db_select('qms_punch_clock', 'pc')
            ->fields('pc', array( 'punch_clock_id', 
                                  'clock_in', 
                                  'clock_out', 
                                  'time_worked', 
                                  'job_id'))
            ->condition('pc.employee_user_id', $user->uid)
            ->condition('pc.clock_out', 0)
            ->orderBy('pc.punch_clock_id', 'desc')
            ->range(0, 1);
  $result = $query->execute();
	
//	$sql = "SELECT punch_clock_id, clock_in, clock_out, time_worked, job_id FROM {qms_punch_clock} 
//					WHERE employee_user_id = :uid AND clock_out = 0 ORDER BY clock_in DESC LIMIT 1";
//	$result = db_query( $sql, array(':uid' => $user->uid) );
	
	if ( !$result->rowCount() ) {
		// no open clock record found
		//unset($pclock);
		$status = QMS_PUNCH_DISPLAY_STATUS_OUT;
	}
	else {
		// found last punch clock event
		$pclock = $result->fetchObject();
		
		$status = QMS_PUNCH_DISPLAY_STATUS_IN;
		$clocked_in = True;
		
		$default_job_id = $pclock->job_id;
		//$punch_clock_id = $pclock->punch_clock_id;
	}
	
	$form['job'] = array(
		'#type' => 'select',
		'#title' => t('Job'),
		'#options' => $job_list->get_active(),
		'#default_value' => $default_job_id,
		'#disabled' => $clocked_in,
		'#attributes' => array( 'id' => 'qms-job-select'),
	);
	
	$form['status'] = array(
		'#markup' => '<div id="qms-punch-clock-status-div"><b>You are:</b><br />' . $status . '<br />&nbsp;<br /></div>', 
		'#attributes' => array( 'id' => 'qms-punch-clock-status' ),
	);
	$form['time_worked'] = array(
		'#markup' => '<div id="qms-time-worked-div"></div>', 
	);
	
	global $base_url;
	$form['waiting'] = array(
		'#markup' => '<div id="qms-waiting"><img src="' . $base_url . QMS_IMAGES_DIR . 'waiting.gif" /></div>', 
	);
	
	
	/*  HANDLE PUNCH CLOCK EVENTS BY USER ID ... NOT PUNCH CLOCK ID
   *  to prevent duplicates
	$form['punch_clock_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $punch_clock_id,
		'#attributes' => array( 'class' => array('qms-hidden-field'),
		 												'id' => 'qms-punch-clock-id'),
	);
   * 
   */
	
	$form['clock_btn'] = array(
		'#type' => 'button',
		'#value' => (( $clocked_in ) ? t(QMS_PUNCH_CLOCK_BTN_CLOCK_OUT) : t(QMS_PUNCH_CLOCK_BTN_CLOCK_IN)),
		'#attributes' => array( 'id' => 'qms-punch-clock-btn',
		 												'class' => array('qms-punch-clock-btn'),
                            'qms-action' => (( $clocked_in ) ? QMS_PUNCH_CLOCK_OUT : QMS_PUNCH_CLOCK_IN),
														'qms-url' => url('punchclock/punch')),
	);
	
	// storage area for dynamic dialog elements
	$form['popup_dialog'] = array(
		'#markup' => '<div id="qms-message-box"></div>',
	);	
		
	return $form;
}

/*
 *	punch_clock_event_callback()
 *
 *  Handler for clock-in/clock-out events
 */

function punch_clock_event_callback() {
  
  try {
		
	$job_id = (int)$_POST['job_id'];
  $action = $_POST['action'];
	
  $punch_clock = Null;
	$result = False;
	$clocked_in = False;
	$button_text = '';
	$status = '';
	$time_worked_text = '';
  global $user;
  
  if (empty($action)) {
		return drupal_json_output(array(
                                'result' => false,
                                'refresh' => false,
                                'msg' => "ERROR:  Punch Clock Action Failed!<br>" . 
                                         "Please refresh the page and try again.<br>" . 
                                         "Missing punch event action.",
                              ));									
    
  }
	
	if ( empty($job_id) && $action == QMS_PUNCH_CLOCK_IN) {
		return drupal_json_output(array(
                                'result' => true,
                                'refresh' => true,
                                'msg' => "ERROR:  Punch Clock Action Failed!<br>" . 
                                         "Please refresh the page and try again.<br>" . 
                                         "Missing job_id.",
                              ));									
	}
  
  if (empty($user->uid)) {
		return drupal_json_output(array(
                                'result' => false,
                                'refresh' => false,
                                'msg' => "ERROR:  Punch Clock Action Failed!<br>" . 
                                         "Please refresh the page and try again.<br>" . 
                                         "Missing user.",
                              ));									    
  }
	
	
	// get id for current user's most recent punch clock event.
	// if user is punched in, then punch them out and finalize hours calculation
  // always check for an open punch event for this user
  // relying on punch_clock_id can result in duplicates
  $query = db_select('qms_punch_clock', 'pc')
          ->fields('pc', array( 'punch_clock_id', 
                                'clock_in', 
                                'clock_out', 
                                'time_worked', 
                                'job_id'))
          ->condition('pc.employee_user_id', $user->uid)
          ->condition('pc.clock_out', 0);
  $result = $query->execute();
  
  if ( $result->rowCount() > 0 ) {
    
    $punch_clock = $result->fetchObject();
    
    // open punch event found, check the action... is the user clocking in or clocking out?
    if ($action == QMS_PUNCH_CLOCK_IN) {
      return drupal_json_output(array(
                            'result' => false,
                            'refresh' => true,
                            'status' => QMS_PUNCH_DISPLAY_STATUS_IN,  
                            'clocked_in' => true, 
                            'button_text' => QMS_PUNCH_CLOCK_BTN_CLOCK_OUT, 
                            'action' => QMS_PUNCH_CLOCK_OUT,
                            'msg' => "already CLOCKED IN.",
                          ));									    
    }
    
    
    // update the punch record
    $punch_clock->clock_out = REQUEST_TIME;

    // calculate time_worked in seconds
    //$punch_clock->time_worked = $punch_clock->clock_out - $punch_clock->clock_in;  
    $punch_clock->time_worked = _st_date_diff_seconds($punch_clock->clock_in, 
                                                      $punch_clock->clock_out);  
    $mins_worked = (int)($punch_clock->time_worked / 60);
    $hours_worked = (int) ($mins_worked / 60);
    $mins_worked = (int)($mins_worked % 60);

    //$hrs_worked = (int)($punch_clock->time_worked / (60*60));
    //$mins_worked = $punch_clock->time_worked % (60*60);

    if ( $punch_clock->time_worked >= 60) {
      // update the punch clock record, which punch's the user out
      if (False == drupal_write_record('qms_punch_clock', $punch_clock, 'punch_clock_id') ) {
        // error
        return drupal_json_output(array(
                                'result' => false,
                                'refresh' => false,
                                'msg' => "ERROR:  Punch Clock Action Failed!<br>" . 
                                       "Please refresh the page and try again.<br>" . 
                                       "Unable to update punch clock record.",
                              ));								
      }
    } else {
      // time worked is less than a minute, bogus punch event , remove the punch clock record
      $num_rows = db_delete('qms_punch_clock')
                  ->condition('punch_clock_id', $punch_clock->punch_clock_id, '=')
                  ->execute();
    }

    $result = True;
    $status = QMS_PUNCH_DISPLAY_STATUS_OUT;
    if ( !$hours_worked && !$mins_worked ) {
      $time_worked_text = t('No time has been logged.');
    }
    else {
      $time_worked_text = t('!h hours, !m minutes have been logged.', 
                            array('!h' => $hours_worked, '!m' => $mins_worked));
    }
    $clocked_in = False;
    $button_text = t(QMS_PUNCH_CLOCK_BTN_CLOCK_IN);
    $action = QMS_PUNCH_CLOCK_IN;
    
    
  } else {
    
    // is the user trying to clock in?  check the action
    if ($action == QMS_PUNCH_CLOCK_OUT) {
      return drupal_json_output(array(
                            'result' => false,
                            'refresh' => true,
                            'status' => QMS_PUNCH_DISPLAY_STATUS_OUT,  
                            'clocked_in' => false, 
                            'button_text' => QMS_PUNCH_CLOCK_BTN_CLOCK_IN, 
                            'action' => QMS_PUNCH_CLOCK_IN,
                            'msg' => "already CLOCKED OUT.",
                          ));									    
    }

    // if user is not punched in, create a new punch clock record.
    $punch_clock = new stdClass;
    $punch_clock->clock_in = REQUEST_TIME;
    $punch_clock->job_id = $job_id;
    $punch_clock->employee_user_id = $user->uid;

    if (False == drupal_write_record('qms_punch_clock', $punch_clock) ) {
      // error 
      return drupal_json_output(array(
                                  'result' => false,
                                  'msg' => "ERROR:  Punch Clock Action Failed!<br>" . 
                                           "Please refresh the page and try again.<br>" . 
                                           "Unable to save punch clock record.",
                                ));										
    }

    $result = True;
    $status = QMS_PUNCH_DISPLAY_STATUS_IN;
    $time_worked_text = '';
    $clocked_in = True;
    $button_text = QMS_PUNCH_CLOCK_BTN_CLOCK_OUT;
    $action = QMS_PUNCH_CLOCK_OUT;
  }
  
	
	return drupal_json_output(array( 'result' => $result, 
                                   'refresh' => false,
																	 'status' => $status,  
																	 'time_worked' => $time_worked_text,
																	 'clocked_in' => $clocked_in, 
																	 'button_text' => $button_text, 
                                   'action' => $action,
                                   /*
                                   'punch_clock_id' => (!empty($punch_clock->punch_clock_id) ? 
                                                          $punch_clock->punch_clock_id : 0),
                                   'time_worked_secs' => (!empty($punch_clock->time_worked) ? 
                                                          $punch_clock->time_worked : 0),
                                    */
																	));	
  
  } catch (Exception $e) {
    watchdog('sabreQMS', 'punch_clock_event_callback() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
  }
	
}

