<?php
declare(strict_types=1);

namespace WP_AUX\Entities\PageTemplate\Traits;

trait RenderTemplateTraits
{
  /**
   * Get the absolute path of the page template part based on post type and part type
   * @since 1.0.0
   */
  public function getRenderFile(?string $forceType = null): string
  {
    $type = isset($this->type) ? $this->type : '';
    if (!is_null($forceType)) {
      $type = $forceType;
    }

    /*
     * If type is set for this template part, prioritize file paths for the part type
     */
    if (!empty($type)) {
      $tryPaths = [
        $this->pageTemplate->getPostType() . '/' . $this->templateSlug . '-' . $type,
        $this->pageTemplate->getPostType() . '/' . $this->templateSlug,
        $this->templateSlug . '-' . $type,
        $this->templateSlug,
      ];
    } else {
      /*
       * Default template part file paths for this page part
       */
      $tryPaths = [
        $this->pageTemplate->getPostType() . '/' . $this->templateSlug,
        $this->templateSlug,
      ];
    }

    foreach ($tryPaths as $tryPathKey => $tryPath) {
      $tryPaths[$tryPathKey] = 'template-parts/main-content/' . $tryPath . '.php';
    }

    return locate_template($tryPaths, false);
  }

  /**
   * Render an HTML comment with relevant info about the template part for site admins
   * @since 1.0.0
   */
  public function renderComment(?string $forceType = null): void
  {
    $relativePath = str_replace(
      WP_CONTENT_DIR . '/themes/',
      '',
      $this->getRenderFile($forceType)
    );

    $type = isset($this->type) ? $this->type : '';
    if (!is_null($forceType)) {
      $type = $forceType;
    }

    $comments = [
      'Template Part: ' . $this->templateSlug,
      'Part Type: ' . $type,
      'Post Type: ' . $this->pageTemplate->getPostType(),
      'File Path: ' . $relativePath,
    ];

    echo "<!--\n" . join(";\n", $comments) . "\n-->";
  }

  /**
   * Render the page template part
   * @since 1.0.0
   */
  public function render(?string $forceType = null): void
  {
    $templateFile = $this->getRenderFile($forceType);

    if (empty($templateFile)) {
      return;
    }

    if (is_current_user_admin()) {
      $this->renderComment($forceType);
    }

    load_template($templateFile, null, [$this->templateSlug => $this]);
  }
}
