<?php

namespace App\Mail;

use App\EmailTemplate;
use App\Laravue\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

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

    private $_title;
    private $_content;
    private $_attachments;

    /**
     * Create a new message instance.
     *
     * @param $user
     * @return void
     */
    public function __construct(User $user)
    {
        $this->onConnection(config('queue.default'));
        $this->onQueue(config('queue.connections.redis.queue'));

        $this->_title = "";
        $this->_content = "";
        $this->_attachments = [];

        $emailItemId = config('settings.u_forgot_password');
        $template = EmailTemplate::where('is_deleted', false)
            ->where('is_activated', true)
            ->where('id', $emailItemId)
            ->first();

        $replaceList = ['username', 'full_name', 'first_name', 'last_name', 'furigana_name', 'email'];
		$forgotCode = $user->reset_password_code;
		$forgotLink = url('/forgot-password/' . $user->reset_password_code);

        if ($template && $template->id != null && $template->title != '' && $template->content != '') {
            $this->_title = str_replace("{{ site_name }}", config('settings.site_name'), $template->title);
            $this->_title = str_replace("{{ site_url }}", config('app.url'), $this->_title);
			$this->_title = str_replace("{{ code }}", $forgotCode, $this->_title);
			$this->_title = str_replace("{{code}}", $forgotCode, $this->_title);
			$this->_title = str_replace("{{ link }}", $forgotLink, $this->_title);
			$this->_title = str_replace("{{link}}", $forgotLink, $this->_title);
			
            $this->_content = str_replace("{{ site_name }}", config('settings.site_name'), $template->content);
            $this->_content = str_replace("{{ site_url }}", config('app.url'), $this->_content);
			
            $this->_content = str_replace("{{%20link }}", "{{ link }}", $this->_content);
            $this->_content = str_replace("{{ %20link }}", "{{ link }}", $this->_content);
            $this->_content = str_replace("{{%20link}}", "{{ link }}", $this->_content);
            $this->_content = str_replace("{{%20link%20}}", "{{ link }}", $this->_content);
            $this->_content = str_replace("{{ link%20}}", "{{ link }}", $this->_content);
			
			$this->_content = str_replace("{{%20code }}", "{{ code }}", $this->_content);
			$this->_content = str_replace("{{ %20code }}", "{{ code }}", $this->_content);
			$this->_content = str_replace("{{%20code}}", "{{ code }}", $this->_content);
			$this->_content = str_replace("{{%20code%20}}", "{{ code }}", $this->_content);
			$this->_content = str_replace("{{ code%20}}", "{{ code }}", $this->_content);
			
			$this->_content = str_replace('href="/{{ link }}"', 'href="{{ link }}"', $this->_content);
			$this->_content = str_replace('href="/{{ code }}"', 'href="{{ code }}"', $this->_content);
			
            $this->_content = str_replace("{{ code }}", $forgotCode, $this->_content);
            $this->_content = str_replace("{{code}}", $forgotCode, $this->_content);
            $this->_content = str_replace("{{ link }}", $forgotLink, $this->_content);
            $this->_content = str_replace("{{link}}", $forgotLink, $this->_content);

            foreach ($replaceList as $rItem) {
                if ($user->{$rItem} != "") {
                    $this->_title = str_replace("{{ " . $rItem . " }}", $user->{$rItem}, $this->_title);
                    $this->_content = str_replace("{{ " . $rItem . " }}", $user->{$rItem}, $this->_content);
                }
            }

            if ($template->attachments != null) {
                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,
                    ];
                }
            }
        }
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        if ($this->_title == "" || $this->_content == "") return null;

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

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

        return $this;
    }
}
