<?php
/**
 * @file
 * Main file for metatag_panels module.
 */

/**
 * Implements hook_page_manager_variant_operations_alter().
 */
function metatag_panels_page_manager_variant_operations_alter(&$operations, $handler) {
  // Use this obnoxious construct to safely insert our item.
  reset($operations['children']);
  $children_operations = array();
  while (list($key, $value) = each($operations['children'])) {
    $children_operations[$key] = $value;
    if ($key == 'context') {
      $children_operations['meta'] = array(
        'title' => t('Meta tags'),
        'description' => t('Edit variant level meta tags.'),
        'form' => 'metatag_panels_form',
      );
    }
  }
  $operations['children'] = $children_operations;
}

/**
 * Metatag panels configuration form.
 */
function metatag_panels_form($form, $form_state) {
  $handler = $form_state['handler'];

  // Load available contexts
  ctools_include('context-task-handler');
  $contexts = ctools_context_handler_get_all_contexts($form_state['task'], $form_state['subtask'], $handler);

  // Convert contexts into keywords readable by the token engine.
  $token_types = array();

  foreach ($contexts as $context) {
    if ($context->keyword == 'taxonomy_term') {
      $token_types[] = 'term';
    }
    else {
      $token_types[] = $context->keyword;
    }
  }

  // Allow the user to enable/disable meta tags for this panel.
  $form['settings']['metatags_enabled'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable Metatag configuration.'),
    '#default_value' => isset($handler->conf['metatag_panels']['enabled']) ? $handler->conf['metatag_panels']['enabled'] : FALSE,
  );

  // Don't set any metatag instance name as the configuration data is managed locally within panels.
  $instance = '';
  $options = array('token types' => $token_types);
  $metatags = empty($handler->conf['metatag_panels']) ? array() : $handler->conf['metatag_panels']['metatags'];

  // This leaves some possibility for future versions to support translation.
  if (!isset($metatags[LANGUAGE_NONE])) {
    $metatags = array(LANGUAGE_NONE => $metatags);
  }

  // Load the metatag form (passed by reference).
  metatag_metatags_form($form, $instance, $metatags[LANGUAGE_NONE], $options);

  // Modify metatag form defaults.
  $form['metatags']['#collapsible'] = FALSE;
  $form['metatags']['#collapsed'] = FALSE;

  // Don't show the Metatag options until it's enabled.
  $form['metatags']['#states'] = array(
    'visible' => array(
      ':input[name="metatags_enabled"]' => array('checked' => TRUE),
    ),
  );

  return $form;
}

/**
 * Submission handler for Metatag panels configuration form.
 */
function metatag_panels_form_submit($form, $form_state) {
  $conf = array(
    'enabled' => $form_state['values']['metatags_enabled'],
    'metatags' => $form_state['values']['metatags'][LANGUAGE_NONE],
  );

  $form_state['handler']->conf['metatag_panels'] = $conf;
}

/**
 * Implements hook_ctools_render_alter().
 */
function metatag_panels_ctools_render_alter($info, $page, $context) {
  $output = &drupal_static('metatag_panels');

  $handler = $context['handler'];

  if (empty($handler->conf['metatag_panels']) || !$handler->conf['metatag_panels']['enabled']) {
    return;
  }

  // This leaves some possibility for future versions to support translation.
  $metatags = $handler->conf['metatag_panels']['metatags'];
  if (!is_array($metatags) || empty($metatags)) {
    $metatags = array();
  }

  // If meta tags were found but they're not nested for the language, fix it.
  // This leaves some possibility for future versions to support translation.
  if (!empty($metatags) && !isset($metatags[LANGUAGE_NONE])) {
    $metatags = array(LANGUAGE_NONE => $metatags);
  }

  // Append global defaults.
  $all_metatags = array();
  foreach ($metatags as $langcode => $values) {
    if (!empty($values)) {
      $all_metatags = $values + metatag_config_load_with_defaults('');
    }
  }
  $metatags = $all_metatags;

  if (empty($metatags)) {
    return;
  }

  // Get the contexts that exist within this panel.
  ctools_include('context-task-handler');
  $task_object = ctools_context_handler_get_task_object($context['task'], $context['subtask'], $context['handler']);
  $task_contexts = ctools_context_load_contexts($task_object, TRUE, $context['contexts']);

  // Build the tokens out of CTools contexts.
  $tokens = array();
  foreach ($task_contexts as $task_context) {
    $tokens[$task_context->keyword] = $task_context->data;
  }

  // Because of page execution order, sometimes the page title does not get set
  // by Panels in time for metatags to use it, so we'll explicitly set it here
  // if we need to.
  if (!empty($info['title'])) {
    drupal_set_title($info['title'], PASS_THROUGH);
  }

  // Build the Metatag.
  $options = array(
    'instance' => 'panels:' . $handler->name,
    'token data' => $tokens,
  );
  foreach ($metatags as $metatag => $data) {
    $metatag_instance = metatag_get_instance($metatag, $data);

    if ($metatag_instance) {
      $output[$metatag] = $metatag_instance->getElement($options);
    }
  }

  // Give third-parties the opportunity to alter the metatag for a given instance.
  drupal_alter('metatag_metatags_view', $output, $options['instance']);
}

/**
 * Implements hook_page_build().
 *
 * @see metatag_panels_ctools_render_alter()
 */
function metatag_panels_page_build(&$page) {
  $metatags = drupal_static('metatag_panels');

  if (!empty($metatags)) {
    $page['content']['metatags']['global'] = $metatags;
  }
}
