<?php
namespace App;

// use PHPMailer\PHPMailer\PHPMailer;
// use PHPMailer\PHPMailer\Exception;
use SendGrid;
use SendGrid\Mail\Mail;
use SendGrid\Mail\Attachment;

class EmailService {
    private $config;

    public function __construct($config) {
        $this->config = $config;
    }

    public function sendInvoice($to, $pdfPath, $invoiceNumber) {
        $emailSent = false;
        
        try {
            $from = $this->config['email']['from_email'];
            $fromName = $this->config['email']['from_name'];
            
            // Email headers
            $headers = "From: $fromName <$from>\r\n";
            $headers .= "Reply-To: $from\r\n";
            $headers .= "MIME-Version: 1.0\r\n";
            $headers .= "Content-Type: multipart/mixed; boundary=\"mixed-".md5(time())."\"\r\n\r\n";
            
            // Email body with attachment
            $message = "--mixed-".md5(time())."\r\n";
            $message .= "Content-Type: text/html; charset=\"UTF-8\"\r\n";
            $message .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
            $message .= "Please find attached invoice #$invoiceNumber\r\n";
            
            // Add PDF attachment
            $attachment = chunk_split(base64_encode(file_get_contents($pdfPath)));
            $message .= "\r\n--mixed-".md5(time())."\r\n";
            $message .= "Content-Type: application/pdf; name=\"invoice_$invoiceNumber.pdf\"\r\n";
            $message .= "Content-Disposition: attachment\r\n";
            $message .= "Content-Transfer-Encoding: base64\r\n\r\n";
            $message .= $attachment;
            
            // Send email
            $emailSent = mail($to, "Invoice #$invoiceNumber", $message, $headers);

        } catch (Exception $e) {
            $error = $e->getMessage();
        }

        // Log message
        $logMessage = sprintf(
            "[%s] Generated PDF for Invoice #%s. Path: %s, Recipient: %s, Email Sent: %s%s",
            date('Y-m-d H:i:s'),
            $invoiceNumber,
            $pdfPath,
            $to,
            $emailSent ? 'Yes' : 'No',
            isset($error) ? ", Error: $error" : ''
        );

        error_log($logMessage . PHP_EOL, 3, 'output/pdf_generation.log');
        
        return $emailSent;
    }
}
