<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class ContactFormCopyMailable extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;

    public $contact;
    public $locale;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($contact)
    {
        $this->contact = $contact;

        // Determine locale from profile lang_preference or browser locale
        if (!empty($contact['profile_lang_preference'])) {
            $this->locale = $contact['profile_lang_preference'];
        } elseif (!empty($contact['browser_locale'])) {
            $this->locale = $contact['browser_locale'];
        } else {
            $this->locale = config('app.fallback_locale');
        }

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

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

        $context = $this->contact['context'] ?? 'contact';

        $subject = match($context) {
            'report-issue' => __('Copy: Issue Report') . ' - ' . ($this->contact['subject'] ?? __('No subject')),
            'report-error' => __('Copy: Error Report'),
            'delete-profile' => __('Copy: Profile Deletion Request'),
            default => __('Copy: Contact Form') . ' - ' . ($this->contact['subject'] ?? __('Your Message')),
        };

        return $this->from(timebank_config('mail.support.email'), timebank_config('mail.support.name'))
            ->subject($subject)
            ->view('emails.contact-form.copy')
            ->with([
                'contact' => $this->contact,
            ]);
    }
}
