<?php

namespace App\Mail\Traits;

use App\EmailTemplate;

/**
 * CMS メールテンプレートの読み込み・変数置換を共通化するトレイト
 */
trait UsesEmailTemplate
{
    protected $_title = '';
    protected $_content = '';
    protected $_attachments = [];

    /**
     * CMS テンプレートを読み込み、変数を置換する
     *
     * @param string $settingSlug Settings テーブルの slug (例: 'u_identity_approved')
     * @param array $variables 置換する変数の連想配列 ['variable_name' => 'value']
     * @return bool テンプレートが見つかったかどうか
     */
    protected function loadTemplate(string $settingSlug, array $variables = []): bool
    {
        $templateId = config("settings.{$settingSlug}");
        if (!$templateId) {
            return false;
        }

        $template = EmailTemplate::where('is_deleted', false)
            ->where('is_activated', true)
            ->where('id', $templateId)
            ->first();

        if (!$template || !$template->title || !$template->content) {
            return false;
        }

        // site_name と site_url は常に置換
        $variables['site_name'] = $variables['site_name'] ?? config('settings.site_name', 'KIREI');
        $variables['site_url'] = $variables['site_url'] ?? config('app.url');

        $this->_title = $template->title;
        $this->_content = $template->content;

        foreach ($variables as $key => $value) {
            if (!is_scalar($value) || $value === null || $value === '') {
                continue;
            }
            $this->_title = str_replace("{{ {$key} }}", $value, $this->_title);
            $this->_content = str_replace("{{ {$key} }}", $value, $this->_content);
        }

        // 添付ファイル
        if ($template->attachments) {
            foreach ($template->attachments as $attachment) {
                $filePath = public_path('uploads/files/' . $attachment->file_name);
                if (!file_exists($filePath)) continue;
                $this->_attachments[] = [
                    'name' => $attachment->title,
                    'file' => $filePath,
                    'mime' => $attachment->file_type,
                ];
            }
        }

        return true;
    }

    /**
     * テンプレートを使ってメールを組み立てる
     */
    protected function buildFromTemplate()
    {
        if ($this->_title === '' || $this->_content === '') {
            \Illuminate\Support\Facades\Log::warning('Email template not found or empty, skipping email', [
                'mailable' => static::class,
            ]);

            // ShouldQueueのMailableはbuild()時にキャンセルできないため、
            // 例外を投げてジョブを失敗させる（キューの再試行で自動復旧可能）
            throw new \RuntimeException("Email template not configured for " . static::class);
        }

        $this->from(config('mail.from.address'), config('mail.from.name'))
            ->replyTo(config('mail.reply_to.address') ?: config('mail.from.address'), config('mail.reply_to.name') ?: config('mail.from.name'))
            ->subject($this->_title)
            ->view('emails.system')
            ->with(['content' => $this->_content]);

        foreach ($this->_attachments as $attachment) {
            $this->attach($attachment['file'], ['as' => $attachment['name'], 'mime' => $attachment['mime']]);
        }

        return $this;
    }
}
