<?php

namespace Yajny\MailYj\Mails;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class BaseMail extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels, InteractsWithQueue;

    public $lang;
    public $theme = 'default';
    public $header_image;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct()
    {
        $lang = config('website.cnf_lang');
        if (isset($this->lang)) {
            $lang = $this->lang;
        } else {
            switch (config('app.purpose')) {
                case  'admin' :
                    $lang = config('website.cnf_lang');
                    break;
                case 'frontend' :
                    $lang = isset($this->user) ? $this->user->user_lang : config('website.cnf_lang');
                    break;
                default :
                    $lang = $lang = app('translator')->getLocale();
                    break;

            }
        }
        $this->setLang($lang);

        if ($lang == 'ar')
            $this->theme = 'default-ar';

        $template = $this->get_real_class(get_called_class());
        $mailConfig = json_decode(file_get_contents(app_path() . '/../config/mailTemplate.json'), true);

        if (isset($mailConfig[$template])) {
            $templateConfig = $mailConfig[$template];
            $templateConfig['subject'] = json_decode($templateConfig['subject'], true);
            $this->subject = $templateConfig['subject'][$this->lang];
            $this->header_image = ($templateConfig['header_image_' . $this->lang]) ?? '';
            $this->from($templateConfig['from_email'], $templateConfig['from_name']);
            if (trim($templateConfig['reply_to']) != '' && empty($this->replyTo))
                $this->replyTo($templateConfig['reply_to']);
            if (trim($templateConfig['cc_to']) != '')
                $this->cc($templateConfig['cc_to']);
        }
    }

    public function setLang($lang)
    {
        $this->lang = $lang;
        app('translator')->setLocale($lang);
        $this->locale = $lang;
        $this->locale($lang);
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        if (isset($this->template_name))
            return $this->markdown('MailYj::' . $this->lang . '.' . $this->template_name);
        return $this;
    }

    function get_real_class($classname)
    {
        if (preg_match('@\\\\([\w]+)$@', $classname, $matches)) {
            $classname = $matches[1];
        }
        return $classname;
    }
}
