<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Collection;

class GenericMail extends Mailable
{
    use Queueable, SerializesModels;

    protected array $filesData = [];

    public function __construct(string $subjectLine, string $html, iterable $attachments = [])
    {
        $this->subject = $subjectLine;
        $this->html = $html;

        $items = $attachments instanceof Collection ? $attachments->all()
            : (is_array($attachments) ? $attachments : []);

        $this->filesData = array_values(array_map(function ($a) {
            if (is_object($a)) {
                $disk = $a->disk ?? null;
                $path = $a->path ?? null;
                $name = $a->name ?? null;
            } else {
                $disk = $a['disk'] ?? null;
                $path = $a['path'] ?? null;
                $name = $a['name'] ?? null;
            }
            return [
                'disk' => $disk,
                'path' => $path,
                'name' => $name ?? ($path ? basename($path) : null),
            ];
        }, $items));
    }

    public function build()
    {
        $mail = $this->subject($this->subject)
            ->html($this->html);

        foreach ($this->filesData as $att) {
            $disk = $att['disk'] ?? null;
            $path = $att['path'] ?? null;
            $name = $att['name'] ?? ($path ? basename($path) : null);
            if ($disk && $path) {
                $mail->attachFromStorageDisk($disk, $path, $name);
            }
        }

        return $mail;
    }
}
