<?php include 'auth.php'; ?>
<?php
$usersFile = __DIR__ . '/users.json';
$users = file_exists($usersFile) ? json_decode(file_get_contents($usersFile), true) : [];
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>创建账单 - Doudou De Car!!!账单管理系统</title>
  <link rel="icon" type="image/svg+xml" href="favicon.svg">
  <link href="assets/css/bootstrap.min.css" rel="stylesheet">
  <script>
    const userData = <?= json_encode($users, JSON_UNESCAPED_UNICODE) ?>;
    let originalAmount = 0;

    function fillEmail() {
      const name = document.getElementById('buyer_name').value;
      const match = userData.find(u => u.name === name);
      document.getElementById('email').value = match ? match.email : '';
    }

    function togglePaymentFields() {
      const status = document.getElementById('status').value;
      document.getElementById('paidFields').style.display = (status === 'paid') ? 'block' : 'none';
    }

    function setAmountByProject() {
      const project = document.getElementById('server_location').value;
      if (project === '高级套餐') originalAmount = 15;
      else if (project === '上天套餐-管理员') originalAmount = 99;
      else originalAmount = 0;
      document.getElementById('amount').value = originalAmount.toFixed(2);
      recalculateDiscountedAmount();
    }

    function recalculateDiscountedAmount() {
      const discountInput = document.getElementById('discount');
      const amountField = document.getElementById('amount');
      const discount = parseFloat(discountInput.value || 0);

      if (discount > 0 && discount < 100) {
        const discounted = (originalAmount * (1 - discount / 100)).toFixed(2);
        amountField.value = discounted;
      } else {
        amountField.value = originalAmount.toFixed(2);
      }
    }

    // 页面加载时获取最新账单编号
    document.addEventListener('DOMContentLoaded', function() {
      fetch('get_latest_invoice.php')
        .then(response => response.json())
        .then(data => {
          document.getElementById('suggested-number').textContent = data.latest_number;
        })
        .catch(error => {
          document.getElementById('suggested-number').textContent = '获取失败';
          console.error('获取最新账单编号失败:', error);
        });
    });
  </script>
</head>
<body class="bg-light">

<nav class="navbar navbar-expand-lg navbar-dark bg-dark mb-4">
  <div class="container-fluid">
    <a class="navbar-brand" href="index.php">Doudou De Car!!!账单管理系统</a>
    <div class="collapse navbar-collapse d-flex justify-content-between">
      <ul class="navbar-nav me-auto">
        <li class="nav-item"><a class="nav-link active" href="index.php">➕ 创建账单</a></li>
        <li class="nav-item"><a class="nav-link" href="bill_manager.php">📂 账单管理</a></li>
        <li class="nav-item"><a class="nav-link" href="users.php">👥 用户管理</a></li>
      </ul>
      <ul class="navbar-nav ms-auto">
        <li class="nav-item"><a class="nav-link text-danger" href="logout.php">🚪 退出登录</a></li>
      </ul>
    </div>
  </div>
</nav>

<div class="container mt-4">
  <div class="card p-4 shadow">
    <h4 class="mb-4">➕ 创建新账单</h4>
    <form method="post" action="generate.php">
      <!-- 账单编号 -->
      <div class="mb-3">
        <label class="form-label">账单编号</label>
        <div class="input-group">
          <input type="text" name="invoice_number" id="invoice_number" class="form-control" required>
          <span class="input-group-text" id="next-number-hint">建议编号: <span id="suggested-number">加载中...</span></span>
        </div>
      </div>

      <!-- 用户信息 - 同一行 -->
      <div class="row mb-3">
        <div class="col-md-6">
          <label class="form-label">用户</label>
          <select name="buyer_name" id="buyer_name" class="form-select" onchange="fillEmail()" required>
            <option value="">请选择用户</option>
            <?php foreach ($users as $user): ?>
              <option value="<?= htmlspecialchars($user['name']) ?>"><?= htmlspecialchars($user['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-6">
          <label class="form-label">邮箱</label>
          <input type="email" name="email" id="email" class="form-control" readonly required>
        </div>
      </div>

      <!-- 日期信息 - 同一行 -->
      <div class="row mb-3">
        <div class="col-md-6">
          <label class="form-label">账单日期</label>
          <input type="date" name="invoice_date" class="form-control" required>
        </div>
        <div class="col-md-6">
          <label class="form-label">截止日期</label>
          <input type="date" name="payment_date" class="form-control" required>
        </div>
      </div>

      <!-- 服务信息 - 同一行 -->
      <div class="row mb-3">
        <div class="col-md-6">
          <label class="form-label">服务描述</label>
          <select name="item_desc" class="form-select" required>
            <option value="Doudou De Car!!!">Doudou De Car!!!</option>
          </select>
        </div>
        <div class="col-md-6">
          <label class="form-label">项目</label>
          <select name="server_location" id="server_location" class="form-select" onchange="setAmountByProject()" required>
            <option value="">请选择</option>
            <option value="高级套餐">高级套餐</option>
            <option value="上天套餐-管理员">上天套餐-管理员</option>
          </select>
        </div>
      </div>
      
      <!-- 服务周期 - 同一行 -->
      <div class="row mb-3">
        <div class="col-md-6">
          <label class="form-label">服务开始日期</label>
          <input type="date" name="start_date" class="form-control" required>
        </div>
        <div class="col-md-6">
          <label class="form-label">服务结束日期</label>
          <input type="date" name="end_date" class="form-control" required>
        </div>
      </div>

      <!-- 金额信息 - 同一行 -->
      <div class="row mb-3">
        <div class="col-md-4">
          <label class="form-label">折扣（百分比）</label>
          <input type="number" id="discount" name="discount" class="form-control" value="0" oninput="recalculateDiscountedAmount()">
        </div>
        <div class="col-md-4">
          <label class="form-label">最终金额（元）</label>
          <input type="number" id="amount" name="amount" class="form-control" required step="0.01" min="0">
        </div>
        <div class="col-md-4">
          <label class="form-label">账单状态</label>
          <select name="status" id="status" class="form-select" onchange="togglePaymentFields()" required>
            <option value="unpaid">未付款</option>
            <option value="paid">已付款</option>
          </select>
        </div>
      </div>

      <!-- 支付信息 - 条件显示 -->
      <div id="paidFields" style="display: none;">
        <div class="row mb-3">
          <div class="col-md-6">
            <label class="form-label">支付方式</label>
            <select name="payment_method" class="form-select">
              <option value="">请选择</option>
              <option value="支付宝">支付宝</option>
              <option value="微信">微信</option>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">交易单号</label>
            <input type="text" name="transaction_id" class="form-control">
          </div>
        </div>
      </div>

      <!-- 备注 -->
      <div class="mb-3">
        <label class="form-label">备注</label>
        <select name="note" class="form-select" required>
          <option value="请在面板完成续费或重新订阅！请在截止日期前完成续费，超期未续费系统将删除您的账号，请重新注册！！" selected>请在面板完成续费或重新订阅！请在截止日期前完成续费，超期未续费系统将删除您的账号，请重新注册！</option>
          <option value="如需发票请联系客户支持">如需发票请联系客户支持</option>
          <option value="此账单为系统自动生成">此账单为系统自动生成</option>
        </select>
      </div>

      <button type="submit" class="btn btn-primary w-100">✅ 创建账单</button>
    </form>
  </div>
</div>
</body>
</html>
