<?php
require_once('tcpdf/tcpdf.php');
include 'auth.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo '禁止的请求方式';
    exit;
}

$invoice_number = $_GET['invoice'] ?? '';
$invoice_number = preg_replace('/[^a-zA-Z0-9_-]/', '', $invoice_number);
if (!$invoice_number) {
    http_response_code(400);
    echo '账单编号缺失';
    exit;
}

$meta_file = __DIR__ . '/invoices/meta.json';
$meta = file_exists($meta_file) ? json_decode(file_get_contents($meta_file), true) : [];
if (!isset($meta[$invoice_number])) {
    http_response_code(404);
    echo '账单不存在';
    exit;
}

$input = json_decode(file_get_contents("php://input"), true);
$method = $input['method'] ?? '';
$tid = $input['tid'] ?? '';
$time = $input['time'] ?? '';

if (!$method || !$tid || !$time) {
    http_response_code(422);
    echo '缺少字段';
    exit;
}

$meta[$invoice_number]['status'] = 'paid';
$meta[$invoice_number]['payment_method'] = $method;
$meta[$invoice_number]['transaction_id'] = $tid;
$meta[$invoice_number]['payment_date'] = date('Y-m-d');
$meta[$invoice_number]['transaction_time'] = $time;

file_put_contents($meta_file, json_encode($meta, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));

// 重新生成 PDF
$_POST = $meta[$invoice_number];
$_POST['invoice_number'] = $invoice_number;
ob_start();
include 'generate.php';
ob_end_clean();

echo 'ok';
