<?php
/**
 * 萧山都市网 - 客户线索管理后台
 * 管理员登录后可查看提交手机号生成的 leads.txt 记录
 * 部署说明：本文件与 submit.php、index.html 放在同一目录，访问 admin.php 即可进入后台
 */

session_start();

/* ============ 配置（上线前请修改管理员密码） ============ */
define('LEADS_FILE', __DIR__ . '/leads.txt');       // 客户记录文件（与 submit.php 共用）
define('ADMIN_PASSWORD', '123123aaa');                // ← 管理员密码，请务必修改
define('MAX_RECORDS', 500);                         // 后台最多显示记录条数

/* ============ 会话与 CSRF Token ============ */
if (empty($_SESSION['xsw_token'])) {
    $_SESSION['xsw_token'] = bin2hex(random_bytes(16));
}
$token = $_SESSION['xsw_token'];

$isLogin = !empty($_SESSION['xsw_admin']) && time() - intval($_SESSION['xsw_login_time'] ?? 0) < 8 * 3600;

/* ============ 动作处理 ============ */
$error = '';
$msg = '';

// 登录
if (!$isLogin && $_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'login') {
    $pass = (string)($_POST['password'] ?? '');
    $_SESSION['xsw_fail'] = intval($_SESSION['xsw_fail'] ?? 0);
    if ($_SESSION['xsw_fail'] >= 8 && time() - intval($_SESSION['xsw_fail_time'] ?? 0) < 600) {
        $error = '尝试次数过多，请10分钟后再试';
    } elseif (hash_equals(ADMIN_PASSWORD, $pass)) {
        $_SESSION['xsw_admin'] = true;
        $_SESSION['xsw_login_time'] = time();
        unset($_SESSION['xsw_fail'], $_SESSION['xsw_fail_time']);
        header('Location: admin.php');
        exit;
    } else {
        $_SESSION['xsw_fail']++;
        $_SESSION['xsw_fail_time'] = time();
        $error = '密码错误，请重试（剩余尝试 ' . max(0, 8 - $_SESSION['xsw_fail']) . ' 次）';
    }
}

// 退出
if ($isLogin && ($_GET['action'] ?? '') === 'logout') {
    session_destroy();
    header('Location: admin.php');
    exit;
}

// 清空记录（需 CSRF token）
if ($isLogin && $_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'clear') {
    if (hash_equals($token, (string)($_POST['token'] ?? ''))) {
        @file_put_contents(LEADS_FILE, '');
        $msg = '记录已清空';
    }
}

/* ============ 读取记录 ============ */
$records = [];
$allLines = [];
if (is_file(LEADS_FILE)) {
    $allLines = file(LEADS_FILE, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
}
$total = count($allLines);
$today = 0;
$todayStr = date('Y-m-d');
foreach ($allLines as $line) {
    if (strpos($line, '[' . $todayStr) === 0) $today++;
}
foreach (array_reverse($allLines) as $line) {
    if (preg_match('/^\[(.*?)\]\s*手机号:\s*([0-9]+)\s*\|\s*称呼:\s*(.*)$/', trim($line), $m)) {
        $records[] = ['time' => $m[1], 'phone' => $m[2], 'name' => $m[3]];
    } else {
        $records[] = ['time' => '未知', 'phone' => htmlspecialchars(trim($line), ENT_QUOTES, 'UTF-8'), 'name' => '-'];
    }
    if (count($records) >= MAX_RECORDS) break;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>萧山都市网 - 客户线索管理后台</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Cdefs%3E%3ClinearGradient id='g' x1='0' y1='0' x2='1' y2='1'%3E%3Cstop offset='0' stop-color='%232E6BFF'/%3E%3Cstop offset='1' stop-color='%237C4DFF'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect width='64' height='64' rx='14' fill='url(%23g)'/%3E%3Cpath d='M12 22h40v6H12zM12 32h28v6H12zM12 42h18v6H12z' fill='%23fff'/%3E%3C/svg%3E">
<link rel="preconnect" href="https://miaoda.feishu.cn">
<link href="https://miaoda.feishu.cn/fonts/css2?family=Noto+Sans+SC:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:"Noto Sans SC","Microsoft YaHei",sans-serif;background:#F3F6FF;color:#14213D;min-height:100vh}
a{text-decoration:none;color:inherit}
.container{width:min(960px,94%);margin:0 auto}

/* 顶部栏 */
.topbar{background:linear-gradient(120deg,#1D3FD6 0%,#6D28D9 52%,#0E9FC6 100%);color:#fff;padding:22px 0}
.topbar .container{display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap}
.brand{display:flex;align-items:center;gap:12px;font-weight:800;font-size:19px}
.brand .logo{width:40px;height:40px;border-radius:11px;background:rgba(255,255,255,.16);border:1px solid rgba(255,255,255,.3);display:grid;place-items:center}
.brand small{display:block;font-size:11px;font-weight:500;color:rgba(255,255,255,.75);letter-spacing:2px}
.topbar .link{font-size:13px;color:rgba(255,255,255,.85);padding:8px 16px;border:1px solid rgba(255,255,255,.35);border-radius:999px;transition:background .25s}
.topbar .link:hover{background:rgba(255,255,255,.15)}

.wrap{padding:36px 0 60px}
.card{background:#fff;border-radius:16px;border:1px solid #E2EBFA;box-shadow:0 10px 30px rgba(20,33,61,.07);padding:26px}

/* 统计 */
.stats{display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-bottom:20px}
.stat{background:#fff;border-radius:14px;border:1px solid #E2EBFA;padding:20px;text-align:center;position:relative;overflow:hidden}
.stat::after{content:"";position:absolute;width:80px;height:80px;border-radius:50%;background:radial-gradient(circle,rgba(124,77,255,.12),transparent 70%);top:-30px;right:-30px}
.stat b{font-size:30px;font-weight:900;background:linear-gradient(120deg,#2E6BFF,#7C4DFF);-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent}
.stat span{display:block;font-size:13px;color:#5A6B8C;margin-top:6px}

/* 表格 */
.tbl-head{display:flex;align-items:center;justify-content:space-between;gap:14px;flex-wrap:wrap;margin-bottom:16px}
.tbl-head h2{font-size:18px;font-weight:800}
.tbl-head .actions{display:flex;gap:10px}
.btn{display:inline-flex;align-items:center;gap:7px;padding:9px 20px;border-radius:999px;font-size:13.5px;font-weight:600;border:none;cursor:pointer;font-family:inherit}
.btn-primary{background:linear-gradient(120deg,#2E6BFF,#7C4DFF);color:#fff}
.btn-danger{background:#fff;color:#C62828;border:1.5px solid rgba(198,40,40,.35)}
.btn-danger:hover{background:#C62828;color:#fff}
table{width:100%;border-collapse:collapse;font-size:14px}
th,td{padding:13px 14px;text-align:left;border-bottom:1px solid #EDF2FA}
th{background:#F7F9FF;font-size:12.5px;color:#5A6B8C;font-weight:700}
td.phone{font-weight:700;color:#1D3FD6;font-size:15px}
td.time{color:#5A6B8C;white-space:nowrap}
tr:hover td{background:#FAFCFF}
.empty{padding:56px 0;text-align:center;color:#9AA8BF}
.empty .ic{font-size:34px;margin-bottom:12px}

/* 登录 */
.login-box{max-width:400px;margin:56px auto;background:#fff;border-radius:20px;border:1px solid #E2EBFA;box-shadow:0 20px 50px rgba(46,107,255,.12);padding:38px 34px;text-align:center}
.login-box .logo{width:58px;height:58px;border-radius:16px;background:linear-gradient(120deg,#2E6BFF,#7C4DFF);display:grid;place-items:center;margin:0 auto 18px;color:#fff;box-shadow:0 12px 26px rgba(124,77,255,.4)}
.login-box h1{font-size:21px;font-weight:800;margin-bottom:6px}
.login-box p{font-size:13px;color:#5A6B8C;margin-bottom:24px}
.login-box input{width:100%;padding:14px 16px;border:1.5px solid #E2EBFA;border-radius:12px;font-size:15px;font-family:inherit;outline:none;margin-bottom:16px;transition:border-color .25s}
.login-box input:focus{border-color:#7C4DFF}
.login-box .btn{width:100%;justify-content:center;padding:14px;font-size:15px}
.login-box .err{background:#FDECEC;color:#C62828;font-size:13px;padding:10px 14px;border-radius:10px;margin-bottom:16px}
.login-box .tip{margin-top:18px;font-size:12px;color:#9AA8BF;line-height:1.8}
.msg{background:#EAFBF0;color:#1B7A3D;font-size:13.5px;padding:12px 16px;border-radius:10px;margin-bottom:18px;display:flex;align-items:center;gap:8px}

/* 提示条 */
.notice{background:#FFF7E8;border:1px solid #FFE3B0;color:#8A5A00;font-size:13px;padding:12px 16px;border-radius:10px;margin-bottom:20px;display:flex;align-items:center;gap:8px;line-height:1.7}

.footer{text-align:center;color:#9AA8BF;font-size:12.5px;padding:24px 0 40px}
@media (max-width:640px){
  .stats{grid-template-columns:1fr 1fr}
  .wrap{padding:24px 0 44px}
  .card{padding:18px}
}
</style>
</head>
<body>

<div class="topbar">
  <div class="container">
    <div class="brand">
      <span class="logo">
        <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="8.5"/><path d="M3.5 12h17M12 3.5c2.4 2.4 3.6 5.2 3.6 8.5s-1.2 6.1-3.6 8.5c-2.4-2.4-3.6-5.2-3.6-8.5S9.6 5.9 12 3.5Z"/></svg>
      </span>
      <span>萧山都市网<small>客户线索管理后台</small></span>
    </div>
    <?php if ($isLogin): ?>
      <div style="display:flex;gap:10px;align-items:center">
        <a class="link" href="index.html" target="_blank">查看前台页面</a>
        <a class="link" href="admin.php?action=logout">退出登录</a>
      </div>
    <?php endif; ?>
  </div>
</div>

<?php if (!$isLogin): ?>
  <!-- ===== 登录视图 ===== -->
  <div class="container">
    <form class="login-box" method="post" autocomplete="off">
      <div class="logo">
        <svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="10" width="16" height="10" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0v3M12 14v2"/></svg>
      </div>
      <h1>管理员登录</h1>
      <p>请输入后台管理密码查看客户登记信息</p>
      <?php if ($error): ?><div class="err"><?php echo htmlspecialchars($error, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
      <input type="password" name="password" placeholder="管理密码" required autofocus>
      <input type="hidden" name="action" value="login">
      <button class="btn btn-primary" type="submit">登 录</button>
      <div class="tip">默认密码见 admin.php 顶部配置，上线前请务必修改</div>
    </form>
  </div>
<?php else: ?>
  <!-- ===== 记录面板 ===== -->
  <div class="container wrap">
    <div class="notice">
      <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><circle cx="12" cy="12" r="9"/><path d="M12 8v4M12 16h.01"/></svg>
      记录保存在 <b><?php echo htmlspecialchars(LEADS_FILE, ENT_QUOTES, 'UTF-8'); ?></b>（TXT 文件），由前台表单提交自动写入。请勿删除或移动该文件。
    </div>
    <?php if ($msg): ?><div class="msg"><?php echo htmlspecialchars($msg, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>

    <div class="stats">
      <div class="stat"><b><?php echo $total; ?></b><span>登记记录总数</span></div>
      <div class="stat"><b><?php echo $today; ?></b><span>今日新增</span></div>
      <div class="stat"><b><?php echo is_file(LEADS_FILE) ? round(filesize(LEADS_FILE)/1024, 1) : 0; ?> KB</b><span>记录文件大小</span></div>
    </div>

    <div class="card">
      <div class="tbl-head">
        <h2>客户登记信息</h2>
        <div class="actions">
          <form method="post" style="display:inline" onsubmit="return confirm('确定清空全部客户记录吗？此操作不可恢复');">
            <input type="hidden" name="action" value="clear">
            <input type="hidden" name="token" value="<?php echo htmlspecialchars($token, ENT_QUOTES, 'UTF-8'); ?>">
            <button class="btn btn-danger" type="submit">清空记录</button>
          </form>
        </div>
      </div>
      <?php if (empty($records)): ?>
        <div class="empty">
          <div class="ic">
            <svg viewBox="0 0 24 24" width="40" height="40" fill="none" stroke="#B7C4DC" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" style="margin:0 auto"><rect x="4" y="3" width="16" height="18" rx="2"/><path d="M8 8h8M8 12h8M8 16h5"/></svg>
          </div>
          <div>暂无客户登记记录</div>
          <div style="font-size:12.5px;margin-top:8px">客户在前台提交手机号后将自动出现在这里</div>
        </div>
      <?php else: ?>
        <table>
          <thead>
            <tr><th style="width:60px">序号</th><th style="width:180px">提交时间</th><th style="width:180px">手机号码</th><th>称呼</th></tr>
          </thead>
          <tbody>
            <?php foreach ($records as $i => $r): ?>
            <tr>
              <td style="color:#9AA8BF"><?php echo $i + 1; ?></td>
              <td class="time"><?php echo htmlspecialchars($r['time'], ENT_QUOTES, 'UTF-8'); ?></td>
              <td class="phone"><?php echo htmlspecialchars($r['phone'], ENT_QUOTES, 'UTF-8'); ?></td>
              <td><?php echo htmlspecialchars($r['name'], ENT_QUOTES, 'UTF-8'); ?></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
        <?php if (count($records) >= MAX_RECORDS): ?>
          <div style="text-align:center;color:#9AA8BF;font-size:12.5px;margin-top:14px">仅显示最近 <?php echo MAX_RECORDS; ?> 条记录</div>
        <?php endif; ?>
      <?php endif; ?>
    </div>
  </div>
<?php endif; ?>

<div class="footer">萧山都市网 客户线索管理后台 · 400-885-6637</div>
</body>
</html>
