<?php
/**
 * @file
 * Module file for diy_meta_alternate
 */

function diy_meta_alternate_preprocess_page(&$vars) {
  
  $languages = language_list();
  
  // process on node-pages for article, video, werkzeug, pages,... 
  if ($node = _diy_meta_alternate_check_for_canonical()) {
    
    // only use domains where current node is published to
    $domainIds = $node->domains;
    if ($node->domain_site) {
      $domainIds = domain_domains();
      $domainIds = array_map(function($obj) { return $obj['domain_id']; }, $domainIds);
    }
    
    // iterate all domains
    foreach ($domainIds as $domainId) {
      $countrycode = diy_meta_alternate_get_country_code_for_domain_id($domainId);
  
      if ($countrycode === false) {
        continue;
      }
  
      $language = $node->language; //current(explode('-', $countrycode));
  
      // check if domain main language exists in languages
      if (empty($languages[$language])) {
        continue;
      }
  
      $path = drupal_lookup_path('alias', 'node/' . $node->nid, $language);
  
      // check if domain has an alias for this language
      if (empty($path)) {
        continue;
      }
  
      // add link to head
      $domain = domain_load($domainId);

      drupal_add_html_head_link(array(
        'rel' => 'alternate',
        'hreflang' => $language.(empty($countrycode) ? '' : '-'.$countrycode),
        'href' => $domain['scheme'].'://'.$domain['subdomain'].'/'.$language.'/'.$path
      ));
    }
  }

  // process on channel pages
  if(arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $term = taxonomy_term_load(arg(2));
 
    // use all active domains
    $domainIds = domain_domains();
    $domainIds = array_map(function($obj) { return $obj['domain_id']; }, $domainIds);
    
    // iterate all domains
    foreach ($domainIds as $domainId) {
      $countrycode = diy_meta_alternate_get_country_code_for_domain_id($domainId);
  
      if ($countrycode === false) {
        continue;
      }
  
      $language = $term->language;
  
      // check if domain main language exists in languages
      if (empty($languages[$language])) {
        continue;
      }

      $path = drupal_lookup_path('alias', 'taxonomy/term/' . $term->tid, $language);
  
      // check if domain has an alias for this language
      if (empty($path)) {
        continue;
      }
  
      // add link to head
      $domain = domain_load($domainId);

      drupal_add_html_head_link(array(
        'rel' => 'alternate',
        'hreflang' => $language.(empty($countrycode) ? '' : '-'.$countrycode),
        'href' => $domain['scheme'].'://'.$domain['subdomain'].'/'.$language.'/'.$path
      ));
    }
  }
  
  // process frontpage
  if(drupal_is_front_page()) {

    $domainIds = domain_domains();
    $domainIds = array_map(function($obj) { return $obj['domain_id']; }, $domainIds);
    
    foreach ($domainIds as $domainId) {
      $countrycode = diy_meta_alternate_get_country_code_for_domain_id($domainId);
  
      if ($countrycode === false) {
        continue;
      }
      
      $domain = domain_load($domainId);
      
      $language = $vars['language']->language;
      
      drupal_add_html_head_link(array(
        'rel' => 'alternate',
        'hreflang' => $language.(empty($countrycode) ? '' : '-'.$countrycode),
        'href' => $domain['scheme'].'://'.$domain['subdomain'].'/'.$language
      ));
      
    }
  }

  
  if ($node = _diy_meta_alternate_check_for_canonical()) {
    if (isset($node->tnid) && drupal_multilingual() && $translations = translation_node_get_translations($node->tnid)) {
    
      // iterate all available translations
      foreach ($translations as $langcode => $translation) {
        /*if ($translation->nid == $node->nid) {
          continue;
        }*/
  
        // get domains where node is published
        $domains = domain_get_node_domains($translation->nid);
  
        if (empty($domains['domain_id'])) {
          continue;
        }
  
        // iterate all domains
        foreach ($domains['domain_id'] as $domainId) {
          $countrycode = diy_meta_alternate_get_country_code_for_domain_id($domainId);
  
          if ($countrycode === false) {
            continue;
          }
  
          $language = $translation->language; //current(explode('-', $countrycode));
  
          if (empty($languages[$language]) || $language != $langcode) {
            continue;
          }
  
          $domain = domain_load($domainId);
          drupal_add_html_head_link(array(
            'rel' => 'alternate',
            'hreflang' => $language.(empty($countrycode) ? '' : '-'.$countrycode),
            'href' => $domain['scheme'].'://'.$domain['subdomain'].'/'.$language.'/'.
              drupal_lookup_path('alias', 'node/' . $translation->nid, $language)
          ));
        }
      }
    }
  }
}

function diy_meta_alternate_html_head_alter(&$head_elements) {
  // remove current canonical link if required
  if(_diy_meta_alternate_check_for_canonical()) {
    foreach (preg_grep('/^drupal_add_html_head_link:canonical:</', array_keys($head_elements)) as $key) {
      unset($head_elements[$key]);
    }
  }
}


function diy_meta_alternate_menu() {
  $items = array();
  $admin = user_access('administer domains');
  $items['admin/structure/diy_meta_alternate'] = array(
    'title' => 'Domain Country Codes',
    'access arguments' => array('administer domain country codes'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('diy_meta_alternate_overview_form'),
    'file' => 'diy_meta_alternate.admin.inc',
    'description' => 'Manage and configure country codes of domains.',
  );
  $items['admin/structure/diy_meta_alternate/view'] = array(
    'title' => 'Domain country code list',
    'access arguments' => array('administer domains'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('diy_meta_alternate_overview_form'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'file' => 'diy_meta_alternate.admin.inc',
    'description' => 'View country codes of domains for the site.',
    'weight' => -50,
  );

  return $items;
}

/**
 * Implements hook_theme().
 */
function diy_meta_alternate_theme($existing, $type, $theme, $path) {
  $themes = array(
    'diy_meta_alternate_overview_form' => array(
      'render element' => 'form',
      'file' => 'diy_meta_alternate.admin.inc',
    ),
  );
  return $themes;
}

/**
 * Custom function to detect if current page requires canonical rewrite
 */
function _diy_meta_alternate_check_for_canonical() {

  if(arg(0) == 'node' && is_numeric(arg(1))) {
    $node = node_load(arg(1));

    if($node && _diy_meta_alternate_check_node_types($node->type)) {
      return $node;
    }
  }

  return false;
}

/**
 * Helper function for making meta-changes
 */
function _diy_meta_alternate_check_node_types($type) {
  $supported = array('article', 'material', 'ct_werkzeug', 'video', 'page');

  if(in_array($type, $supported)) {
    return true;
  }

  return false;
}

function diy_meta_alternate_get_country_code_for_domain_id($domain_id) {
  $res = db_query("SELECT countrycode FROM {diy_domain_countrycode} WHERE domain_id=".((int)$domain_id))->fetchField();
  if ($res !== false) return $res;
  return false;
}

function diy_meta_alternate_is_enabled_domain_id($domain_id) {
  $res = db_query("SELECT enabled FROM {diy_domain_countrycode} WHERE domain_id=".((int)$domain_id))->fetchField();
  if ($res !== false) return $res;
  return false;
}

/**
 * Implements HOOK_metatag_metatags_view_alter().
 */
function diy_meta_alternate_metatag_metatags_view_alter(&$output, $instance) {
  // alter metatag for anbieterprofil
  if($instance == 'global' && arg(0) == 'anbieterprofil' && is_numeric(arg(1)) && is_numeric(arg(2))) {
    if(isset($output['canonical']['#attached']['drupal_add_html_head'][0][0]['#value'])) {

      $branche = node_load(arg(1));
      $domain = domain_load($branche->domain_source);

      $new_canonical = $domain['scheme'].'://'.$domain['subdomain'].'/'. $branche->language . '/' .
        drupal_lookup_path('alias', 'node/' . $branche->nid, $branche->language);

      $output['canonical']['#attached']['drupal_add_html_head'][0][0]['#value'] = $new_canonical;
    }
  }
}