<?php

class bigw_handler_field_time_taken extends views_handler_field {

   /**
    * Loads additional fields.
    */
   function query() {
      $this->ensure_my_table();
      $this->add_additional_fields();
   }

   /**
    * Default options form.
    */
   function option_definition() {
      $options = parent::option_definition();

      $options['time_start'] = array('default' => '');
      $options['time_end'] = array('default' => '');

      return $options;
   }

   /**
    * Creates the form item for the options added.
    */
   function options_form(&$form, &$form_state) {
      parent::options_form($form, $form_state);

      $form['time_start'] = array(
         '#type' => 'textfield',
         '#title' => t('Quiz start date'),
         '#default_value' => $this->options['time_start'],
         '#description' => t('Pass start date.'),
         '#weight' => -10,
      );

      $form['time_end'] = array(
         '#type' => 'textfield',
         '#title' => t('Quiz end date'),
         '#default_value' => $this->options['time_end'],
         '#description' => t('Pass start date.'),
         '#weight' => -10,
      );
      
   }

   /**
    * Renders the field handler.
    */
   function render($values) {
      $time_start = $values->quiz_node_results_time_start != NULL ? $values->quiz_node_results_time_start : 0;
      $time_end = $values->quiz_node_results_time_end != NULL ? $values->quiz_node_results_time_end : 0;
      $diff = NULL;
      if ($time_start != 0 && $time_end != 0) {
         $o_time_start = new DateTime();
         $o_time_end = new DateTime();
         $o_time_start->setTimestamp($time_start);
         $o_time_end->setTimestamp($time_end);
         $diff = $o_time_start->diff($o_time_end);
      }
      if ($diff != NULL) {
         $days = $diff->d != 0 ? $diff->d . 'd ' : '';
         $hours = $diff->h != 0 ? $diff->h . 'h ' : '';
         $mins = $diff->i != 0 ? $diff->i . 'm ' : '';
         $seconds = $diff->s != 0 ? $diff->s . 's': '';
         return $days . $hours . $mins . $seconds;
      }
      return '';
   }
}