<?php
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$invoice_number = $_GET['invoice'] ?? '';
$invoice_number = preg_replace('/[^a-zA-Z0-9_-]/', '', $invoice_number);

$meta_file = __DIR__ . '/invoices/meta.json';
$meta = file_exists($meta_file) ? json_decode(file_get_contents($meta_file), true) : [];
if (!isset($meta[$invoice_number])) die("账单不存在");

$data = $meta[$invoice_number];
$to = $data['email'];
$buyer_name = $data['buyer_name'];
$amount = $data['amount'];
$payment_date = $data['payment_date'];
$pdf_path = __DIR__ . "/invoices/Invoice-$invoice_number.pdf";

$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host = 'smtp.qiye.aliyun.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'noreply@digac.icu';
    $mail->Password = 'ng.+057720';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;
    $mail->CharSet = 'UTF-8';

    $mail->setFrom('noreply@digac.icu', 'Doudou De Car!!!');
    $mail->addAddress($to, $buyer_name);
    $mail->addAttachment($pdf_path);

    $mail->isHTML(true);
    $mail->Subject = "⚠️ 账号删除提醒通知";

    $mail->Body = "
        <div style='font-family:微软雅黑,Helvetica,sans-serif; font-size:15px; color:#333;'>
        <h2 style='background-color: #d32f2f; color: white; padding: 10px 15px;'>账号删除提醒通知</h2>
        <p><strong>{$buyer_name} 您好：</strong></p>
        <p>您的账单 <strong>#{$invoice_number}</strong> 截止日期为 <strong>{$payment_date}</strong>，金额为 ¥{$amount}。</p>
        <p style='color:red;'>⚠️ 若截止日期已过仍未完成续费，系统将在 24 小时内自动删除您的账号。</p>
        <p>如需继续使用服务，请立即续费。</p>
        <p><a href='https://reg.023021.xyz' target='_blank' style='color:#1976d2;'>点击获取邀请码或重新注册</a></p>
        <p>如有疑问请及时联系我们。</p>
        <p>--<br>
        <strong>Doudou De Car!!!账单管理系统</strong><br>
        <small>系统自动发送，请勿回复</small></p>
        </div>
    ";

    $mail->send();
    http_response_code(200);
    echo 'ok';
} catch (Exception $e) {
    http_response_code(500);
    echo "邮件发送失败：{$mail->ErrorInfo}";
}
