<?php

namespace Origo\Services;

class Template {

  /**
   * The template to render.
   */
  protected $template;

  /**
   * Creates a new Template object.
   */
  public function __construct($template_name) {
    $this->template = file_get_contents('templates/' . $template_name);
  }

  /**
   * Renders the template and returns the result.
   */
  public function render(array $replacements = []) {
    $this->swapHtml();
    
    if ($replacements) {
      $this->replaceSections($replacements);
    }

    return $this->template;
  }

  /**
   * Replace dynamic sections.
   * 
   * @param array $swaps
   *   An array of placeholders and their replacements.
   */
  public function replaceSections(array $swaps) {
    foreach ($swaps as $placeholder => $contents) {
      $placeholder = "{{ " . $placeholder . " }}";
      $this->template = str_replace($placeholder, $contents, $this->template);
    }
  }

  /**
   * Replaces all sections in the template with the contents of the included file.
   */
  public function swapHtml() {
    preg_match_all('/\[\[\s*(.+?)\s*\]\]/', $this->template, $matches);

    foreach ($matches[0] as $i => $placeholder) {
      $filename = $matches[1][$i];
      $template_path = rtrim('templates', '/') . '/' . $filename;

      if (file_exists($template_path)) {
        $contents = file_get_contents($template_path);
      } 
      else {
        $contents = "<!-- Missing include: {$filename} -->";
      }
      $this->template = str_replace($placeholder, $contents, $this->template);
    }
  }

}
