<?php

namespace App\Mail;

use App\Models\EmailTemplate;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

/**
 * DynamicEmail Mailable
 * 
 * A flexible email class that renders content from database templates.
 * Supports both HTML and text content with variable substitution.
 * 
 * @package App\Mail
 */
class DynamicEmail extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * The email template instance.
     */
    public EmailTemplate $template;

    /**
     * The data for variable substitution.
     */
    public array $data;

    /**
     * The rendered email content.
     */
    public array $rendered;

    /**
     * Create a new message instance.
     */
    public function __construct(EmailTemplate $template, array $data = [])
    {
        $this->template = $template;
        $this->data = $data;
        $this->rendered = $template->render($data);
    }

    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: $this->rendered['subject'],
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            view: 'emails.dynamic',
            with: [
                'template' => $this->template,
                'data' => $this->data,
                'rendered' => $this->rendered,
            ],
        );
    }

    /**
     * Get the attachments for the message.
     *
     * @return array<int, \Illuminate\Mail\Mailables\Attachment>
     */
    public function attachments(): array
    {
        return [];
    }
}
