<?php
// app/mail/templates/loader.php

/**
 * Static map: do NOT use $domain here (no ctx available yet)
 */
function mailTemplateMap(): array
{
    return [
        'quary' => [
            'file'  => __DIR__ . '/query-template.php',
        ],
        'thanks' => [
            'file'  => __DIR__ . '/thanks-template.php',
        ],
        'approve' => [
            'file'  => __DIR__ . '/approved-template.php',
        ],
        'decline' => [
            'file'  => __DIR__ . '/declined-template.php',
        ],
    ];
}

/**
 * Load a single template by key.
 */
function loadMailTemplate(string $key, array $ctx): array
{
    $map = mailTemplateMap();

    if (!isset($map[$key])) {
        throw new RuntimeException("Unknown mail template key: {$key}");
    }

    $file  = $map[$key]['file'];
    $label = $map[$key]['label'];

    // Make $ctx visible inside template file
    $template = require $file;

    if (!is_array($template)) {
        throw new RuntimeException("Template file {$file} did not return array");
    }

    // attach meta
    $template['key']   = $key;
    $template['label'] = $template['label'] ?? $label;

    return $template;
}

/**
 * Build index for dropdown (dynamic domain support)
 */
function getMailTemplatesIndex(array $ctx): array
{
    $map     = mailTemplateMap();
    $index   = [];
    $domain  = $ctx['domain'] ?? '';

    foreach ($map as $key => $meta) {

        $label = $meta['label'];

        if ($domain) {
            if ($key === 'quary') {
                $label = "{$domain} Query Response";
            }
            if ($key === 'thanks') {
                $label = "{$domain} Thanks Reaching";
            }
            if ($key === 'approve') {
                $label = "{$domain} Approved Temp.";
            }
            if ($key === 'decline') {
                $label = "{$domain} Declined Temp.";
            }
        }

        $index[] = [
            'key'   => $key,
            'label' => $label,
        ];
    }

    return $index;
}

