<?php

    namespace App\Mail\Tickets;

    use App\Models\{Departments,Tickets,User};
    use Illuminate\Bus\Queueable;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Illuminate\Mail\Mailable;
    use Illuminate\Mail\Mailables\Address;
    use Illuminate\Mail\Mailables\Content;
    use Illuminate\Mail\Mailables\Envelope;
    use Illuminate\Queue\SerializesModels;

    class Assigned extends Mailable
    {
        use Queueable, SerializesModels;


        /**
         * Create a new message instance.
         */
        public function __construct(protected $ticket)
        {
            $this->ticket = $ticket;
        }

        /**
         * Get the message envelope.
         */
        public function envelope(): Envelope
        {
            $department = Departments::select('department_name', 'department_email')->where('id', '=',
                $this->ticket['department_id'])->first();
            $email_company = config('app.name').': '.$department->department_name;
            return new Envelope(
                from: new Address($department->department_email, $email_company),
                subject: 'Re: Ticket #'.$this->ticket['id'].' has been assigned to an employee.',
            );
        }

        /**
         * Get the message content definition.
         */
        public function content(): Content
        {
            $ticket = Tickets::where('id', '=', $this->ticket['id']);
            $ticket_public_url = config('app.url').'/'.'tickets/public/'.$this->ticket['id'].'/'.$this->ticket['public_hash'];
            
            $name = User::select('name')->selectRaw('name')->where('id', '=', $this->ticket['user_id'])->first();
            $ip_address = app('request')->ip();
            
            $author_name = $name ?: $this->ticket['public_name'];

            $assigned_name = User::select('name')->selectRaw('name')->where('id', '=', $this->ticket['assigned'])->first()->name;
            
            return new Content(
                markdown: 'emails.tickets.assigned',
                with: [
                    'ticketId' => $this->ticket['id'],
                    'ticketPublicUrl' => $ticket_public_url,
                    'authorName' => $author_name ?: 'unknown',
                    'assignedName' => $assigned_name ?: 'unknown',
                    'ticketStatus' => $this->ticket['status'],
                    'ticketPriority' => $this->ticket['priority'],
                    'authorIPaddress' => $ip_address,
                ],
            );
        }

        /**
         * Get the attachments for the message.
         *
         * @return array<int, \Illuminate\Mail\Mailables\Attachment>
         */
        public function attachments(): array
        {
            return [];
        }
    }