<?php

namespace App\Models;

use App\Core\Model;

class MailTemplate extends Model
{
    protected static string $table = 'iw_mail_templates';

    /**
     * Find a template by its slug.
     */
    public static function findBySlug(string $slug): ?array
    {
        return static::db()->fetch(
            "SELECT * FROM " . static::$table . " WHERE slug = :slug LIMIT 1",
            ['slug' => $slug]
        );
    }

    /**
     * Render a template by replacing {{placeholders}} with values.
     */
    /**
     * Render a template by replacing {{placeholders}} with values.
     * Automatically injects {{logo_url}} and {{site_name}} if not provided.
     */
    public static function render(string $slug, array $variables = []): ?array
    {
        $template = static::findBySlug($slug);
        if (!$template) {
            return null;
        }

        // Auto-inject logo_header: either <img> with absolute URL or <h1> text fallback
        if (!isset($variables['logo_header'])) {
            $logoUrl  = branding_logo_url('header');
            $siteName = htmlspecialchars($variables['site_name'] ?? setting('site_name', 'ITSWEBER CMS'), ENT_QUOTES, 'UTF-8');

            if ($logoUrl !== null) {
                $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
                $host   = $_SERVER['HTTP_HOST'] ?? 'localhost';
                $absUrl = $scheme . '://' . $host . $logoUrl;
                $variables['logo_header'] = '<img src="' . htmlspecialchars($absUrl, ENT_QUOTES, 'UTF-8')
                    . '" alt="' . $siteName
                    . '" style="max-height:40px;max-width:200px;">';
            } else {
                $variables['logo_header'] = '<span style="color:#ffffff;font-size:20px;font-weight:700;">' . $siteName . '</span>';
            }
        }

        // Keep logo_url for backwards compat (empty string if no logo)
        if (!isset($variables['logo_url'])) {
            $logoUrl = branding_logo_url('header');
            if ($logoUrl !== null) {
                $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
                $host   = $_SERVER['HTTP_HOST'] ?? 'localhost';
                $variables['logo_url'] = $scheme . '://' . $host . $logoUrl;
            } else {
                $variables['logo_url'] = '';
            }
        }

        $subject = $template['subject'];
        $body    = $template['html_body'];

        foreach ($variables as $key => $value) {
            $placeholder = '{{' . $key . '}}';
            $subject = str_replace($placeholder, $value, $subject);
            $body    = str_replace($placeholder, $value, $body);
        }

        return [
            'subject' => $subject,
            'body'    => $body,
        ];
    }
}
