<?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'];
$status = $data['status'];
$amount = $data['amount'];
$invoice_date = $data['invoice_date'];
$payment_date = $data['payment_date'];
$payment_method = $data['payment_method'] ?? '';
$transaction_id = $data['transaction_id'] ?? '';
$note = $data['note'] ?? '';
$server_location = $data['server_location'] ?? '';
$start_date = $data['start_date'] ?? '';
$end_date = $data['end_date'] ?? '';
$period_text = ($start_date && $end_date) ? "（{$start_date} 至 {$end_date}）" : '';
$project_text = htmlspecialchars($server_location . $period_text, ENT_QUOTES, 'UTF-8');
$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);
    $statusTextSubject = ($status === 'paid') ? '已支付' : '未支付';
    $mail->Subject = "Doudou De Car!!!账单通知($statusTextSubject)：#$invoice_number";

    $statusColor = ($status === 'paid') ? '#4CAF50' : '#f44336';
    $statusTextBody = ($status === 'paid') ? '✅ 已付款' : '❌ 未付款';

    $mail->Body = "
        <div style='font-family:微软雅黑,Helvetica,sans-serif; font-size:15px; line-height:1.6; color:#333;'>
        <h2 style='background-color: $statusColor; color: white; padding: 10px 15px;'>
        Doudou De Car!!!账单通知$statusTextBody：#$invoice_number
        </h2>
        <p><strong>尊敬的 {$buyer_name}，您好：</strong></p>" .
        ($status === 'paid' ? "<p style='color: green; font-weight: bold;'>我们已经收到了您的付款。</p>" : "") . "
        <p>以下是您本次账单的详细信息：</p>
        <ul>
        <li><strong>账单号：</strong> #$invoice_number</li>
        <li><strong>账单日期：</strong> $invoice_date</li>" .
        ($status !== 'paid' ? "<li><strong>截止日期：</strong> $payment_date</li>" : "") . "
        <li><strong>状态：</strong> $statusTextBody</li>
        <li><strong>金额：</strong> ¥$amount</li>
        <li><strong>项目：</strong> $project_text</li>" .
        ($status === 'paid' ? "<li><strong>支付方式：</strong> $payment_method</li>
        <li><strong>交易单号：</strong> $transaction_id</li>" : "") .
        "<li><strong>备注：</strong> 📣 请在面板完成续费或重新订阅！请在截止日期前完成续费，超期未续费系统将删除您的账号，请重新注册！<a href='https://reg.023021.xyz' target='_blank' style='color:#1976d2;'>获取邀请码</a></li>"  .
        /*
        ($status !== 'paid' ? "<li>📣 请在面板完成续费或重新订阅！请在截止日期前完成续费，超期未续费系统将删除您的账号，请重新注册！<a href='https://reg.023021.xyz' target='_blank''>获取邀请码</a></li>" : "") . "
        */
        "</ul>
        <p style='color:#d32f2f;'><strong>⚠️ 所有非中转节点无法保证服务的有效性。</strong></p>
        <p>📎 请查收附件中的 PDF 账单，如有疑问欢迎联系。</p>
        <p>--<br>
        <a href='https://panel.reality.pp.ua' target='_blank'>
        <strong>Doudou De Car!!!账单管理系统</strong>
        </a><br>
        <small>系统自动发送，请勿回复</small></p>
    </div>";



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