<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class ExportNotification extends Mailable
{
    use Queueable, SerializesModels;

    public $emailData;
    private $filePath;
    private $fileName;

    /**
     * Create a new message instance.
     */
    public function __construct($emailData, $filePath, $fileName)
    {
        $this->emailData = $emailData;
        $this->filePath = $filePath;
        $this->fileName = $fileName;
    }

    /**
     * Build the message.
     */
    public function build()
    {
        try {
            $email = $this->subject($this->emailData['subject'])
                        ->view('emails.export-notification')
                        ->with('data', $this->emailData);

            if (file_exists($this->filePath)) {
                $email->attach($this->filePath, [
                    'as' => $this->fileName,
                    'mime' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                ]);

                Log::info('Email attachment added', [
                    'file_path' => $this->filePath,
                    'file_name' => $this->fileName,
                    'file_size' => filesize($this->filePath)
                ]);
            } else {
                Log::warning('Export file not found for email attachment', [
                    'file_path' => $this->filePath
                ]);
            }

            return $email;

        } catch (\Exception $e) {
            Log::error('Error building export notification email', [
                'error' => $e->getMessage(),
                'file_path' => $this->filePath,
                'file_name' => $this->fileName
            ]);
            throw $e;
        }
    }
}
