<?php

/**
 * @file
 * A drush script that imports/updates migrated pages.
 */

require_once(__DIR__ . "/vendor/autoload.php");

use Drupal\node\Entity\Node;
use Drupal\paragraphs\Entity\Paragraph;
use PHPHtmlParser\Dom;

// conversion from external terms to internal terms
$nav_terms = []; // not used

// This is the csv file holdings the list of incoming legacy URLs.
// @see README.md
$source_urls_csv = dirname(__FILE__) . '/../source_urls.csv';

$translations_map = dirname(__FILE__) . '/../translations_map.csv';
$fp = fopen($translations_map, 'w+');
$translations = [];

$htaccess = dirname(__FILE__) . '/../htaccess';

if (file_exists($source_urls_csv)) {
  // Log all the errors together.
  $error_log = [];

  $file_lines = file($source_urls_csv);
  // Get rid of the CSV header.
  array_shift($file_lines);

  // Iterate through all the lines and extract the URL and title.
  foreach ($file_lines as $index => $file_line) {
    $line_tokens = array_map(
      function ($value) {
        return trim($value);
      },
      array_filter(
        explode("\t", $file_line),
        function ($value) {
          return !empty(trim($value));
        }
      )
    );

    $url_old = trim(array_shift($line_tokens));
    $old_page = file_get_contents("http://www.svv.ch/" . $url_old);

    $url_new = trim(array_shift($line_tokens));
    $new_page = file_get_contents("http://svv.dev/" . $url_new);

    $dom_old = new Dom;
    $dom_old->load($old_page);
    $translations_old = dom_extract_translations($dom_old, '#block-locale-0 li a');

    $dom_new = new Dom;
    $dom_new->load($new_page);
    $translations_new = dom_extract_translations($dom_new, '#block-languageswitcher li a');

    //$translations['de'] = $url_old
    $redirect_original = "\n# Redirect from " . $url_old . ' to ' . $url_new;
    file_put_contents($htaccess, $redirect_original . "\n", FILE_APPEND);

    foreach ($translations_old as $lang => $tr) {
      if (trim($tr) != '') {
        if ($translations_new[$lang] && $translations_new[$lang] != "/$lang") {
          $redirect = 'Redirect 301 ' . $tr . ' ' . $translations_new[ $lang ];
        }
        else {
          $redirect = '# Redirect 301 ' . $tr . ' ' . $translations_new[ $lang ];
        }
        file_put_contents($htaccess, $redirect . "\n", FILE_APPEND);
        echo "$redirect \n";
      }
    }
  }
}

/**
 * Extract filtered body content from DOM as string.
 */
function dom_extract_translations($dom, $langdropdown_selector) {
  $links = $dom->find($langdropdown_selector);

  $translations = ['de' => '', 'fr' => '', 'it' => '', 'en' => ''];
  foreach ($links as $link){
    $translations[strtolower($link->text)] = $link->href;
  }
  return $translations;
}


