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

function getEmail($name, $users) {
    foreach ($users as $u) {
        if ($u['name'] === $name) return $u['email'] ?? '';
    }
    return '';
}

// 分页逻辑
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$per_page = 20;
$total_records = count($meta);
$total_pages = ceil($total_records / $per_page);
$offset = ($page - 1) * $per_page;

// 获取当前页的数据
$meta_paged = array_slice($meta, $offset, $per_page, true);
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>账单管理</title>
  <link rel="icon" type="image/svg+xml" href="favicon.svg">
  <link href="assets/css/bootstrap.min.css" rel="stylesheet">
    <script src="assets/js/sweetalert2.all.min.js"></script>
  <style>
    .btn-purple {
      background-color: #6f42c1;
      color: white;
    }
    .btn-purple:hover {
      background-color: #5a32a3;
      color: white;
    }
    .btn-deleted {
      background-color: #d2691e;
      color: white;
    }
    .btn-deleted:hover {
      background-color: #a0522d;
      color: white;
    }
  </style>
</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">
      <ul class="navbar-nav me-auto">
        <li class="nav-item"><a class="nav-link" href="index.php">➕ 创建账单</a></li>
        <li class="nav-item"><a class="nav-link active" 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">
  <h4 class="mb-3">📂 所有账单 (共 <?= $total_records ?> 条记录，第 <?= $page ?>/<?= $total_pages ?> 页)</h4>
  
  <?php if ($total_pages > 1): ?>
  <nav aria-label="账单分页">
    <ul class="pagination justify-content-center mb-3">
      <?php if ($page > 1): ?>
        <li class="page-item">
          <a class="page-link" href="?page=<?= $page - 1 ?>">上一页</a>
        </li>
      <?php endif; ?>
      
      <?php
      $start_page = max(1, $page - 2);
      $end_page = min($total_pages, $page + 2);
      
      if ($start_page > 1): ?>
        <li class="page-item"><a class="page-link" href="?page=1">1</a></li>
        <?php if ($start_page > 2): ?>
          <li class="page-item disabled"><span class="page-link">...</span></li>
        <?php endif; ?>
      <?php endif; ?>
      
      <?php for ($i = $start_page; $i <= $end_page; $i++): ?>
        <li class="page-item <?= $i == $page ? 'active' : '' ?>">
          <a class="page-link" href="?page=<?= $i ?>"><?= $i ?></a>
        </li>
      <?php endfor; ?>
      
      <?php if ($end_page < $total_pages): ?>
        <?php if ($end_page < $total_pages - 1): ?>
          <li class="page-item disabled"><span class="page-link">...</span></li>
        <?php endif; ?>
        <li class="page-item"><a class="page-link" href="?page=<?= $total_pages ?>"><?= $total_pages ?></a></li>
      <?php endif; ?>
      
      <?php if ($page < $total_pages): ?>
        <li class="page-item">
          <a class="page-link" href="?page=<?= $page + 1 ?>">下一页</a>
        </li>
      <?php endif; ?>
    </ul>
  </nav>
  <?php endif; ?>
  
  <table class="table table-bordered align-middle">
    <thead class="table-light">
      <tr>
        <th>账单号</th>
        <th>用户</th>
        <th>邮箱</th>
        <th>到期日</th>
        <th>状态</th>
        <th>金额</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($meta_paged as $id => $item): ?>
      <tr>
        <td><?= htmlspecialchars($id) ?></td>
        <td><?= htmlspecialchars($item['buyer_name']) ?></td>
        <td><?= htmlspecialchars($item['email'] ?? getEmail($item['buyer_name'], $users)) ?></td>
        <td>
          <?php if ($item['status'] === 'paid'): ?>
            <span class="text-success">已付款</span>
          <?php elseif ($item['status'] === 'deleted'): ?>
            <span class="text-muted">已删除</span>
          <?php else: ?>
            <?= htmlspecialchars($item['payment_date'] ?? '未设置') ?>
          <?php endif; ?>
        </td>
        <td>
          <?php if ($item['status'] === 'paid'): ?>
            <span class="badge bg-success">已付款</span>
          <?php elseif ($item['status'] === 'deleted'): ?>
            <span class="badge" style="background-color: #8b0000;">已删除</span>
          <?php else: ?>
            <span class="badge bg-danger">未付款</span>
          <?php endif; ?>
        </td>
        <td>¥<?= $item['amount'] ?></td>
        <td>
          <?php if ($item['status'] !== 'deleted'): ?>
            <a href="invoices/Invoice-<?= $id ?>.pdf" class="btn btn-sm btn-secondary" target="_blank">查看</a>
            <a href="javascript:void(0);" onclick="sendMail('<?= $id ?>')" class="btn btn-sm btn-primary">发送</a>
            <?php if ($item['status'] !== 'paid'): ?>
              <a href="javascript:void(0);" onclick="markPaid('<?= $id ?>')" class="btn btn-sm btn-warning">标记为已支付</a>
              <a href="javascript:void(0);" onclick="sendDeleteNotice('<?= $id ?>')" class="btn btn-sm btn-purple">账号通知删除</a>
              <a href="javascript:void(0);" onclick="markDeleted('<?= $id ?>')" class="btn btn-sm btn-deleted">标记为已删除</a>
            <?php endif; ?>
            <a href="javascript:void(0);" onclick="deleteInvoice('<?= $id ?>')" class="btn btn-sm btn-danger">删除</a>
          <?php endif; ?>
        </td>
      </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

<script>
function sendMail(id) {
  fetch('send_mail.php?invoice=' + id)
    .then(() => {
      Swal.fire({ icon: 'success', title: '邮件已发送', text: '账单已成功发送至用户邮箱', timer: 2000, showConfirmButton: false });
    })
    .catch(() => Swal.fire('错误', '发送失败，请检查服务器配置', 'error'));
}

function markPaid(id) {
  Swal.fire({
    title: '标记为已支付',
    html:
      '<select id="paymentMethod" class="swal2-input">' +
        '<option value="">请选择支付方式</option>' +
        '<option value="支付宝">支付宝</option>' +
        '<option value="微信">微信</option>' +
        '<option value="余额支付">余额支付</option>' +
      '</select>' +
      '<input id="transactionId" class="swal2-input" placeholder="请输入交易单号">' +
      '<input id="payTime" class="swal2-input" type="date" placeholder="交易时间">',
    showCancelButton: true,
    confirmButtonText: '提交',
    preConfirm: () => {
      const method = document.getElementById('paymentMethod').value;
      const tid = document.getElementById('transactionId').value;
      const time = document.getElementById('payTime').value;
      if (!method || !tid || !time) {
        Swal.showValidationMessage('请完整填写信息');
        return false;
      }
      return { method, tid, time };
    }
  }).then(result => {
    if (result.isConfirmed) {
      fetch(`mark_paid.php?invoice=${id}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(result.value)
      })
      .then(r => r.text())
      .then(res => {
        if (res.trim().toLowerCase() === 'ok') {
          Swal.fire({ icon: 'success', title: '操作成功', text: '账单已标记为已支付', timer: 1500, showConfirmButton: false })
            .then(() => location.reload());
        } else {
          Swal.fire('错误', res || '操作失败', 'error');
        }
      })
      .catch(() => Swal.fire('网络错误', '请求失败，请检查网络或服务器', 'error'));
    }
  });
}

function deleteInvoice(id) {
  Swal.fire({
    title: '确认删除账单？',
    text: `账单 #${id} 将被永久删除`,
    icon: 'warning',
    showCancelButton: true,
    confirmButtonText: '确认删除',
    cancelButtonText: '取消'
  }).then(result => {
    if (result.isConfirmed) {
      fetch(`delete_invoice.php?invoice=${id}`)
        .then(r => r.text())
        .then(res => {
          if (res === 'ok') {
            Swal.fire({ icon: 'success', title: '删除成功', timer: 1500, showConfirmButton: false })
              .then(() => location.reload());
          } else {
            Swal.fire('错误', res || '删除失败', 'error');
          }
        })
        .catch(() => Swal.fire('网络错误', '请求失败，请检查服务器', 'error'));
    }
  });
}

function sendDeleteNotice(id) {
  Swal.fire({
    title: '确认发送删除通知？',
    text: `将向账单 #${id} 对应用户发送删除提醒邮件`,
    icon: 'warning',
    showCancelButton: true,
    confirmButtonText: '发送',
    cancelButtonText: '取消'
  }).then(result => {
    if (result.isConfirmed) {
      fetch(`send_delete_notice.php?invoice=${id}`)
        .then(r => r.text())
        .then(res => {
          if (res.trim().toLowerCase() === 'ok') {
            Swal.fire('成功', '邮件已发送', 'success');
          } else {
            Swal.fire('错误', res, 'error');
          }
        })
        .catch(() => Swal.fire('网络错误', '请求失败', 'error'));
    }
  });
}

function markDeleted(id) {
  Swal.fire({
    title: '确认标记为已删除？',
    text: `账单 #${id} 将被标记为已删除状态`,
    icon: 'warning',
    showCancelButton: true,
    confirmButtonText: '标记',
    cancelButtonText: '取消'
  }).then(result => {
    if (result.isConfirmed) {
      fetch(`mark_deleted.php?invoice=${id}`)
        .then(r => r.text())
        .then(res => {
          if (res.trim().toLowerCase() === 'ok') {
            Swal.fire('成功', '账单已标记为已删除', 'success')
              .then(() => location.reload());
          } else {
            Swal.fire('错误', res, 'error');
          }
        })
        .catch(() => Swal.fire('网络错误', '请求失败', 'error'));
    }
  });
}
</script>

</body>
</html>
