<?php

/**
 * Implements hook_mail().
 */
function scratchpads_data_integrity_mail($key, &$message, $params){
  switch($key){
    case 'maintainer':
      $message = array_merge($message, array(
        'subject' => t('Your Scratchpad has a data issue'),
        'body' => array(
          'Dear Scratchpad Maintainer',
          'There appears to be an issue with the data on your site.  The Scratchpads Team has been informed of this issue, so we will already be working on repairing your data.',
          'Depending on the issue, this may well affect how your site is functioning.  If you have experienced any problems, then please report them to us.',
          'There is no reason to be concerned by this, but if you would like further information, then please do not hesitate to reply to this message.',
          'Thanks,',
          'Scratchpads Support Team',
          "--\nsupport@scratchpads.org"
        )
      ));
      break;
    case 'scratchpads_team':
      $message = array_merge($message, array(
        'subject' => t('Scratchpads data integrity: !site_url', array(
          '!site_url' => $params['site_url']
        )),
        'body' => array_merge(array(
          'Scratchpads Team,',
          t('The following issues were found with !site_url:', array(
            '!site_url' => $params['site_url']
          ))
        ), $params['messages'], array(
          'Thanks,',
          'Scratchpads Support Team',
          "--\nsupport@scratchpads.org"
        ))
      ));
  }
}

/**
 * Implements hook_menu().
 */
function scratchpads_data_integrity_menu(){
  return array(
    'admin/reports/scratchpads-data-integrity' => array(
      'title' => 'Scratchpads Data Issues',
      'description' => 'View a list of all issues with this Scratchpad.',
      'page callback' => 'scratchpads_data_integrity_overview',
      'access arguments' => array(
        'access site reports'
      ),
      'weight' => -1,
      'file' => 'scratchpads_data_integrity.pages.inc'
    )
  );
}

/**
 * Implements hook_scratchpads_data_integrity().
 */
function scratchpads_data_integrity_scratchpads_data_integrity(){
  return array(
    'scratchpads_data_integrity_check_all_terms_have_parents' => array(
      'file' => 'scratchpads_data_integrity.inc',
      'mail' => TRUE
    ),
    'scratchpads_data_integrity_check_taxonomy_for_loops' => array(
      'file' => 'scratchpads_data_integrity.inc',
      'mail' => TRUE
    ),
    'scratchpads_data_integrity_check_for_terms_in_deleted_vocabularies' => array(
      'file' => 'scratchpads_data_integrity.inc',
      'frequency' => 604800,
      'mail' => FALSE
    ),
    'scratchpads_data_integrity_check_for_deleted_files' => array(
      'file' => 'scratchpads_data_integrity.inc',
      'frequency' => 604800,
      'mail' => FALSE
    ),
    /*'scratchpads_data_integrity_check_for_orphan_field_values' => array(
      'file' => 'scratchpads_data_integrity.inc',
      'frequency' => 604800,
      'mail' => TRUE
    )*/
  );
}

/**
 * Helper function to get a list of messages.
 *
 * $mail = Whether or not to return messages that are not for mailing.
 * $all = Whether or not to ignore the last run time
 */
function scratchpads_data_integrity_get_messages($mail = FALSE, $all = FALSE){
  // Get a list of functions to run.
  $data_ints = array();
  foreach(module_implements('scratchpads_data_integrity') as $module){
    $new_ints = call_user_func($module . '_scratchpads_data_integrity');
    foreach(array_keys($new_ints) as $key){
      if(!empty($new_ints[$key]['file'])){
        $new_ints[$key]['file'] = DRUPAL_ROOT . '/' . drupal_get_path('module', $module) . "/" . $new_ints[$key]['file'];
      }
      if(empty($new_ints[$key]['frequency'])){
        $new_ints[$key]['frequency'] = 86400;
      }
    }
    $data_ints = array_merge($data_ints, $new_ints);
  }
  // Alter the data-ints
  drupal_alter('scratchpads_data_integrity', $data_ints);
  // Get the last run time of each int as an array
  $last_run = variable_get('scratchpads_data_integrity_last_run', array());
  // Loop through each, and add the messages that are returned to the list.
  $messages = array();
  $time = time();
  foreach($data_ints as $func => $int){
    if(($mail || !empty($int['mail'])) && ($all || empty($last_run[$func]) || $last_run[$func] + $int['frequency'] < $time)){
      if(!empty($int['file'])){
        require_once $int['file'];
      }
      $output = $func();
      if(is_array($output) && count($output)){
        if(!empty($int['description'])){
          $messages[] = $int['description'];
        }
        $messages = array_merge($messages, $output);
      }
      $last_run[$func] = $time;
    }
  }
  if(!$all){
    variable_set('scratchpads_data_integrity_last_run', $last_run);
  }
  return $messages;
}

/**
 * Implements hook_cron().
 */
function scratchpads_data_integrity_cron(){
  // Get a list of messages
  $messages = scratchpads_data_integrity_get_messages();
  if(count($messages)){
    global $language;
    /*
     * The following code will be allowed to run once we are confident that
     * there are no sites with large quantities of problematic data.
     *
    $query = db_select('users', 'u');
    $query->innerJoin('users_roles', 'r', 'u.uid = r.uid');
    $results = $query->condition('rid', 5)->fields('u', array(
      'mail'
    ))->execute();
    foreach($results as $row){
      drupal_mail('scratchpads_data_integrity', 'maintainer', $row->mail, $language, array(
        'site_url' => url('', array(
          'absolute' => TRUE
        ))
      ), 'Scratchpads Support Team <support@scratchpads.org>');
    }
    */
    drupal_mail('scratchpads_data_integrity', 'scratchpads_team', 'Scratchpads Support Team <support@scratchpads.org>', $language, array(
      'site_url' => url('', array(
        'absolute' => TRUE
      )),
      'messages' => $messages
    ), 'Scratchpads Team (No reply) <no-reply@scratchpads.org>');
  }
}
