<?php

namespace App\Mail;

use App\Models\Tag;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Mail;

class TagAddedMail extends Mailable implements ShouldQueue
{
    use Queueable;
    use SerializesModels;

    public $tagId;
    public $locale;

    /**
     * Create a new message instance.
     *
     * @param $tagInfo
     */
    public function __construct($tagId, $locale = null)
    {
        $this->tagId = $tagId;
        $this->locale = $locale ?? App::getLocale();
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        // Set application locale for this email
        app()->setLocale($this->locale);

        $tagInfo = collect((new Tag())->translateTagIdsWithContexts($this->tagId, $this->locale, App::getFallbackLocale()));

        // Handle empty tag info
        $tagInfoData = $tagInfo->first();
        $tagName = $tagInfoData['tag'] ?? 'Unknown Tag';

        return $this
                ->from(timebank_config('mail.system_admin.email'), timebank_config('mail.system_admin.name'))
                ->subject(trans('messages.new_tag_added', [], $this->locale) . ': ' . $tagName)
                ->view('emails.tags.new')
                ->with(['tagInfo' => $tagInfoData ]);

    }
}
