<?php

namespace App\Mail;

use App\Models\MachineSession;
use App\Models\SessionSegment;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;

class SessionReportMail extends Mailable
{
    use Queueable, SerializesModels;

    public function __construct(
        public MachineSession $session,
        public float $oee,
        public array $segmentOees,
        public array $timeline,
    ) {}

    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Session Report #' . $this->session->id . ' — ' . $this->session->product_name,
        );
    }

    public function content(): Content
    {
        return new Content(
            view: 'emails.session-report',
        );
    }

    public function attachments(): array
    {
        $pdf = Pdf::loadView('admin.sessions.pdf', [
            'session'     => $this->session,
            'oee'         => $this->oee,
            'segmentOees' => $this->segmentOees,
            'timeline'    => $this->timeline,
        ])->setPaper('a4', 'portrait');

        $filename = 'shift-report-' . $this->session->id . '-' . now()->format('Ymd') . '.pdf';

        return [
            Attachment::fromData(fn () => $pdf->output(), $filename)
                ->withMime('application/pdf'),
        ];
    }
}
