<?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\PurchaseOrder;
use Swift_Mailer;
use Swift_SmtpTransport;

class PurchaseOrderEmail extends Mailable
{
    use Queueable, SerializesModels;
    public $user;
    public $subject;
    public $body;
    public $order;
    public $pdf;
    public $contact;
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($user, $subject, $body, PurchaseOrder $order)
    {
        $request = RequestCreator::createWithParameters([
          'format' => 'pdf',
          'attention' => $order->supplier->contact
        ]);

        $this->pdf = app('App\Http\Controllers\Resources\PurchaseOrderDetailController')->export($request, $order->id);
        $this->user = $user;
        $this->subject = $subject;
        $this->body = $body;
        $this->order = $order;
        $this->contact = $order->supplier->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->order->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);
        });

    }
}
