<?php

namespace App\Mail;

use Cog\Laravel\Love\ReactionType\Models\ReactionType;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class ReactionCreatedMail extends Mailable implements ShouldQueue  // ShouldQueue here creates the class as a background job
{
    use Queueable;
    use SerializesModels;

    protected $reaction;
    protected $reactionType;
    protected $reactionCount;
    protected $buttonUrl;
    public $locale;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($reaction)
    {
        $this->reaction = $reaction;
        $this->reactionType = ReactionType::fromName($reaction->getType()->name);
        $this->reactionCount = $reaction->getReactant()->getReactionCounterOfType($this->reactionType)->count;

        $recipient = $reaction->getReactant()->getReactable();

        // Support lang_preference for User, Organization, Bank, and Admin models
        $this->locale = $recipient->lang_preference ?? config('app.fallback_locale');

        // Ensure locale is not empty
        if (empty($this->locale)) {
            $this->locale = config('app.fallback_locale');
        }

        $reacter = $reaction->getReacter()->getReacterable();
        $reacterType = strtolower(class_basename($reacter));
        $translatedType = __($reacterType, [], $this->locale);

        if ($reacter) {
            $this->buttonUrl = LaravelLocalization::localizeURL(route('profile.show_by_type_and_id', ['type' => $translatedType, 'id' => $reacter->id]), $this->locale);
        } else {
            Log::warning('ReactionCreatedMail: Unknown reacter type');
        }

    }

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

        return $this
            ->from(timebank_config('mail.support.email'), timebank_config('mail.support.name'))
            ->subject(trans('messages.Your_profile_has_received_a_'. $this->reaction->getType()->name, [], $this->locale))
            ->view('emails.reactions.star-received')
            ->with([
                'reactionType' => $this->reaction->getType(),
                'reactionCount' => $this->reactionCount,
                'from' => $this->reaction->getReacter()->getReacterable(),
                'to' => $this->reaction->getReactant()->getReactable(),
                'buttonUrl' => $this->buttonUrl,
            ]);
    }
}
