<?php

namespace App\Jobs;

use Filament\Actions\Action;
use App\Models\Transmittal;
use App\Models\User;
use Barryvdh\DomPDF\Facade\Pdf;
use Filament\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage;

class TransmittalPDFExportJob implements ShouldQueue
{
    use Queueable, Dispatchable, InteractsWithQueue, SerializesModels;

    /**
     * Create a new job instance.
     */
    public function __construct(private User $user, private array $ids)
    {}

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $this->user->refresh();

        $transmittals = Transmittal::query()
            ->with(['client', 'branch', 'files.notes', 'files.remarks'])
            ->whereIn('id', $this->ids)
            ->get();

        $pdf = Pdf::loadView('transmittal.export.transmittal-export-pdf', [
            'transmittals' => $transmittals,
        ]);

        $filename = 'transmittal-export-'.$this->user->id.'-'.now()->format('YmdHis').'.pdf';

        Storage::disk('public')->put($filename, $pdf->output());

        Notification::make()
            ->success()
            ->title('Export Completed')
            ->actions([
                Action::make('download_transmittal_export')
                    ->label('Download PDF File')
                    ->url(Storage::url($filename), true)
                    ->markAsRead(),
            ])
            ->sendToDatabase($this->user);
    }
}
