<?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');

// 获取查询条件
$startDate = isset($_GET['start_date']) ? $_GET['start_date'] : '';
$endDate = isset($_GET['end_date']) ? $_GET['end_date'] : '';
$supplier = isset($_GET['supplier']) ? $_GET['supplier'] : '';
$customer = isset($_GET['customer']) ? $_GET['customer'] : '';
$status = isset($_GET['status']) ? $_GET['status'] : '';

// 组装查询条件
$where = "1=1";
if (!empty($startDate)) $where .= " AND invoice_date >= '$startDate'";
if (!empty($endDate)) $where .= " AND invoice_date <= '$endDate'";
if (!empty($supplier)) $where .= " AND supplier = '$supplier'";
if (!empty($customer)) $where .= " AND purchaser = '$customer'";
if (!empty($status)) $where .= " AND status = '$status'";

// 查询所有发票数据
$sql = "SELECT id, invoice_no, amount, invoice_date, supplier, purchaser, remark, status, create_time FROM invoice_info WHERE $where ORDER BY create_time DESC";
$result = mysqli_query($conn, $sql);
$invoices = [];
while ($row = mysqli_fetch_assoc($result)) {
    $invoices[] = $row;
}
mysqli_close($conn);

// 生成Excel文件（CSV格式，兼容Excel）
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="发票数据_' . date('YmdHis') . '.csv"');
header('Cache-Control: max-age=0');

// 处理CSV编码（解决中文乱码）
$fp = fopen('php://output', 'w');
fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF)); // UTF-8 BOM

// 写入表头
$header = ['ID', '发票号码', '金额(元)', '开票日期', '供应商', '客户', '备注', '状态', '录入时间'];
fputcsv($fp, $header);

// 写入数据
foreach ($invoices as $invoice) {
    $row = [
        $invoice['id'],
        $invoice['invoice_no'],
        $invoice['amount'],
        $invoice['invoice_date'],
        $invoice['supplier'] ?: '',
        $invoice['purchaser'] ?: '',
        $invoice['remark'] ?: '',
        $invoice['status'],
        $invoice['create_time']
    ];
    fputcsv($fp, $row);
}

fclose($fp);
exit;
?>