<?php
// $Id$

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


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

  $items = array();

  $items['fgcf'] = array(
    'title' => 'Catalogue Formations',
    'page callback' => 'fgcf_page_home',
    'access arguments' => $read_access,
    'menu_name' => 'primary-links',
  );
  $items['fgcf/format'] = array(
    'type' => MENU_CALLBACK,
    'title' => 'Formations par format',
    'page callback' => 'fgcf_page_format',
    '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/thematique'] = array(
    'type' => MENU_CALLBACK,
    'title' => 'Formations par thématique',
    'page callback' => 'fgcf_page_thematique',
    'access arguments' => $read_access,
  );
  $items['fgcf/odt'] = array(
    'title' => 'ODT Test',
    'page callback' => 'fgcf_page_odt',
    'access arguments' => $read_access,
  );
  return $items;
}

/**
 * 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_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('filter_form' => array()),
      '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ématique'):
      return 'fgcf/thematique/'. $term->tid;
      break;

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

    // @todo Quid de :
    // - FGCF Supports remis (affiché en lien)
    // - FGCF Sanction (affiché en lien)
    // - FGCF Public visé (affiché en lien)
  }
}

/**
 * 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;
      }
      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),
          );

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

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

/**
 * Page callback : 'Catalogue Formations'.
 */
function fgcf_page_home() {
  drupal_add_css(drupal_get_path('module', 'fgcf') .'/theme/css/fgcf.css');
  drupal_set_title('Catalogue des formations France Galop');

  $filter_form = drupal_get_form('fgcf_filter_form');
  $ret = theme('fgcf_home', $filter_form);

  return $ret;
}

/**
 * Page callback : 'Formations par format'.
 */
function fgcf_page_format($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 Format de cours');
  if (empty($format)) {
    $ret .= views_embed_view('fgcf_formats_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('Formats de formation'), 'fgcf/format');
      drupal_set_title(t('Format : @term', array('@term' => $term->name)));
      $values = _fgcf_filter_form_translate_values();
    }

    $ret .= views_embed_view('fgcf_formations_par_format', '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 = $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ématique' vocab outside the view.
  $vid = _fgcf_get_vocabulary_by_name('FGCF Thématique');
  if (empty($thematique)) {
    // Afficher liste des thématiques 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ématiques'), 'fgcf/thematique');
      $parents = taxonomy_get_parents($thematique);
      $description = $term->description;
    }

    if (empty($parents)) {
      // Top category: display list of sub-categories.
      drupal_set_title(t('Thématique : @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/thematique/'. $parent->tid);
      drupal_set_title(t('Thématique : @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() {
  $odf = fgcf_new_odt(dirname(__FILE__) ."/odtphp/tests/tutoriel1.odt");
  $odf->setVars('titre', 'PHP');
  $message = "PHP est un langage de scripts libre ... hello";
  $odf->setVars('message', $message);
  //$odf->saveToDisk('foo.odt');
  $odf->exportAsAttachedFile();
}

function fgcf_new_odt($filename) {
  fgcf_load_odt();
  $options = array(
    'PATH_TO_TMP' => file_directory_temp() .'/',
    // The PHP Zip extension in recent PHP versions produces corrupt ODT
    // archives. See http://www.odtphp.com/forum/viewtopic.php?f=4&t=43#p154.
    'ZIP_PROXY' => 'PclZipProxy',
  );
  return new odf($filename, $options);
}

function fgcf_load_odt() {
  // Use correct temp folders - see http://www.odtphp.com/forum/viewtopic.php?f=5&t=20#p126

  // Temp folder used by PclZipProxy - see the beginning of PclZipProxy.php.
  // This folder is deleted and recreated each time, so we use a subfolder of
  // the tmp dir.
  define('PCL_ZIP_TMP', file_directory_temp() .'/phpodt/');
  // Temp folder used by the pclzip library - see the beginning of
  // pclzip.lib.php.
  define('PCLZIP_TEMPORARY_DIR', file_directory_temp() .'/');

  // Load the OdtPHP library.
  require_once(dirname(__FILE__) .'/odtphp/library/odf.php');
}

/**
 * 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;
}

/**
 * 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'),
      '3'   => 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)) {
      $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
 */
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];
}