<?php
// 数据库配置
$host = 'localhost';
$user = 'invoice_system';
$pwd = '123456';
$dbname = 'invoice_system';

// 连接数据库
$conn = mysqli_connect($host, $user, $pwd, $dbname);
if (!$conn) {
    die('数据库连接失败：' . mysqli_connect_error());
}
mysqli_set_charset($conn, 'utf8mb4');

// 3. 配置附件上传参数
$uploadDir = './invoice/'; // 根目录下的invoice文件夹
$allowedExts = ['pdf', 'jpg', 'jpeg', 'png']; // 允许的文件格式
$maxFileSize = 10 * 1024 * 1024; // 最大文件大小：10MB/个

// 4. 处理批量附件上传
$attachPaths = [];
if (!empty($_FILES['invoice_attach']['name'][0])) {
    // 创建存储目录（如果不存在）
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    // 遍历上传的文件
    foreach ($_FILES['invoice_attach']['name'] as $key => $fileName) {
        if (empty($fileName)) continue;
        
        // 获取文件信息
        $fileInfo = pathinfo($fileName);
        $fileExt = strtolower($fileInfo['extension']);
        $fileTmp = $_FILES['invoice_attach']['tmp_name'][$key];
        $fileSize = $_FILES['invoice_attach']['size'][$key];

        // 验证文件
        if (!in_array($fileExt, $allowedExts)) {
            die('附件格式错误！仅支持PDF、JPG、PNG格式 <a href="invoice_add.php">返回</a>');
        }
        if ($fileSize > $maxFileSize) {
            die("文件 {$fileName} 过大！最大支持10MB <a href=\"invoice_add.php\">返回</a>");
        }

        // 生成唯一文件名（发票号码_时间戳_序号.后缀）
        $invoiceNo = trim($_POST['invoice_no'] ?? '');
        $uniqueFileName = $invoiceNo . '_' . time() . '_' . ($key+1) . '.' . $fileExt;
        $savePath = $uploadDir . $uniqueFileName;

        // 移动上传文件
        if (move_uploaded_file($fileTmp, $savePath)) {
            $attachPaths[] = $savePath;
        } else {
            die("文件 {$fileName} 上传失败！<a href=\"invoice_add.php\">返回</a>");
        }
    }
}

// 拼接附件路径（用|分隔存储多个附件）
$attachPath = implode('|', $attachPaths);

// 5. 接收并验证表单数据
$invoice_no = trim($_POST['invoice_no'] ?? '');
$amount = trim($_POST['amount'] ?? '');
$invoice_date = trim($_POST['invoice_date'] ?? '');
$supplier = trim($_POST['supplier'] ?? '');
$purchaser = trim($_POST['purchaser'] ?? '');
$remark = trim($_POST['remark'] ?? '');
$status = trim($_POST['status'] ?? '已收票');

// 基础验证
if (empty($invoice_no) || empty($amount) || empty($invoice_date)) {
    die('必填字段不能为空！<a href="invoice_add.php">返回</a>');
}
// 金额格式验证
if (!is_numeric($amount)) {
    die('金额必须为数字！<a href="invoice_add.php">返回</a>');
}

// 6. 插入数据库
$sql = "INSERT INTO invoice_info (invoice_no, amount, invoice_date, supplier, purchaser, remark, status, attach_path) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

// 预编译SQL
$stmt = mysqli_prepare($conn, $sql);
if (!$stmt) {
    die('SQL预编译失败：' . mysqli_error($conn) . '<br>SQL语句：' . $sql);
}

// 绑定参数
$bindResult = mysqli_stmt_bind_param($stmt, 'sdssssss', $invoice_no, $amount, $invoice_date, $supplier, $purchaser, $remark, $status, $attachPath);
if (!$bindResult) {
    die('参数绑定失败：' . mysqli_stmt_error($stmt));
}

// 执行插入
if (mysqli_stmt_execute($stmt)) {
    echo '<!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>录入成功 - 发票管理系统</title>
        <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
        <style>
            body { font-family: "Microsoft Yahei"; background: #f5f7fa; }
            .success-box { width: 500px; margin: 100px auto; background: #fff; padding: 30px; border-radius: 4px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); text-align: center; }
            .success-icon { font-size: 60px; color: #2ecc71; margin-bottom: 20px; }
            .success-box h2 { color: #333; margin-bottom: 20px; }
            .btn { padding: 8px 16px; border: none; border-radius: 4px; color: #fff; text-decoration: none; margin: 0 5px; }
            .btn-blue { background: #3498db; }
            .btn-green { background: #2ecc71; }
        </style>
    </head>
    <body>
        <div class="success-box">
            <div class="success-icon"><i class="fa fa-check-circle"></i></div>
            <h2>发票录入成功！</h2>
            <p>发票号码：'.$invoice_no.' | 金额：¥'.$amount.'</p>
            <div style="margin-top: 30px;">
                <a href="invoice_add.php" class="btn btn-blue">继续录入</a>
                <a href="invoice_list.php" class="btn btn-green">查看发票列表</a>
            </div>
        </div>
    </body>
    </html>';
} else {
    // 捕获唯一键冲突（发票号码重复）
    if (mysqli_errno($conn) == 1062) {
        echo '该发票号码已存在！<a href="invoice_add.php">返回</a>';
    } else {
        echo '录入失败：' . mysqli_stmt_error($stmt) . '<a href="invoice_add.php">返回</a>';
    }
}

// 7. 关闭连接
mysqli_stmt_close($stmt);
mysqli_close($conn);
?>