<?php

/**
 * @file
 * Contains archibald_stats_date_field.
 */

class archibald_stats_date_field extends views_handler_field_date {

  /**
   * @{inheritdoc}
   */
  function render($values) {
    // The date field doesn't actually exist. Instead, we have to construct it
    // from the year, month and day fields.
    $values->date = !isset($values->month) ?
      strtotime("{$values->year}-01-01") :
      (
        isset($values->day) ?
          strtotime("{$values->year}-{$values->month}-{$values->day}") :
          strtotime("{$values->year}-{$values->month}-01")
      );

    // Check the format. By default, it will by "d/m/Y", which doesn't suffice
    // for certain aggregation methods.
    if ($this->options['date_format'] == 'custom') {
      $custom_format = $this->options['custom_date_format'];

      if (preg_match('/d/', $custom_format) && !isset($values->day)) {
        $this->options['custom_date_format'] = preg_replace('/.*d(-|\/| )/', '', $custom_format);
      }

      if (preg_match('/m/', $custom_format) && !isset($values->month)) {
        $this->options['custom_date_format'] = preg_replace('/.*m(-|\/| )/', '', $custom_format);
      }
    }

    return parent::render($values);
  }
}
