<?php

declare(strict_types=1);

namespace CloudXM\NFe\Admin;

use CloudXM\SDK\Support\HasLogger;

/**
 * Template loading trait for admin components
 *
 * Provides consistent template loading functionality across controllers and pages
 */
trait HasTemplate
{
    use HasLogger;

    /**
     * Load and render a template file
     *
     * @param string $template Template path relative to templates directory (e.g., 'admin/settings/main')
     * @param array $data Data to extract into template scope
     */
    protected function loadTemplate(string $template, array $data = []): void
    {
        // Ensure plugin path constant is defined
        if (!defined('CLOUDXM_NFE_PATH')) {
            $this->log()->error('nfe.template.missing_plugin_path', [
                'template' => $template,
                'data_keys' => array_keys($data)
            ]);
            echo '<div class="notice notice-error"><p>';
            printf(__('Plugin path not defined. Cannot load template %s.', 'woocommerce-cloudxm-nfe'), esc_html($template));
            echo '</p></div>';
            return;
        }

        // Build full template path
        $file = CLOUDXM_NFE_PATH . "templates/{$template}.php";

        if (file_exists($file)) {
            // Extract data into local scope for template
            extract($data, EXTR_SKIP);

            // Include template
            include $file;

            $this->log()->debug('nfe.template.loaded', [
                'template' => $template,
                'file' => $file,
                'data_keys' => array_keys($data)
            ]);
        } else {
            $this->log()->error('nfe.template.not_found', [
                'template' => $template,
                'file' => $file,
                'data_keys' => array_keys($data)
            ]);

            echo '<div class="notice notice-error"><p>';
            printf(__('Template %s not found.', 'woocommerce-cloudxm-nfe'), esc_html($template));
            echo '</p></div>';
        }
    }
}
