<?php

namespace LoftyIDX\includes;

defined('ABSPATH') || exit;

class LoftyIDXFacades
{
  private static $valid_ext=['html', 'twig'];

  public static function view($view_file, $variables = [], $return=false)
  {
    $inst = LoftyIDX::get_instance();
    $template_svc = $inst->services['template'];

    // if (!str_ends_with($view_file, '.twig')) {
    //   $view_file .= '.twig';
    // }
    $parts=explode('.', $view_file);
    if(!in_array(end($parts), self::$valid_ext)){
      $view_file .= '.html';  // let file ext default to html
    }

    $template = $template_svc->viewer->load($view_file);

    // Pass the current template name as a context variable
    $variables['current_template'] = $view_file;

    if($return){
      $custom_output = apply_filters('lofty_idx_inject_custom_html_body', []) ?? '';
      if(!empty($custom_output)){
        return $custom_output . $template->render($variables);
      }
      return $template->render($variables);
    }

    ob_start();

    do_action('lofty_idx_inject_custom_html_body');

    $template->display($variables);

    // Output the rendered template, flush output buffer
    ob_end_flush();
  }
}
