<?php

declare(strict_types=1);
namespace App\Services;
use App\Core\Database;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
use RuntimeException;

final class EmailService
{
    public function __construct(private ?SettingsService $settings=null, private ?PdfService $pdfs=null){$this->settings??=new SettingsService();$this->pdfs??=new PdfService();}
    public function sendInvoice(int $invoiceId,string $recipient,string $recipientName=''): void
    {
        $recipient=trim($recipient); if(!filter_var($recipient,FILTER_VALIDATE_EMAIL)) throw new RuntimeException('The patient does not have a valid email address.');
        $data=$this->pdfs->invoice($invoiceId); $business=$data['business'];
        $subject='Invoice '.$data['invoice_number'].' — '.$business['name'];
        $body=$this->invoiceBody($data,$recipientName);
        $this->send($recipient,$recipientName,$subject,$body,$data['invoice_number'].'.pdf',$this->pdfs->render('invoice',['invoice'=>$data]));
    }
    private function invoiceBody(array $data,string $name): string
    { $greeting=$name!==''?'Dear '.htmlspecialchars($name,ENT_QUOTES,'UTF-8'):'Dear Customer'; $total=number_format((float)$data['total'],2); return '<p>'.$greeting.',</p><p>Please find attached invoice <strong>'.htmlspecialchars((string)$data['invoice_number'],ENT_QUOTES,'UTF-8').'</strong> from '.htmlspecialchars((string)$data['business']['name'],ENT_QUOTES,'UTF-8').'.</p><p><strong>Total: '.htmlspecialchars((string)$data['business']['currency'],ENT_QUOTES,'UTF-8').' '.$total.'</strong></p><p>Thank you.</p>'; }
    private function send(string $to,string $toName,string $subject,string $html,string $filename,string $attachment): void
    {
        $all=$this->settings->get(); $get=static fn(string $k,string $d='')=>(string)($all[$k]['value']??$d);
        $host=$get('mail.smtp.host'); $username=$get('mail.smtp.username'); $password=$get('mail.smtp.password'); $port=(int)$get('mail.smtp.port','587'); $encryption=$get('mail.smtp.encryption','tls'); $from=$get('mail.from.address',$get('business.email')); $fromName=$get('mail.from.name',$get('business.name','Grow Tool Therapies'));
        if($host===''||$from==='') throw new RuntimeException('Email is not configured. Go to Settings → Email and enter SMTP host and sender email.');
        if(!filter_var($from,FILTER_VALIDATE_EMAIL)) throw new RuntimeException('The configured sender email is not valid.');
        $mail=new PHPMailer(true); try{$mail->isSMTP();$mail->Host=$host;$mail->Port=$port;$mail->SMTPAuth=$username!=='';if($mail->SMTPAuth){$mail->Username=$username;$mail->Password=$password;}if($encryption==='ssl')$mail->SMTPSecure=PHPMailer::ENCRYPTION_SMTPS;elseif($encryption==='tls')$mail->SMTPSecure=PHPMailer::ENCRYPTION_STARTTLS;$mail->CharSet='UTF-8';$mail->setFrom($from,$fromName);$mail->addAddress($to,$toName);$mail->isHTML(true);$mail->Subject=$subject;$mail->Body=$html;$mail->AltBody=strip_tags(str_replace(['</p>','<br>'],["\n","\n"],$html));$mail->addStringAttachment($attachment,$filename,'base64','application/pdf');$mail->send();}catch(Exception $e){throw new RuntimeException('Email could not be sent: '.$mail->ErrorInfo);}
    }
}
