<?php

namespace App\Mail;

use App\EmailTemplate;
use App\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

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

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

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

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

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

		$replaceList = [
			'code', 'first_name', 'last_name', 'furigana_first_name', 'furigana_last_name', 'post_code',
			'address1', 'address2', 'address3', 'phone_number', 'email', 'note', 'created_at'
		];
        $replaceFormatList = ['total_price', 'discount_point_amount'];
        $replaceLangList = ['payment_method', 'payment_status', 'status'];

        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->_content = str_replace("{{ site_name }}", config('settings.site_name'), $template->content);
            $this->_content = str_replace("{{ site_url }}", config('app.url'), $this->_content);

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

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

            foreach ($replaceLangList as $rItem) {
                if ($order->{$rItem} != "") {
                    $lblRs = '';
                    $txtVal = $order->{$rItem};
                    if ($rItem == 'payment_method') {
                        $lblRs = ($txtVal == 1 || $txtVal == "1") ? '前払い' : 'クレジットカード';
                    } elseif ($rItem == 'payment_status') {
                        $lblRs = ($txtVal == 1 || $txtVal == "1") ? '支払われた' : '未払い';
                    } else {
                        if ($txtVal == 0 || $txtVal == "0") {
                            $lblRs = '確認を待ちます';
                        } elseif ($txtVal == 1 || $txtVal == "1") {
                            $lblRs = '進行中';
                        } elseif ($txtVal == 2 || $txtVal == "2") {
                            $lblRs = '配送';
                        } elseif ($txtVal == 3 || $txtVal == "3") {
                            $lblRs = '配達済み';
                        } elseif ($txtVal == 4 || $txtVal == "4") {
                            $lblRs = '完了';
                        } elseif ($txtVal == 5 || $txtVal == "5") {
                            $lblRs = '戻ってきた';
                        } else {
                            $lblRs = 'キャンセル';
                        }
                    }
                    $this->_title = str_replace("{{ " . $rItem . " }}", $lblRs, $this->_title);
                    $this->_content = str_replace("{{ " . $rItem . " }}", $lblRs, $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;
    }
}
