<?php

namespace Aoc2025\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($substitutions = []) {
    $this->replaceSections();
    
    if ($substitutions) {
      foreach ($substitutions as $key => $value) {
        $this->template = str_replace('{{ ' . $key . ' }}', $value, $this->template);
      }
    }

    return $this->template;
  }

  /**
   * Replaces all sections in the template with the contents of the included file.
   */
  public function replaceSections() {
    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);
    }

    return $this->template;
  }

}
