<?php include 'auth.php'; ?>
<?php
require_once('tcpdf/tcpdf.php');
ob_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

$invoice_number_raw = $_POST['invoice_number'] ?? $_GET['invoice_number'] ?? '';
if (!$invoice_number_raw) die("缺少账单号");

$invoice_number = preg_replace('/[^a-zA-Z0-9_-]/', '', $invoice_number_raw);
$meta_file = __DIR__ . '/invoices/meta.json';
$meta = file_exists($meta_file) ? json_decode(file_get_contents($meta_file), true) : [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $meta[$invoice_number] = [
        'invoice_date' => $_POST['invoice_date'],
        'buyer_name' => $_POST['buyer_name'],
        'email' => $_POST['email'],
        'item_desc' => $_POST['item_desc'],
        'server_location' => $_POST['server_location'],
        'start_date' => $_POST['start_date'],
        'end_date' => $_POST['end_date'],
        'amount' => floatval($_POST['amount']),
        'discount' => floatval($_POST['discount']),
        'status' => $_POST['status'],
        'payment_method' => $_POST['payment_method'] ?? '',
        'transaction_id' => $_POST['transaction_id'] ?? '',
        'transaction_time' => $_POST['transaction_time'] ?? '',
        'payment_date' => $_POST['payment_date'],
        'note' => trim($_POST['note'] ?? '请在面板完成续费或重新订阅！请在截止日期前完成续费，超期未续费系统将删除您的账号，请重新注册！')
    ];
    file_put_contents($meta_file, json_encode($meta, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

if (!isset($meta[$invoice_number])) die("账单不存在！");
extract($meta[$invoice_number]);

$billing_period = "$start_date 至 $end_date";
$discount_amount = round(($amount / (1 - ($discount / 100)) - $amount), 2);
$original_price = ($discount > 0) ? round($amount / (1 - $discount / 100), 2) : $amount;

$pdf = new TCPDF();
$pdf->AddPage();
$pdf->SetFont('alibabapuhuiti355', '', 10);

// 页眉：logo + 地址
$logoPath = __DIR__ . '/invoices/logo.png';
if (file_exists($logoPath)) {
    $pdf->Image($logoPath, 10, 15, 60);
}
$pdf->SetXY(150, 15);
$pdf->MultiCell(50, 5, "2413 Illinois Avenue\nValley View, Oregon, 97415\nUS", 0, 'R');

// 状态条
$pdf->Ln(30);
$statusColor = ($status === 'paid') ? [76, 175, 80] : [244, 67, 54];
$statusText = ($status === 'paid') ? '已付款' : '未付款';
$pdf->SetFillColor(...$statusColor);
$pdf->SetTextColor(255, 255, 255);
$pdf->SetFont('', 'B', 12);
$pdf->Cell(140, 12, "账单 #$invoice_number", 0, 0, 'L', true);
$pdf->Cell(50, 12, $statusText, 0, 1, 'R', true);
$pdf->SetTextColor(0, 0, 0);
$pdf->Ln(5);

// 账号信息
$pdf->SetFont('', '', 10);
$infoX = $pdf->GetX();
$infoY = $pdf->GetY();
$cellWidth = 110;

$pdf->SetXY($infoX, $infoY);
$pdf->MultiCell($cellWidth, 6, "账号：$buyer_name\n邮箱：$email\n账单日期：$invoice_date" . ($status !== 'paid' ? "\n截止日期：$payment_date" : ""), 0, 'L');

//$qrcodePath = __DIR__ . '/invoices/qrcode.png';
//if ($status !== 'paid' && file_exists($qrcodePath)) {
//    $pdf->Image($qrcodePath, $infoX + $cellWidth + 57, $infoY - 2, 22, 22);
//}

// 服务明细表格
$pdf->Ln(6);
$pdf->SetFont('', 'B', 11);
$pdf->Cell(0, 6, "账单明细", 0, 1);

$html = <<<EOD
<table border="1" cellpadding="5" cellspacing="0">
<tr bgcolor="#f0f0f0">
  <th width="70%">描述</th>
  <th width="30%" align="right">金额</th>
</tr>
EOD;

$period = (!empty($start_date) && !empty($end_date)) ? "（" . $start_date . " 至 " . $end_date . "）" : "";
$project_full = "项目：" . $server_location . $period;
$detailText = htmlspecialchars($item_desc, ENT_QUOTES, 'UTF-8') . "<br>" . htmlspecialchars($project_full, ENT_QUOTES, 'UTF-8');
if (!empty($note)) $detailText .= "<br>备注：" . htmlspecialchars($note, ENT_QUOTES, 'UTF-8');

if ($discount > 0) {
    $html .= "
<tr>
  <td>$detailText</td>
  <td align='right'>¥{$original_price}</td>
</tr>
<tr>
  <td>折扣（{$discount}%）</td>
  <td align='right'>-¥{$discount_amount}</td>
</tr>";
} else {
    $html .= "
<tr>
  <td>$detailText</td>
  <td align='right'>¥{$amount}</td>
</tr>";
}

$html .= "
<tr>
  <td align='right'>小计</td>
  <td align='right'>¥" . ($discount > 0 ? $original_price : $amount) . "</td>
</tr>
<tr>
  <td align='right'>账户余额</td>
  <td align='right'>¥0.00</td>
</tr>";

$bg = ($status === 'paid') ? '#4CAF50' : '#f44336';
$html .= "
<tr bgcolor='$bg'>
  <td align='right'><b style='color:white'>合计</b></td>
  <td align='right'><b style='color:white'>¥$amount</b></td>
</tr>
</table>";

$pdf->writeHTML($html, true, false, false, false, '');

// 交易信息
$pdf->Ln(6);
$pdf->SetFont('', 'B', 14);
$pdf->Cell(0, 8, "交易", 0, 1, 'L');
$pdf->SetFont('', '', 10);

$pdf->writeHTML("
<table border='1' cellpadding='5' cellspacing='0'>
<tr bgcolor='#f0f0f0'>
  <th>交易日期</th>
  <th>支付方式</th>
  <th>交易单号</th>
  <th align='right'>金额</th>
</tr>" .
($status === 'paid' ?
"<tr>
  <td>$payment_date</td>
  <td>$payment_method</td>
  <td>$transaction_id</td>
  <td align='right'>¥$amount</td>
</tr>" .
($transaction_time ? "<tr><td colspan='4'><b>交易时间：</b>$transaction_time</td></tr>" : "") :
"<tr><td colspan='4' align='center'>找不到任何与此账单有关的交易记录</td></tr>
<tr><td colspan='3' align='right'>未缴金额</td><td align='right'>¥$amount</td></tr>"
) . "</table>", true, false, false, false, '');

ob_clean();
$pdf_path = __DIR__ . "/invoices/Invoice-$invoice_number.pdf";
$pdf->Output($pdf_path, 'F');

// 页面展示
echo <<<HTML
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
    <script src="assets/js/sweetalert2.all.min.js"></script>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark mb-4">
  <div class="container-fluid">
    <a class="navbar-brand" href="index.php">Doudou De Car!!!账单管理系统</a>
    <div class="collapse navbar-collapse">
      <ul class="navbar-nav me-auto">
        <li class="nav-item"><a class="nav-link" href="index.php">➕ 创建账单</a></li>
        <li class="nav-item"><a class="nav-link" href="bill_manager.php">📂 账单管理</a></li>
        <li class="nav-item"><a class="nav-link" href="users.php">👥 用户管理</a></li>
      </ul>
      <ul class="navbar-nav ms-auto">
        <li class="nav-item"><a class="nav-link text-danger" href="logout.php">🚪 退出登录</a></li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <div class="alert alert-success text-center">✅ 账单已生成：Invoice-$invoice_number.pdf</div>
  <div class="text-center mb-3">
    <button onclick="sendMail('$invoice_number')" class="btn btn-primary">📧 发送账单邮件</button>
  </div>
  <div class="ratio ratio-4x3 border shadow">
    <iframe src="invoices/Invoice-$invoice_number.pdf" frameborder="0"></iframe>
  </div>
</div>
<script>
function sendMail(id) {
  fetch('send_mail.php?invoice=' + id)
    .then(() => {
      Swal.fire({
        icon: 'success',
        title: '发送成功！',
        text: '账单邮件已发送。',
        timer: 2000,
        showConfirmButton: false
      });
    })
    .catch(() => {
      Swal.fire('错误', '发送失败，请检查服务器配置', 'error');
    });
}
</script>
HTML;
