<?php
session_start();
header("Content-Type: text/html; charset=utf-8");

// 数据库配置（替换为你的实际信息）
$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, 'utf8');

// 登录验证：未登录跳登录页
$isLogin = !empty($_SESSION['user_info']);
if (!$isLogin && $_GET['page'] != 'login') {
    header("Location: ?page=login");
    exit;
}

// 处理登录请求
if ($_GET['page'] == 'login' && $_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = trim($_POST['username']);
    $password = md5(trim($_POST['password']));
    $userRes = mysqli_query($conn, "SELECT id, username, realname FROM user WHERE username = '$username' AND password = '$password'");
    if (mysqli_num_rows($userRes) > 0) {
        $userInfo = mysqli_fetch_assoc($userRes);
        $_SESSION['user_info'] = [
            'id' => $userInfo['id'],
            'username' => $userInfo['username'],
            'realname' => $userInfo['realname']
        ];
        header("Location: ?page=dashboard");
        exit;
    } else {
        $loginError = '用户名或密码错误，请重新输入';
    }
}

// 退出登录
if ($_GET['act'] == 'logout') {
    unset($_SESSION['user_info']);
    header("Location: ?page=login");
    exit;
}

// 页面路由：默认仪表盘
$page = $_GET['page'] ?? 'dashboard';
$pageTitle = '';
$contentHtml = '';

// 通用CSS样式
$commonCss = '
<style>
* {margin:0; padding:0; box-sizing:border-box; font-family: "Microsoft YaHei", sans-serif;}
body {background: #f5f7fa; padding: 20px;}
.container {max-width: 1200px; margin: 0 auto;}
.header {display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding-bottom: 10px; border-bottom: 1px solid #e6e9ed;}
.header h1 {font-size: 24px; color: #333; font-weight: 600;}
.header .user-info {color: #666;}
.header .user-info a {color: #e74c3c; text-decoration: none; margin-left: 10px;}
.menu {margin-bottom: 20px; display: flex; gap: 10px; flex-wrap: wrap;}
.menu a {padding: 8px 16px; background: #3498db; color: #fff; text-decoration: none; border-radius: 4px;}
.menu a:hover {background: #2980b9;}
.table {width: 100%; border-collapse: collapse; background: #fff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1);}
.table th, .table td {padding: 12px; text-align: left; border: 1px solid #e6e9ed;}
.table th {background: #f8f9fa; font-weight: 600; color: #333;}
.form-control {width: 100%; padding: 8px 10px; border: 1px solid #e6e9ed; border-radius: 4px; outline: none;}
.form-control:focus {border-color: #3498db; box-shadow: 0 0 0 2px rgba(52,152,219,0.1);}
.btn {padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer; font-size: 14px;}
.btn-blue {background: #3498db; color: #fff;}
.btn-blue:hover {background: #2980b9;}
.btn-green {background: #2ecc71; color: #fff;}
.btn-green:hover {background: #27ae60;}
.btn-red {background: #e74c3c; color: #fff;}
.btn-red:hover {background: #c0392b;}
.btn-gray {background: #95a5a6; color: #fff;}
.btn-gray:hover {background: #7f8c8d;}
.form-group {margin-bottom: 15px;}
.form-group label {display: block; margin-bottom: 5px; color: #666; font-weight: 500;}
.alert {padding: 10px; border-radius: 4px; margin-bottom: 15px;}
.alert-success {background: #d4edda; color: #155724;}
.alert-error {background: #f8d7da; color: #721c24;}
.alert-warning {background: #fff3cd; color: #856404;}
.scan-area {margin: 20px 0; padding: 15px; background: #f8f9fa; border-radius: 6px; border-left: 4px solid #3498db;}
.scan-tip {margin-top: 10px; font-size: 14px;}
</style>
';

// 页面逻辑分发
switch ($page) {
    case 'login':
        $pageTitle = '系统登录';
        $contentHtml = '
        <div style="max-width: 400px; margin: 50px auto; background: #fff; padding: 30px; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1);">
            <h2 style="text-align: center; margin-bottom: 20px; color: #333;">发票管理系统</h2>
            '.($loginError ? '<div class="alert alert-error">'.$loginError.'</div>' : '').'
            <form method="post">
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" name="username" class="form-control" required>
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" name="password" class="form-control" required>
                </div>
                <button type="submit" class="btn btn-blue" style="width: 100%; margin-top: 10px;">登录</button>
            </form>
        </div>';
        break;

    case 'dashboard':
        $pageTitle = '系统仪表盘';
        // 仅保留基础统计，适配数据库
        $totalInvoice = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as num FROM invoice"))['num'];
        $totalAmount = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as sum FROM invoice"))['sum'] ?? 0;
        
        $contentHtml = '
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; margin-bottom: 30px; flex-wrap: wrap;">
            <div style="background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                <h3 style="color: #666; margin-bottom: 10px; font-size: 14px; font-weight: 500;">总发票数</h3>
                <p style="font-size: 28px; font-weight: bold; color: #3498db;">'.$totalInvoice.'</p>
            </div>
            <div style="background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                <h3 style="color: #666; margin-bottom: 10px; font-size: 14px; font-weight: 500;">总金额（元）</h3>
                <p style="font-size: 28px; font-weight: bold; color: #2ecc71;">'.number_format($totalAmount, 2).'</p>
            </div>
        </div>
        <div style="background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
            <h3 style="color: #333; margin-bottom: 15px; font-weight: 600;">数据说明</h3>
            <p style="color: #666; line-height: 1.6;">
                系统适配你的数据库表结构，核心功能（发票/供应商/客户/用户的增删改查）均可正常使用；<br>
                供应商/客户表无地址字段，表单已适配删除；status字段默认赋值1（启用）。
            </p>
        </div>';
        break;

    case 'invoice_list':
        $pageTitle = '发票列表';
        // 提示信息
        $alertHtml = '';
        if (!empty($_SESSION['invoice_alert'])) {
            $alertHtml = $_SESSION['invoice_alert'];
            unset($_SESSION['invoice_alert']);
        }

        // 删除发票
        if (isset($_GET['del_id']) && intval($_GET['del_id']) > 0) {
            $delId = intval($_GET['del_id']);
            // 获取附件并删除
            $attachRes = mysqli_query($conn, "SELECT attach_path FROM invoice WHERE id = $delId");
            if (mysqli_num_rows($attachRes) > 0) {
                $attachPath = mysqli_fetch_assoc($attachRes)['attach_path'];
                if ($attachPath && file_exists(__DIR__.'/uploads/'.$attachPath)) {
                    unlink(__DIR__.'/uploads/'.$attachPath);
                }
                mysqli_query($conn, "DELETE FROM invoice WHERE id = $delId");
                $_SESSION['invoice_alert'] = '<div class="alert alert-success">发票删除成功！附件已同步清理</div>';
            } else {
                $_SESSION['invoice_alert'] = '<div class="alert alert-error">发票不存在！</div>';
            }
            header("Location: ?page=invoice_list");
            exit;
        }

        // 构建查询条件：仅保留关键词筛选
        $where = '';
        $keyword = '';
        if (isset($_GET['keyword']) && !empty($_GET['keyword'])) {
            $keyword = trim($_GET['keyword']);
            $where = "WHERE i.invoice_no LIKE '%$keyword%' OR s.name LIKE '%$keyword%' OR c.name LIKE '%$keyword%'";
        }

        // 查询发票数据
        $invoiceHtml = '';
        $res = mysqli_query($conn, "SELECT i.*, s.name as supplier_name, c.name as customer_name 
                FROM invoice i 
                LEFT JOIN supplier s ON i.supplier_id = s.id 
                LEFT JOIN customer c ON i.customer_id = c.id 
                $where ORDER BY i.create_time DESC");
        if ($res && mysqli_num_rows($res) > 0) {
            while ($row = mysqli_fetch_assoc($res)) {
                // 附件链接
                $attachHtml = '';
                if (!empty($row['attach_path'])) {
                    $attachUrl = 'uploads/'.$row['attach_path'];
                    $attachHtml = '<a href="'.$attachUrl.'" target="_blank" style="color: #3498db; text-decoration: none; margin-right: 10px;">查看附件</a>';
                }
                // 列表行
                $invoiceHtml .= '
                <tr>
                    <td>'.$row['id'].'</td>
                    <td>'.$row['invoice_no'].'</td>
                    <td>'.$row['invoice_date'].'</td>
                    <td>'.$row['amount'].'</td>
                    <td>'.$row['supplier_name'].'</td>
                    <td>'.$row['customer_name'].'</td>
                    <td>'.$row['create_time'].'</td>
                    <td>
                        '.$attachHtml.'
                        <a href="?page=invoice_list&del_id='.$row['id'].'" style="color: #e74c3c; text-decoration: none;" onclick="return confirm(\'确定删除吗？删除后附件将同步删除！\')">删除</a>
                    </td>
                </tr>';
            }
        } else {
            $invoiceHtml .= '<tr><td colspan="8" style="text-align: center; color:#95a5a6; padding: 20px;">暂无发票数据</td></tr>';
        }

        // 发票列表页面
        $contentHtml = '
        '.$alertHtml.'
        <form method="get" style="margin-bottom: 20px; display: flex; gap: 10px; align-items: center; flex-wrap: wrap;">
            <input type="hidden" name="page" value="invoice_list">
            <div style="display: flex; align-items: center; gap: 5px;">
                <label>关键词：</label>
                <input type="text" name="keyword" class="form-control" placeholder="发票号码/供应商/客户" value="'.$keyword.'" style="width: 200px;">
            </div>
            <button type="submit" class="btn btn-blue">搜索</button>
            <a href="?page=invoice_add" class="btn btn-green">新增发票</a>
        </form>
        <table class="table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>发票号码</th>
                    <th>开票日期</th>
                    <th>金额（元）</th>
                    <th>供应商</th>
                    <th>客户</th>
                    <th>添加时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>'.$invoiceHtml.'</tbody>
        </table>';
        break;

    case 'invoice_add':
        $pageTitle = '新增发票';
        $alertHtml = '';
        // 处理发票提交：适配数据库（仅保留存在的字段）
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $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'] ?? '');
            $currentUserId = $_SESSION['user_info']['id']; // 解决create_user_id非空

            // 基础校验
            if (empty($invoice_no) || empty($invoice_date) || $amount <= 0 || $supplier_id <= 0 || $customer_id <= 0) {
                $alertHtml = '<div class="alert alert-error">请填写完整且合法的信息！金额必须大于0，供应商/客户必选</div>';
            } else {
                // 发票号码唯一校验
                $checkRepeat = mysqli_query($conn, "SELECT id FROM invoice WHERE invoice_no = '$invoice_no'");
                if (mysqli_num_rows($checkRepeat) > 0) {
                    $alertHtml = '<div class="alert alert-error">【'.$invoice_no.'】已存在！禁止重复录入</div>';
                } else {
                    // 附件上传
                    $attachPath = '';
                    if (!empty($_FILES['attach_file']['name']) && $_FILES['attach_file']['error'] == 0) {
                        $uploadDir = __DIR__.'/uploads/';
                        if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
                        $fileExt = pathinfo($_FILES['attach_file']['name'], PATHINFO_EXTENSION);
                        $fileName = uniqid('invoice_').'.'.$fileExt;
                        $filePath = $uploadDir.$fileName;
                        if (move_uploaded_file($_FILES['attach_file']['tmp_name'], $filePath)) {
                            $attachPath = $fileName;
                        } else {
                            $alertHtml = '<div class="alert alert-warning">附件上传失败，发票正常保存</div>';
                        }
                    }

                    // 核心：仅写入数据库存在的字段
                    $sql = "INSERT INTO invoice (invoice_no, invoice_date, amount, supplier_id, customer_id, remark, attach_path, create_user_id, create_time) 
                            VALUES ('$invoice_no', '$invoice_date', $amount, $supplier_id, $customer_id, '$remark', '$attachPath', $currentUserId, NOW())";
                    if (mysqli_query($conn, $sql)) {
                        $_SESSION['invoice_alert'] = '<div class="alert alert-success">发票【'.$invoice_no.'】新增成功！</div>';
                        header("Location: ?page=invoice_list");
                        exit;
                    } else {
                        $alertHtml = '<div class="alert alert-error">新增失败：'.mysqli_error($conn).'</div>';
                    }
                }
            }
        }

        // 获取供应商/客户下拉选项
        $supplierOptions = '';
        $supRes = mysqli_query($conn, "SELECT id, name FROM supplier ORDER BY name");
        while ($row = mysqli_fetch_assoc($supRes)) {
            $supplierOptions .= "<option value='{$row['id']}'>{$row['name']}</option>";
        }
        $customerOptions = '';
        $cusRes = mysqli_query($conn, "SELECT id, name FROM customer ORDER BY name");
        while ($row = mysqli_fetch_assoc($cusRes)) {
            $customerOptions .= "<option value='{$row['id']}'>{$row['name']}</option>";
        }

        // 新增发票页面
        $contentHtml = '
        '.$alertHtml.'
        <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" style="margin-top: 10px; color: #6c757d; font-size: 14px;">未开始扫码</div>
        </div>

        <form method="post" enctype="multipart/form-data" style="max-width: 800px; background:#fff; padding:20px; border-radius:8px; box-shadow:0 2px 8px rgba(0,0,0,0.1);">
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap:15px; margin-bottom:15px;">
                <div class="form-group">
                    <label for="invoice_no">发票号码 <span style="color:red;">*</span></label>
                    <input type="text" id="invoice_no" name="invoice_no" class="form-control" placeholder="扫码自动填充/手动输入" required>
                    <small style="color:#95a5a6; font-size:12px;">全局唯一，不可重复</small>
                </div>
                <div class="form-group">
                    <label for="invoice_date">开票日期 <span style="color:red;">*</span></label>
                    <input type="date" id="invoice_date" name="invoice_date" class="form-control" required value="'.date('Y-m-d').'">
                </div>
            </div>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap:15px; margin-bottom:15px;">
                <div class="form-group">
                    <label for="amount">发票金额（元） <span style="color:red;">*</span></label>
                    <input type="number" id="amount" name="amount" class="form-control" step="0.01" min="0.01" placeholder="扫码自动填充/手动输入" required>
                </div>
                <div class="form-group">
                    <label for="attach_file">发票附件</label>
                    <input type="file" id="attach_file" name="attach_file" class="form-control" accept=".pdf,.jpg,.jpeg,.png">
                    <small style="color:#95a5a6; font-size:12px;">支持PDF/图片，建议小于5M</small>
                </div>
            </div>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap:15px; margin-bottom:15px;">
                <div class="form-group">
                    <label for="supplier_id">供应商 <span style="color:red;">*</span></label>
                    <select id="supplier_id" name="supplier_id" class="form-control" required>
                        <option value="">请选择供应商</option>
                        '.$supplierOptions.'
                    </select>
                </div>
                <div class="form-group">
                    <label for="customer_id">客户 <span style="color:red;">*</span></label>
                    <select id="customer_id" name="customer_id" class="form-control" required>
                        <option value="">请选择客户</option>
                        '.$customerOptions.'
                    </select>
                </div>
            </div>
            <div class="form-group" style="margin-bottom:20px;">
                <label for="remark">备注</label>
                <textarea id="remark" name="remark" class="form-control" rows="3" placeholder="选填"></textarea>
            </div>
            <div style="display: flex; gap:10px;">
                <button type="submit" class="btn btn-blue">提交保存</button>
                <a href="?page=invoice_list" class="btn btn-gray">取消返回</a>
            </div>
        </form>

        <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").style.color = "#3498db";
            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").style.color = "#6c757d";
            document.getElementById("scan-status").textContent = "扫码已停止，可手动输入信息";
        });
        document.addEventListener("keydown", function(e) {
            if (!isScanning) return;
            if (["Shift","Ctrl","Alt","Meta","CapsLock","Tab","Backspace"].includes(e.key)) return;
            if (e.key === "Enter") {
                const parts = scanBuffer.split(",");
                if (parts.length >= 6) {
                    document.getElementById("invoice_no").value = parts[3] || "";
                    document.getElementById("amount").value = parts[4] || "";
                    const d = parts[5];
                    if (d && d.length === 8) {
                        document.getElementById("invoice_date").value = d.substring(0,4)+"-"+d.substring(4,6)+"-"+d.substring(6,8);
                    }
                    document.getElementById("scan-status").style.color = "#2ecc71";
                    document.getElementById("scan-status").textContent = "扫码成功！已自动填充发票号、金额、日期";
                } else {
                    document.getElementById("scan-status").style.color = "#e74c3c";
                    document.getElementById("scan-status").textContent = "扫码数据格式错误，请重新扫描";
                }
                scanBuffer = "";
                return;
            }
            scanBuffer += e.key;
        });
        </script>';
        break;

    case 'supplier_manage':
        $pageTitle = '供应商管理';
        $alertHtml = '';
        // 删除供应商
        if (isset($_GET['del_id']) && intval($_GET['del_id']) > 0) {
            $delId = intval($_GET['del_id']);
            $checkRel = mysqli_query($conn, "SELECT id FROM invoice WHERE supplier_id = $delId");
            if (mysqli_num_rows($checkRel) > 0) {
                $alertHtml = '<div class="alert alert-error">该供应商已被发票关联，无法删除！</div>';
            } else {
                mysqli_query($conn, "DELETE FROM supplier WHERE id = $delId");
                header("Location: ?page=supplier_manage");
                exit;
            }
        }
        // 供应商添加/编辑：完全适配你的表结构（删除address，补充status=1）
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $id = intval($_POST['id']);
            $name = trim($_POST['name']);
            $contact = trim($_POST['contact']);
            $phone = trim($_POST['phone']);
            if (empty($name)) {
                $alertHtml = '<div class="alert alert-error">供应商名称不能为空！</div>';
            } else {
                if ($id > 0) {
                    // 编辑：仅更新存在的字段（name/contact/phone）
                    mysqli_query($conn, "UPDATE supplier SET name = '$name', contact = '$contact', phone = '$phone' WHERE id = $id");
                } else {
                    // 新增：添加status=1（满足非空），删除address，保留create_time
                    mysqli_query($conn, "INSERT INTO supplier (name, contact, phone, create_time, status) VALUES ('$name', '$contact', '$phone', NOW(), 1)");
                }
                header("Location: ?page=supplier_manage");
                exit;
            }
        }
        // 编辑数据
        $editSupplier = [];
        if (isset($_GET['edit_id']) && intval($_GET['edit_id']) > 0) {
            $editId = intval($_GET['edit_id']);
            $editSupplier = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM supplier WHERE id = $editId"));
        }
        // 供应商列表：删除address列，匹配表结构
        $supplierList = '';
        $supRes = mysqli_query($conn, "SELECT * FROM supplier ORDER BY create_time DESC");
        while ($row = mysqli_fetch_assoc($supRes)) {
            $supplierList .= '
            <tr>
                <td>'.$row['id'].'</td>
                <td>'.$row['name'].'</td>
                <td>'.$row['contact'].'</td>
                <td>'.$row['phone'].'</td>
                <td>'.$row['create_time'].'</td>
                <td>'.($row['status']==1?'启用':'禁用').'</td>
                <td>
                    <a href="?page=supplier_manage&edit_id='.$row['id'].'" style="color: #3498db; text-decoration: none; margin-right: 10px;">编辑</a>
                    <a href="?page=supplier_manage&del_id='.$row['id'].'" style="color: #e74c3c; text-decoration: none;" onclick="return confirm(\'确定删除吗？\')">删除</a>
                </td>
            </tr>';
        }
        // 供应商管理页面：删除address输入框，仅保留表中存在的字段
        $contentHtml = '
        '.$alertHtml.'
        <div style="display: flex; gap: 20px; margin-bottom: 20px; flex-wrap: wrap;">
            <div style="flex: 1; min-width: 300px; background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                <h3 style="color: #333; margin-bottom: 15px; font-weight: 600;">'.(empty($editSupplier) ? '添加供应商' : '编辑供应商').'</h3>
                <form method="post">
                    <input type="hidden" name="id" value="'.$editSupplier['id'].'">
                    <div class="form-group">
                        <label for="name">供应商名称 <span style="color:red;">*</span></label>
                        <input type="text" id="name" name="name" class="form-control" value="'.$editSupplier['name'].'" required>
                    </div>
                    <div class="form-group">
                        <label for="contact">联系人</label>
                        <input type="text" id="contact" name="contact" class="form-control" value="'.$editSupplier['contact'].'">
                    </div>
                    <div class="form-group">
                        <label for="phone">联系电话</label>
                        <input type="text" id="phone" name="phone" class="form-control" value="'.$editSupplier['phone'].'">
                    </div>
                    <button type="submit" class="btn btn-blue">'.(empty($editSupplier) ? '添加' : '保存修改').'</button>
                </form>
            </div>
            <div style="flex: 2; min-width: 300px;">
                <a href="?page=supplier_manage" class="btn btn-green" style="margin-bottom: 10px;">刷新列表</a>
                <table class="table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>供应商名称</th>
                            <th>联系人</th>
                            <th>联系电话</th>
                            <th>添加时间</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        '.($supplierList ?: '<tr><td colspan="7" style="text-align: center; color:#95a5a6; padding:20px;">暂无供应商数据</td></tr>').'
                    </tbody>
                </table>
            </div>
        </div>';
        break;

    case 'customer_manage':
        $pageTitle = '客户管理';
        $alertHtml = '';
        // 删除客户
        if (isset($_GET['del_id']) && intval($_GET['del_id']) > 0) {
            $delId = intval($_GET['del_id']);
            $checkRel = mysqli_query($conn, "SELECT id FROM invoice WHERE customer_id = $delId");
            if (mysqli_num_rows($checkRel) > 0) {
                $alertHtml = '<div class="alert alert-error">该客户已被发票关联，无法删除！</div>';
            } else {
                mysqli_query($conn, "DELETE FROM customer WHERE id = $delId");
                header("Location: ?page=customer_manage");
                exit;
            }
        }
        // 客户添加/编辑：完全适配表结构（删除address，补充status=1）
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $id = intval($_POST['id']);
            $name = trim($_POST['name']);
            $contact = trim($_POST['contact']);
            $phone = trim($_POST['phone']);
            if (empty($name)) {
                $alertHtml = '<div class="alert alert-error">客户名称不能为空！</div>';
            } else {
                if ($id > 0) {
                    // 编辑：仅更新存在的字段
                    mysqli_query($conn, "UPDATE customer SET name = '$name', contact = '$contact', phone = '$phone' WHERE id = $id");
                } else {
                    // 新增：添加status=1，删除address
                    mysqli_query($conn, "INSERT INTO customer (name, contact, phone, create_time, status) VALUES ('$name', '$contact', '$phone', NOW(), 1)");
                }
                header("Location: ?page=customer_manage");
                exit;
            }
        }
        // 编辑数据
        $editCustomer = [];
        if (isset($_GET['edit_id']) && intval($_GET['edit_id']) > 0) {
            $editId = intval($_GET['edit_id']);
            $editCustomer = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM customer WHERE id = $editId"));
        }
        // 客户列表：删除address列
        $customerList = '';
        $cusRes = mysqli_query($conn, "SELECT * FROM customer ORDER BY create_time DESC");
        while ($row = mysqli_fetch_assoc($cusRes)) {
            $customerList .= '
            <tr>
                <td>'.$row['id'].'</td>
                <td>'.$row['name'].'</td>
                <td>'.$row['contact'].'</td>
                <td>'.$row['phone'].'</td>
                <td>'.$row['create_time'].'</td>
                <td>'.($row['status']==1?'启用':'禁用').'</td>
                <td>
                    <a href="?page=customer_manage&edit_id='.$row['id'].'" style="color: #3498db; text-decoration: none; margin-right: 10px;">编辑</a>
                    <a href="?page=customer_manage&del_id='.$row['id'].'" style="color: #e74c3c; text-decoration: none;" onclick="return confirm(\'确定删除吗？\')">删除</a>
                </td>
            </tr>';
        }
        // 客户管理页面：删除address输入框
        $contentHtml = '
        '.$alertHtml.'
        <div style="display: flex; gap: 20px; margin-bottom: 20px; flex-wrap: wrap;">
            <div style="flex: 1; min-width: 300px; background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                <h3 style="color: #333; margin-bottom: 15px; font-weight: 600;">'.(empty($editCustomer) ? '添加客户' : '编辑客户').'</h3>
                <form method="post">
                    <input type="hidden" name="id" value="'.$editCustomer['id'].'">
                    <div class="form-group">
                        <label for="name">客户名称 <span style="color:red;">*</span></label>
                        <input type="text" id="name" name="name" class="form-control" value="'.$editCustomer['name'].'" required>
                    </div>
                    <div class="form-group">
                        <label for="contact">联系人</label>
                        <input type="text" id="contact" name="contact" class="form-control" value="'.$editCustomer['contact'].'">
                    </div>
                    <div class="form-group">
                        <label for="phone">联系电话</label>
                        <input type="text" id="phone" name="phone" class="form-control" value="'.$editCustomer['phone'].'">
                    </div>
                    <button type="submit" class="btn btn-blue">'.(empty($editCustomer) ? '添加' : '保存修改').'</button>
                </form>
            </div>
            <div style="flex: 2; min-width: 300px;">
                <a href="?page=customer_manage" class="btn btn-green" style="margin-bottom: 10px;">刷新列表</a>
                <table class="table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>客户名称</th>
                            <th>联系人</th>
                            <th>联系电话</th>
                            <th>添加时间</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        '.($customerList ?: '<tr><td colspan="7" style="text-align: center; color:#95a5a6; padding:20px;">暂无客户数据</td></tr>').'
                    </tbody>
                </table>
            </div>
        </div>';
        break;

    case 'user_manage':
        $pageTitle = '用户管理';
        $alertHtml = '';
        // 删除用户
        if (isset($_GET['del_id']) && intval($_GET['del_id']) > 0) {
            $delId = intval($_GET['del_id']);
            if ($delId == $_SESSION['user_info']['id']) {
                $alertHtml = '<div class="alert alert-error">禁止删除当前登录账号！</div>';
            } else {
                mysqli_query($conn, "DELETE FROM user WHERE id = $delId");
                header("Location: ?page=user_manage");
                exit;
            }
        }
        // 重置密码
        if (isset($_GET['reset_pwd']) && intval($_GET['reset_pwd']) > 0) {
            $resetId = intval($_GET['reset_pwd']);
            $newPwd = md5('123456');
            mysqli_query($conn, "UPDATE user SET password = '$newPwd' WHERE id = $resetId");
            $_SESSION['invoice_alert'] = '<div class="alert alert-success">密码已重置为：123456</div>';
            header("Location: ?page=user_manage");
            exit;
        }
        // 用户添加/编辑
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $id = intval($_POST['id']);
            $username = trim($_POST['username']);
            $realname = trim($_POST['realname']);
            $password = trim($_POST['password']);
            if (empty($username) || empty($realname)) {
                $alertHtml = '<div class="alert alert-error">用户名和真实姓名为必填项！</div>';
            } else {
                if ($id > 0) {
                    $pwdSql = !empty($password) ? ", password = '".md5($password)."'" : "";
                    mysqli_query($conn, "UPDATE user SET realname = '$realname' $pwdSql WHERE id = $id");
                } else {
                    if (empty($password)) {
                        $alertHtml = '<div class="alert alert-error">新增用户必须设置密码！</div>';
                    } else {
                        $checkUser = mysqli_query($conn, "SELECT id FROM user WHERE username = '$username'");
                        if (mysqli_num_rows($checkUser) > 0) {
                            $alertHtml = '<div class="alert alert-error">用户名已存在！</div>';
                        } else {
                            mysqli_query($conn, "INSERT INTO user (username, password, realname, create_time) VALUES ('$username', '".md5($password)."', '$realname', NOW())");
                        }
                    }
                }
                if (empty($alertHtml)) {
                    header("Location: ?page=user_manage");
                    exit;
                }
            }
        }
        // 编辑数据
        $editUser = [];
        if (isset($_GET['edit_id']) && intval($_GET['edit_id']) > 0) {
            $editId = intval($_GET['edit_id']);
            $editUser = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM user WHERE id = $editId"));
        }
        // 用户列表
        $userList = '';
        $userRes = mysqli_query($conn, "SELECT * FROM user ORDER BY create_time DESC");
        while ($row = mysqli_fetch_assoc($userRes)) {
            $operateHtml = $row['id'] == $_SESSION['user_info']['id'] ? 
                '<span style="color: #95a5a6;">不可操作</span>' : 
                '<a href="?page=user_manage&edit_id='.$row['id'].'" style="color: #3498db; text-decoration: none; margin-right: 10px;">编辑</a>
                <a href="?page=user_manage&reset_pwd='.$row['id'].'" style="color: #f39c12; text-decoration: none; margin-right: 10px;" onclick="return confirm(\'确定重置密码为123456吗？\')">重置密码</a>
                <a href="?page=user_manage&del_id='.$row['id'].'" style="color: #e74c3c; text-decoration: none;" onclick="return confirm(\'确定删除该用户吗？\')">删除</a>';
            $userList .= '
            <tr>
                <td>'.$row['id'].'</td>
                <td>'.$row['username'].'</td>
                <td>'.$row['realname'].'</td>
                <td>'.$row['create_time'].'</td>
                <td>'.$operateHtml.'</td>
            </tr>';
        }
        // 用户管理页面
        $contentHtml = '
        '.$alertHtml.'
        <div style="display: flex; gap: 20px; margin-bottom: 20px; flex-wrap: wrap;">
            <div style="flex: 1; min-width: 300px; background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                <h3 style="color: #333; margin-bottom: 15px; font-weight: 600;">'.(empty($editUser) ? '添加用户' : '编辑用户').'</h3>
                <form method="post">
                    <input type="hidden" name="id" value="'.$editUser['id'].'">
                    <div class="form-group">
                        <label for="username">用户名 <span style="color:red;">*</span></label>
                        <input type="text" id="username" name="username" class="form-control" value="'.$editUser['username'].'" '.($editUser ? 'readonly' : 'required').'>
                        <small style="color:#95a5a6; font-size:12px;">新增可填，编辑不可修改</small>
                    </div>
                    <div class="form-group">
                        <label for="realname">真实姓名 <span style="color:red;">*</span></label>
                        <input type="text" id="realname" name="realname" class="form-control" value="'.$editUser['realname'].'" required>
                    </div>
                    <div class="form-group">
                        <label for="password">登录密码 '.($editUser ? '<small style="color:#95a5a6;">不填则保持原密码</small>' : '<span style="color:red;">*</span>').'</label>
                        <input type="password" id="password" name="password" class="form-control" placeholder="请输入密码">
                    </div>
                    <button type="submit" class="btn btn-blue">'.(empty($editUser) ? '添加用户' : '保存修改').'</button>
                </form>
            </div>
            <div style="flex: 2; min-width: 300px;">
                <a href="?page=user_manage" class="btn btn-green" style="margin-bottom: 10px;">刷新列表</a>
                <table class="table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>用户名</th>
                            <th>真实姓名</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        '.($userList ?: '<tr><td colspan="5" style="text-align: center; color:#95a5a6; padding:20px;">暂无用户数据</td></tr>').'
                    </tbody>
                </table>
            </div>
        </div>';
        break;

    default:
        $pageTitle = '404页面不存在';
        $contentHtml = '
        <div style="text-align: center; margin-top: 100px; background: #fff; padding: 50px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
            <h2 style="font-size: 48px; color: #e74c3c; margin-bottom: 20px;">404</h2>
            <p style="font-size: 18px; color: #666; margin-bottom: 30px;">你访问的页面不存在或已被删除</p>
            <a href="?page=dashboard" class="btn btn-blue">返回首页</a>
        </div>';
        break;
}

// 页面主体渲染
echo '
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发票管理系统 - '.$pageTitle.'</title>
    '.$commonCss.'
</head>
<body>
    <div class="container">
        '.($isLogin ? '
        <div class="header">
            <h1>发票管理系统</h1>
            <div class="user-info">
                欢迎，'.$_SESSION['user_info']['realname'].' | 
                <a href="?act=logout">退出登录</a>
            </div>
        </div>
        <div class="menu">
            <a href="?page=dashboard">仪表盘</a>
            <a href="?page=invoice_list">发票管理</a>
            <a href="?page=invoice_add">新增发票</a>
            <a href="?page=supplier_manage">供应商管理</a>
            <a href="?page=customer_manage">客户管理</a>
            <a href="?page=user_manage">用户管理</a>
            <a href="report.php">数据大屏</a>
            
           
        </div>
        ' : '').'
        <div class="content">
            '.$contentHtml.'
        </div>
    </div>
</body>
</html>';

// 关闭数据库连接
mysqli_close($conn);
?>