<?php
// $Id$

/**
 * @file
 * Non-features part of FGCF
 */
include_once('fgcf.features.inc');

/**
 * Implementation of hook_init().
 */
function fgcf_init() {
  if (arg(0) == 'fgcf') {
    drupal_add_css(drupal_get_path('module', 'fgcf') .'/theme/css/fgcf.css');
  }
}

/**
 * Implementation of hook_menu().
 */
function fgcf_menu() {
  $read_access = array('access course catalog');

  $items = array();

  // 'admin/settings/fg' est défini dans fgrhm, qui est une dépendance de ce module.
  $items['admin/settings/fg/fgcf'] = array(
    'title'            => 'Catalogue formations',
    'description'      => 'Réglages du catalogue de formations',
    'type'             => MENU_LOCAL_TASK,
    'access arguments' => array('administer site configuration'),
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('fgcf_admin_settings'),
    'file'             => 'fgcf.admin.inc',
    'weight'           => 0,
  );

  $items['fgcf'] = array(
    'title' => 'Catalogue formations',
    'page callback' => 'fgcf_page_home',
    'access arguments' => $read_access,
    'menu_name' => 'primary-links',
  );
  $items['fgcf/support'] = array(
    'type' => MENU_CALLBACK,
    'title' => 'Formations par support',
    'page callback' => 'fgcf_page_support',
    'access arguments' => $read_access,
  );
  $items['fgcf/organisme'] = array(
    'type' => MENU_CALLBACK,
    'title' => 'Formations par organisme',
    'page callback' => 'fgcf_page_organisme',
    'access arguments' => $read_access,
  );
  $items['fgcf/theme'] = array(
    'type' => MENU_CALLBACK,
    'title' => 'Formations par thème',
    'page callback' => 'fgcf_page_thematique',
    'access arguments' => $read_access,
  );
  $items['fgcf/odt'] = array(
    'title' => 'ODT Test',
    'page callback' => 'fgcf_page_odt',
    'access arguments' => array('create fgcf_fiche content'),
  );

  return $items;
}

/**
 * Implementation of hook_perm().
 */
function fgcf_perm() {
  return array('access course catalog');
}

/**
 * Implementation of hook_theme().
 */
function fgcf_theme($existing, $type, $theme, $path) {
  $ret = array(
    'fgcf_home' => array(
      'arguments' => array('links' => array(), 'content' => NULL),
      'template'  => 'fgcf-home',
      'path'      => $path .'/theme',
    ),
    'fgcf_thematiques' => array(
      'arguments' => array('terms' => array()),
    ),
  );

  return $ret;
}

/**
 * Implementation of hook_term_path().
 */
function fgcf_term_path($term) {
  $vocabulary = taxonomy_vocabulary_load($term->vid);
  switch ($vocabulary->vid) {
    case _fgcf_get_vocabulary_by_name('FGCF Théme'):
      return 'fgcf/theme/'. $term->tid;
      break;

    case _fgcf_get_vocabulary_by_name('FGCF Format de cours'):
      return 'fgcf/format/'. $term->tid;
      break;

    default:
      // Terms in other vocabs should be set to display 'as text' (no link)
      break;
  }
}

/**
 * Implementation of hook_views_api().
 */
function fgcf_views_api() {
  $ret = array(
    'api'  => '2',
    'path' => drupal_get_path('module', 'fgcf') . '/views',
  );
  return $ret;
}

/**
 * Implementation of hook_nodeapi().
 */
function fgcf_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'view':
      // Only operate on 'page' view.
      if ($a3 /* !teaser */  || !$a4 /* page */) {
        break;
      }

      // Not redundant with hook_init: fgcf node pages are not on fgcf[/.*] URLs
      if (in_array($node->type, array_keys(fgcf_node_info()))) {
        drupal_add_css(drupal_get_path('module', 'fgcf') .'/theme/css/fgcf.css');
      }

      switch ($node->type) {
        case 'fgcf_prestataire':
          $bc = drupal_get_breadcrumb();
          $bc[] = l(t('Catalogue formations'), 'fgcf');
          $bc[] = l(t('Organismes'), 'fgcf/organisme');
          drupal_set_breadcrumb($bc);
          break;

        case 'fgcf_fiche':
          $nat_config = variable_get('nat_config', NULL);
          $vid = isset($nat_config['types']['fgcf_thematique'])
            ? reset($nat_config['types']['fgcf_thematique'])
            : 0;
          unset($nat_config);
          $taxo2 = array();
          foreach ($node->taxonomy as $tid => $term) {
            if ($term->vid != $vid) {
              $taxo2[$tid] = $term;
            }
            else {
              $node->fgcf_scat = $term; // Single by configuration
            }
          }
          $node->taxonomy = $taxo2;
          unset($taxo2, $tid, $term);

          // Build cat/scat[/scat]* path
          $cats = array();
          $parents = taxonomy_get_parents($node->fgcf_scat->tid);
          foreach ($parents as $tid => $term) {
            $cats[] = $term;
          }
          $cats[] = $node->fgcf_scat;
          $node->content['fgcf_catpath'] = array(
            '#value' => theme('fgcf_thematiques', $cats),
          );

          // Add 'Subscribe' button.
          $node->content['fgcf_subscribe'] = array(
            '#value' => drupal_get_form('fgcf_subscribe_form', $node),
            '#weight' => -100,
          );

          $bc = drupal_get_breadcrumb();
          $bc[] = l(t('Catalogue formations'), 'fgcf');
          $bc[] = l(t('Thèmes'), 'fgcf/theme');
          $bc[] = l($cats[0]->description, 'fgcf/theme/'. $cats[0]->tid);
          $bc[] = l($cats[1]->description, 'fgcf/theme/'. $cats[1]->tid);
          drupal_set_breadcrumb($bc);

          unset($cats, $parents, $tid, $term);
          break;
      }
  }
}

/**
 * Page callback : 'Catalogue Formations'.
 */
function fgcf_page_home() {
  drupal_set_title('Catalogue des formations France Galop');

  $links = array(
    l(t('Formations par organisme'), 'fgcf/organisme'),
    l(t('Formations par support'), 'fgcf/support'),
  );
  $ret = theme('fgcf_home', $links, fgcf_page_thematique());
  return $ret;
}

/**
 * Page callback : 'Formations par support'.
 */
function fgcf_page_support($format = 0) {
  $bc = drupal_get_breadcrumb();
  $bc[] = l(t('Catalogue formations'), 'fgcf');

  $filter_form = drupal_get_form('fgcf_filter_form');

  $ret = $filter_form;
  $vid = _fgcf_get_vocabulary_by_name('FGCF Supports de cours');
  if (empty($format)) {
    $ret .= views_embed_view('fgcf_supports_de_formations', 'default', $vid);
  }
  else {
    $term = taxonomy_get_term($format);
    if (!is_object($term) || !isset($term->vid) || $term->vid != $vid) {
      $format = 0;
    }
    else {
      $bc[] = l(t('Supports de formation'), 'fgcf/support');
      drupal_set_title(t('Support: @term', array('@term' => $term->name)));
      $values = _fgcf_filter_form_translate_values();
    }

    $ret .= views_embed_view('fgcf_formations_par_support', 'default', $format, $values['dif'], $values['modalites']);
  }

  drupal_set_breadcrumb($bc);
  return $ret;
}

/**
 * Page callback : 'Formations par organisme'.
 */
function fgcf_page_organisme() {
  $bc = drupal_get_breadcrumb();
  $bc[] = l(t('Catalogue formations'), 'fgcf');
  drupal_set_breadcrumb($bc);

  $filter_form = drupal_get_form('fgcf_filter_form');

  $ret = views_embed_view('fgcf_organismes_de_formation');

  return $ret;
}

/**
 * Page callback : 'Formations par thematique'.
 */
function fgcf_page_thematique($thematique = 0) {
  $bc = drupal_get_breadcrumb();
  $bc[] = l(t('Catalogue formations'), 'fgcf');

  $filter_form = drupal_get_form('fgcf_filter_form');

  $ret = $filter_form;

  // The views itself doesn't mention vocab ids, which might be different in dev
  // and in production.
  // We limit to terms in the 'Thème' vocab outside the view.
  $vid = _fgcf_get_vocabulary_by_name('FGCF Thème');
  if (empty($thematique)) {
    // Afficher liste des thèmes de 1er niveau.
    $ret .= views_embed_view('fgcf_thematiques_premier_niveau', 'default', $vid);
  }
  else {
    $term = taxonomy_get_term($thematique);
    $parents = array();

    if (!is_object($term) || !isset($term->vid) || $term->vid != $vid) {
      $thematique = 0;
      $description = '';
    }
    else {
      $bc[] = l(t('Thèmes'), 'fgcf/theme');
      $parents = taxonomy_get_parents($thematique);
      $description = $term->description;
    }

    if (empty($parents)) {
      // Top category: display list of sub-categories.
      drupal_set_title(t('Thème : @term', array('@term' => $description)));
      $ret .= views_embed_view('fgcf_thematique_deuxieme_niveau', 'default', $thematique);
    }
    else {
      // Sub-category: display list of nodes.
      $parent = current($parents);
      $bc[] = l($parent->description, 'fgcf/theme/'. $parent->tid);
      drupal_set_title(t('Thème : @term', array('@term' => $description)));

      $values = _fgcf_filter_form_translate_values();
      $ret .= views_embed_view('fgcf_formations_par_thematique', 'default', $thematique, $values['dif'], $values['modalites']);
    }
  }

  drupal_set_breadcrumb($bc);

  return $ret;
}

/**
 * Page callback : 'ODT test'.
 */
function fgcf_page_odt() {
  module_load_include('inc', 'fgcf', 'fgcf.odt');

  $template = dirname(__FILE__) ."/catalogue_template.odt";
  $template = "catalogue_template.odt";
  $odf = fgcf_odt_export_formations($template);
  $odf->exportAsAttachedFile('catalogue.odt');
}

/**
 * Theme function for course themes.
 */
function theme_fgcf_thematiques($terms) {
  $items = array();
  foreach ($terms as $tid => $term) {
    $items[] = l($term->description, taxonomy_term_path($term));
  }

  // Build cat logo
  $cat_term = reset($terms);
  $nodes = nat_get_nids(array($cat_term->tid), TRUE);
  $cat_node = reset($nodes);
  $node_view = node_build_content($cat_node, FALSE, FALSE);
  $logo = drupal_render($node_view->content['field_fgcf_thematique_logo']);
  array_unshift($items, $logo);

  $ret = '<div class="node-thematique">'. theme('item_list', $items) .'</div>';
  return $ret;
}

/**
 * Subscribe form displayed on 'formations' nodes.
 */
function fgcf_subscribe_form($form_state, $node) {
  global $user;

  $form['node'] = array(
    '#type' => 'value',
    '#value' => $node,
  );
  if ($user->uid) {
    $form['subscribe'] = array(
      '#type' => 'submit',
      '#value' => t('Inscrivez-moi'),
    );
  }

  return $form;
}

/**
 * Submit handler for the subscribe form.
 *
 * Send an email to site administrators.
 */
function fgcf_subscribe_form_submit($form, &$form_state) {
  global $user;

  // Prevent flooding.
  $flood_limit = variable_get('fgcf_subscribe_flood', 10);
  if ($flood_limit && flood_is_allowed('fgcf_subscribe', $flood_limit)) {
    $to = variable_get('fgcf_mail_destination', variable_get('site_mail', ini_get('sendmail_from')));
    $params = array(
      'account' => $user,
      'node' => $form_state['values']['node'],
    );

    $message = drupal_mail('fgcf', 'subscribe', $to, language_default(), $params);
    if ($message['result']) {
      drupal_set_message(t("Votre demande a été transmise aux administrateurs du site."));
      flood_register_event('fgcf_subscribe');
    }
  }
}

/**
 * Implementation of hook_mail().
 */
function fgcf_mail($key, &$message, $params) {
  $language = $message['language'];

  switch ($key) {
    case 'subscribe':
      // Generate base replacement strings.
      $variables = user_mail_tokens($params['account'], $language);
      // Add our own.
      $node = $params['node'];
      $variables['@node_title'] = $node->title;
      $variables['@node_reference'] = $node->field_fgcf_fiche_reference[0]['value'];
      $variables['!node_uri'] = url('node/' . $node->nid, array('absolute' => TRUE));
      $variables['!user_ip'] = ip_address();

      $message['subject'] = t('[France-galop] Inscription à une formation', $variables, $language->language);
      $message['body'][] = t("Formation: @node_reference - @node_title (!node_uri)\nUtilisateur: !username\nMail: !mailto\nIP de connection: !user_ip", $variables, $language->language);
      break;
  }
}

/**
 * Shared filter form for course lists.
 *
 * Filter values are taken from the form logic or, when absent, from the
 * session, in order for them to be persistent across non-form pages.
 *
 * @return array
 */
function fgcf_filter_form($form_state) {

  $form['filtre'] = array(
    '#title' => t('Filtrer les formations'),
    '#attributes' => array('class' => 'fgcf-filtre'),
    '#type' => 'fieldset',
    '#collapsible' => TRUE,
  );

  $dif = isset($form_state['storage']['dif'])
    ? $form_state['storage']['dif']
    : isset($_SESSION['fgcf']['dif'])
      ? $_SESSION['fgcf']['dif']
      : FALSE;
  $form['filtre']['dif'] = array(
    '#type' => 'checkbox',
    '#default_value' => $dif,
    '#title'         => t('Eligibles DIF'),
  );

  $modalite = isset($form_state['storage']['modalite'])
    ? $form_state['storage']['modalite']
    : isset($_SESSION['fgcf']['modalite'])
      ? $_SESSION['fgcf']['modalite']
      : array();
  $form['filtre']['modalite'] = array(
    '#title'   => t('Modalité'),
    '#type'    => 'checkboxes',
    '#options' => array(
      '1'    => t('Inter-entreprises'),
      '2'    => t('Intra-entreprise'),
      '999'  => t('Autres'),
    ),
    '#default_value' => $modalite,
  );

  $form['filtre']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Appliquer le filtre'),
  );

  return $form;
}

/**
 * Submit handler for fgcf_filter_form().
 */
function fgcf_filter_form_submit($form, &$form_state) {
  foreach (array('modalite', 'dif') as $key) {
    $value = $form_state['values'][$key];
    $form_state['storage'][$key] = $value;
    $_SESSION['fgcf'][$key] = $value;
  }
}

/**
 * Translate values in the filter form into arguments for the views.
 */
function _fgcf_filter_form_translate_values() {
  // Default values.
  $values = array(
    'dif' => 'all',
    'modalites' => 'all',
  );

  if (isset($_SESSION['fgcf']['dif']) && $_SESSION['fgcf']['dif']) {
    $values['dif'] = 'o';
  }

  if (isset($_SESSION['fgcf']['modalite'])) {
    $modalites = array_filter($_SESSION['fgcf']['modalite']);
    if (!empty($modalites)) {
      // 'Autres' (999) means 'all other values than 1 and 2'.
      // Translate this into actual values.
      if (isset($modalites[999])) {
        // Get the actual possible values from the field definition.
        $field = content_fields('field_fgcf_fiche_modalite', 'fgcf_fiche');
        $allowed_values = content_allowed_values($field);
        // Remove the first 2 options.
        unset($allowed_values[1], $allowed_values[2]);
        // Remove the 'proxy' 'Autres' choice.
        unset($modalites[999]);
        // Add the actual values.
        $modalites += drupal_map_assoc(array_keys($allowed_values));
      }
      $values['modalites'] = implode('+', array_keys($modalites));
    }
  }
  return $values;
}

/**
 * Helper: get a vocabulary ID from its name.
 *
 * @todo : inefficient - replace with constants once the vocabs are deployed ?
 *
 * @param string $name
 *
 * @return int
 */
function _fgcf_get_vocabulary_by_name($name) {
  static $matches = array();

  if (!isset($matches[$name])) {
    $matches[$name] = 0;
    $vocabularies = taxonomy_get_vocabularies();
    foreach ($vocabularies as $vid => $vocabulary) {
      if (drupal_strtolower($vocabulary->name) == drupal_strtolower($name)) {
        $matches[$name] = $vid;
        break;
      }
    }
  }

  return $matches[$name];
}