<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Container\Container;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use Unlu\Laravel\Api\RequestCreator;
use App\Quotation;
use Swift_Mailer;
use Swift_SmtpTransport;

class QuotationEmail extends Mailable
{
    use Queueable, SerializesModels;
    public $user;
    public $subject;
    public $body;
    public $quotation;
    public $pdf;
    public $contact;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($user, $subject, $body, Quotation $quotation)
    {
        $request = RequestCreator::createWithParameters([
          'format' => 'pdf',
          'attention' => $quotation->customer->contact,
        ]);

        $this->pdf = app('App\Http\Controllers\Resources\QuotationDetailController')->export($request, $quotation->id);
        $this->user = $user;
        $this->subject = $subject;
        $this->body = $body;
        $this->quotation = $quotation;
        $this->contact = $quotation->customer->contact;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->from($this->user->getMailUser(), $this->user->name)
                    ->view('reports.email-template')
                    ->subject($this->subject)
                    ->attachData($this->pdf, $this->quotation->folio . '.pdf', [
                        'mime' => 'application/pdf',
                    ]);
    }

    /**
     * Override Mailable functionality to support per-user mail settings
     *
     * @param  \Illuminate\Contracts\Mail\Mailer  $mailer
     * @return void
     */
    public function send(Mailer $mailer)
    {
        $transport = new Swift_SmtpTransport(\Config::get('mail.host'), \Config::get('mail.port'), \Config::get('mail.encryption'));
        $transport->setUsername($this->user->getMailUser());//new method I added on User Model
        $transport->setPassword($this->user->getMailPassword());//new method I added on User Model
        $mailer->setSwiftMailer(new Swift_Mailer($transport));

        Container::getInstance()->call([$this, 'build']);
        $mailer->send($this->buildView(), $this->buildViewData(), function ($message) {
            $this->buildFrom($message)
                 ->buildRecipients($message)
                 ->buildSubject($message)
                 ->buildAttachments($message)
                 ->runCallbacks($message);
        });

    }
}
