<?php
// 表单提交处理
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_invoice'])) {
    $invoice_no = trim($_POST['invoice_no']);
    $invoice_date = trim($_POST['invoice_date']);
    $amount = floatval($_POST['amount']);
    $supplier_id = intval($_POST['supplier_id']);
    $customer_id = intval($_POST['customer_id']);
    $remark = trim($_POST['remark']);
    
    // 附件上传处理
    $attachPath = '';
    if (!empty($_FILES['attach_file']['name'])) {
        $uploadDir = 'uploads/invoice_attach/';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
        $fileExt = pathinfo($_FILES['attach_file']['name'], PATHINFO_EXTENSION);
        $fileName = uniqid('invoice_') . '.' . $fileExt;
        $targetPath = $uploadDir . $fileName;
        if (move_uploaded_file($_FILES['attach_file']['tmp_name'], $targetPath)) {
            $attachPath = $targetPath;
        }
    }
    
    // 插入数据
    $sql = "INSERT INTO invoice (invoice_no, invoice_date, amount, supplier_id, customer_id, remark, attach_path, create_time) 
            VALUES ('$invoice_no', '$invoice_date', $amount, $supplier_id, $customer_id, '$remark', '$attachPath', NOW())";
    if (mysqli_query($conn, $sql)) {
        echo "<div class='alert alert-success'>发票添加成功！</div>";
    } else {
        echo "<div class='alert alert-error'>添加失败：" . mysqli_error($conn) . "</div>";
    }
}

// 查询供应商和客户数据
$supplierList = mysqli_query($conn, "SELECT id, name FROM supplier WHERE status=1 ORDER BY name");
$customerList = mysqli_query($conn, "SELECT id, name FROM customer WHERE status=1 ORDER BY name");
?>

<!-- 扫码区域 -->
<div class="scan-area">
    <button id="start-scan-btn" class="btn btn-blue">开始扫码</button>
    <button id="stop-scan-btn" class="btn btn-red" disabled>结束扫码</button>
    <div id="scan-status" class="scan-tip">已进入扫码模式，请扫描发票二维码...</div>
</div>

<!-- 表单 -->
<form method="post" enctype="multipart/form-data" id="invoiceForm">
    <input type="hidden" name="save_invoice" value="1">
    
    <div class="form-group">
        <label>发票号码 <span style="color: red;">*</span></label>
        <input type="text" name="invoice_no" id="invoice_no" class="form-control" required placeholder="扫码后自动填充或手动输入">
    </div>
    
    <div class="form-group">
        <label>开票日期 <span style="color: red;">*</span></label>
        <input type="date" name="invoice_date" id="invoice_date" class="form-control" required value="<?= date('Y-m-d') ?>">
    </div>
    
    <div class="form-group">
        <label>金额（元） <span style="color: red;">*</span></label>
        <input type="number" name="amount" id="amount" class="form-control" step="0.01" required placeholder="扫码后自动填充或手动输入">
    </div>
    
    <div class="form-group">
        <label>供应商 <span style="color: red;">*</span></label>
        <select name="supplier_id" id="supplier_id" class="form-control" required>
            <option value="">-- 请选择供应商 --</option>
            <?php if (mysqli_num_rows($supplierList) > 0): ?>
                <?php while ($row = mysqli_fetch_assoc($supplierList)): ?>
                    <option value="<?= $row['id'] ?>"><?= $row['name'] ?></option>
                <?php endwhile; ?>
            <?php else: ?>
                <option value="">暂无供应商，请先添加</option>
            <?php endif; ?>
        </select>
    </div>
    
    <div class="form-group">
        <label>客户 <span style="color: red;">*</span></label>
        <select name="customer_id" id="customer_id" class="form-control" required>
            <option value="">-- 请选择客户 --</option>
            <?php if (mysqli_num_rows($customerList) > 0): ?>
                <?php while ($row = mysqli_fetch_assoc($customerList)): ?>
                    <option value="<?= $row['id'] ?>"><?= $row['name'] ?></option>
                <?php endwhile; ?>
            <?php else: ?>
                <option value="">暂无客户，请先添加</option>
            <?php endif; ?>
        </select>
    </div>
    
    <div class="form-group">
        <label>备注</label>
        <textarea name="remark" class="form-control" placeholder="选填"></textarea>
    </div>
    
    <div class="form-group">
        <label>发票附件</label>
        <div class="attach-area">
            <input type="file" name="attach_file" accept=".pdf,.jpg,.jpeg,.png,.doc,.docx">
            <p style="margin-top: 8px; font-size: 12px; color: #666;">支持PDF、图片、Word文件</p>
        </div>
    </div>
    
    <div class="form-group">
        <button type="submit" class="btn btn-blue">保存发票</button>
        <button type="reset" class="btn btn-green">重置表单</button>
    </div>
</form>

<!-- 扫码JS -->
<script>
let isScanning = false;
let scanBuffer = '';

// 开始扫码
document.getElementById('start-scan-btn').addEventListener('click', function() {
    isScanning = true;
    scanBuffer = '';
    this.disabled = true;
    document.getElementById('stop-scan-btn').disabled = false;
    document.getElementById('scan-status').className = 'scan-tip show';
    document.getElementById('scan-status').textContent = '正在扫码，请对准二维码...';
});

// 结束扫码
document.getElementById('stop-scan-btn').addEventListener('click', function() {
    isScanning = false;
    this.disabled = true;
    document.getElementById('start-scan-btn').disabled = false;
    document.getElementById('scan-status').textContent = '扫码已停止';
});

// 监听键盘输入（扫码枪输入）
document.addEventListener('keydown', function(e) {
    if (!isScanning) return;
    
    // 忽略功能键
    if (['Shift', 'Ctrl', 'Alt', 'Meta', 'CapsLock', 'Tab', 'Enter'].includes(e.key)) {
        if (e.key === 'Enter') {
            // 扫码完成（回车结束）
            parseScanData(scanBuffer);
            scanBuffer = '';
        }
        return;
    }
    
    scanBuffer += e.key;
});

// 解析扫码数据
function parseScanData(data) {
    if (!data) return;
    
    // 适配你的二维码格式：01, 32, , 26412000000224572816, 9480.00, 20260121, , 88f
    const cleanData = data.replace(/\s+/g, '');
    const parts = cleanData.split(',');
    
    if (parts.length >= 6) {
        const invoiceNo = parts[3] || '';
        const amount = parts[4] || '';
        const invoiceDate = parts[5] || '';
        
        // 填充表单
        if (invoiceNo) document.getElementById('invoice_no').value = invoiceNo;
        if (amount) document.getElementById('amount').value = amount;
        if (invoiceDate && invoiceDate.length === 8) {
            const dateStr = `${invoiceDate.substring(0,4)}-${invoiceDate.substring(4,6)}-${invoiceDate.substring(6,8)}`;
            document.getElementById('invoice_date').value = dateStr;
        }
        
        document.getElementById('scan-status').className = 'scan-tip show scan-success';
        document.getElementById('scan-status').textContent = '扫码成功！已自动填充信息';
    } else {
        document.getElementById('scan-status').className = 'scan-tip show scan-error';
        document.getElementById('scan-status').textContent = '扫码失败：无法识别二维码格式';
    }
}
</script>