<?php

namespace App\Mail;

use App\Helpers\Helper;
use App\Models\Base\Company;
use App\Models\Sales\CustomerInvoice as CustomerForeignTrade;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendCustomerForeignTrade extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * @var CustomerForeignTrade
     */
    public $customer_foreign_trade;

    /**
     * @var custom_message
     */
    public $custom_message;

    /**
     * @var pdf
     */
    private $pdf;

    /**
     * @var file_xml_pac
     */
    private $file_xml_pac;

    private $reply;


    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct(CustomerForeignTrade $customer_foreign_trade,$subject,$custom_message,$pdf,$file_xml_pac, $reply = [])
    {
        $this->customer_foreign_trade = $customer_foreign_trade;
        $this->subject = $subject; //incluido porr default
        $this->custom_message = $custom_message;
        $this->pdf = $pdf;
        $this->file_xml_pac = $file_xml_pac;
        $this->reply = $reply;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        $message = $this->markdown('emails.send_customer_foreign_trade');

        //Valida si se envia el PDF
        if(!empty($this->pdf)){
            $message->attachData($this->pdf,
            str_replace('/','',$this->customer_foreign_trade->name) . '.pdf', [
                    'mime' => 'application/pdf',
                ]);
        }
        //Valida si existe y adjunta el XML
        if(!empty($this->file_xml_pac) && $this->customer_foreign_trade->status != CustomerForeignTrade::DRAFT){
            if(\Storage::exists($this->file_xml_pac)) {
                $message->attach(\Storage::path($this->file_xml_pac), [
                    'as' => str_replace('/','',$this->customer_foreign_trade->name) . '.xml'
                ]);
            }
        }

        if(!empty($this->reply)){
            $message->replyTo($this->reply);
        }

        return $message;
    }
}
