<?php
require 'vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$errorList = [];
$data = json_decode(file_get_contents('output/email_list.json'), true);

foreach ($data as $entry) {
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host = 'mail.dan.digitalagency.ro';
        $mail->SMTPAuth = true;
        $mail->Username = 'test_interpneumo@dan.digitalagency.ro';
        $mail->Password = 'Parola123!$!';
        $mail->SMTPSecure = 'ssl';
        $mail->Port = 465;

        $mail->setFrom('test_interpneumo@dan.digitalagency.ro', 'Inter-Pneumo 2025');
        $mail->addAddress($entry['email'], $entry['name']);
        $mail->addAttachment($entry['pdf']);

        $mail->isHTML(true);
        $mail->Subject = 'Diploma de participare - INTER-PNEUMO 2025';
        $html = file_get_contents(__DIR__ . '/email_template.html');
        $html = str_replace('{{name}}', htmlspecialchars($entry['name']), $html);
        $mail->Body = $html;

        $mail->send();
    } catch (Exception $e) {
        $errorList[] = [
            'email' => $entry['email'],
            'name' => $entry['name'],
            'error' => $mail->ErrorInfo
        ];
    }
}

header('Content-Type: application/json');
echo json_encode($errorList);
