<?php
date_default_timezone_set('PRC'); // 一切按北京时间（PRC = Asia/Shanghai）计算
$flag_file = __DIR__ . '/../PPQSQL.PPQSQL';
$today = date('Ymd');
$need_update = true;
if (file_exists($flag_file)) {
    $last = trim(file_get_contents($flag_file));
    if ($last === $today) $need_update = false;
}

// ---------------------------------------------------------------------------
// 今日首位访客彩蛋：只有当天真正第一个触发更新的人能看到。
// 用"原子创建"标记文件来认领，并发时也只有一个人拿得到；
// 第二个进来的人正常看更新进度，不再重复弹彩蛋。
// ---------------------------------------------------------------------------
$tmp_dir  = __DIR__ . '/tmp';
$egg_flag = $tmp_dir . '/first_visitor_' . $today . '.txt';
$is_first_visitor = false;
if ($need_update) {
    if (!is_dir($tmp_dir)) { @mkdir($tmp_dir, 0777, true); }
    $fh = @fopen($egg_flag, 'x');
    if ($fh) {
        @fwrite($fh, date('Y-m-d H:i:s'));
        @fclose($fh);
        $is_first_visitor = true;
    }
    $olds = glob($tmp_dir . '/first_visitor_*.txt');
    if ($olds) {
        foreach ($olds as $of) {
            if (is_file($of) && (time() - filemtime($of)) > 7 * 86400) @unlink($of);
        }
    }
}

// 判断是否为首次铺数据（Home 下无视频 txt）
$home_dir = __DIR__ . '/Home';
$is_first = !is_dir($home_dir) || empty(glob($home_dir . '/*.txt'));
$page_title = $is_first ? '首次初始化内容中' : '数据更新中';
$page_hint  = $is_first ? '首次部署，正在快速初始化网站内容，请稍候...' : '正在更新数据，请稍候...';
$status_init = $is_first ? '正在初始化内容（每类最新 50 条）...' : '连接更新服务器中...';
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title><?php echo $page_title; ?></title>
<style>
* { box-sizing: border-box; }
body {
  font-family: "Microsoft YaHei", "PingFang SC", "Helvetica Neue", Arial, sans-serif;
  background: linear-gradient(180deg,#f4faf7 0%,#ffffff 38%);
  color: #333;
  text-align: center;
  margin: 0;
  padding: clamp(48px,11vw,120px) 16px 48px;
  -webkit-font-smoothing: antialiased;
}
.container {
  width: 100%;
  max-width: 600px;
  margin: auto;
}

/* ---------- 今日首位访客彩蛋 ---------- */
.egg{
  position:relative;
  overflow:hidden;
  margin:0 auto 32px;
  padding:30px 24px 26px;
  border-radius:20px;
  background:linear-gradient(158deg,#f1fbf6 0%,#ffffff 52%,#f3f9ff 100%);
  border:1px solid #d9ece4;
  box-shadow:0 14px 34px rgba(27,50,74,.09), inset 0 1px 0 rgba(255,255,255,.9);
  animation:eggIn .7s cubic-bezier(.22,.9,.3,1) both;
}
.egg::before{
  content:"";position:absolute;left:0;right:0;top:0;height:3px;
  background:linear-gradient(90deg,#1aad19,#00c853,#00bfa5,#1aad19);
  background-size:300% 100%;
  animation:eggFlow 3.4s linear infinite;
}
.egg-badge{
  display:inline-flex;align-items:center;gap:7px;
  padding:6px 15px;margin-bottom:18px;
  border-radius:999px;
  background:linear-gradient(90deg,#1aad19,#00bfa5);
  color:#fff;font-size:12px;font-weight:700;letter-spacing:.08em;
  box-shadow:0 6px 16px rgba(26,173,25,.24);
}
.egg-badge .dot{
  width:6px;height:6px;border-radius:50%;background:#fff;
  animation:eggPulse 1.8s ease-out infinite;
}
.egg-zh{
  margin:0 0 12px;
  font-size:clamp(17px,4.6vw,21px);
  line-height:1.9;
  font-weight:600;
  color:#1f2d3d;
  letter-spacing:.01em;
}
.egg-zh em{font-style:normal;color:#0f9d58;}
.egg-en{
  margin:0;
  font-size:clamp(12.5px,3.3vw,14.5px);
  line-height:1.8;
  font-weight:400;
  color:#7f8c9b;
  letter-spacing:.02em;
}
@keyframes eggIn{from{opacity:0;transform:translateY(16px)}to{opacity:1;transform:none}}
@keyframes eggFlow{from{background-position:0 0}to{background-position:300% 0}}
@keyframes eggPulse{
  0%{box-shadow:0 0 0 0 rgba(255,255,255,.7)}
  70%{box-shadow:0 0 0 9px rgba(255,255,255,0)}
  100%{box-shadow:0 0 0 0 rgba(255,255,255,0)}
}
@media (max-width:420px){
  .egg{padding:24px 16px 22px;border-radius:16px;margin-bottom:26px}
  .egg-badge{font-size:11px;padding:5px 12px}
}

/* ---------- 原有进度区 ---------- */
h1 {
  font-size: clamp(19px,5vw,22px);
  margin: 0 0 20px;
}
.progress {
  width: 100%;
  height: 26px;
  background: #f0f0f0;
  border-radius: 13px;
  overflow: hidden;
  box-shadow: inset 0 0 5px rgba(0,0,0,.1);
}
.bar {
  height: 100%;
  width: 0%;
  background: linear-gradient(90deg, #1aad19, #00c853);
  transition: width .3s ease-in-out;
}
.status {
  font-size: 17px;
  margin-top: 18px;
  color: #444;
  word-break: break-word;
  white-space: pre-wrap;
}
small {
  color: #888;
  display: block;
  margin-top: 12px;
}
.loader {
  display: inline-block;
  width: 22px;
  height: 22px;
  border: 3px solid #ccc;
  border-top-color: #1aad19;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  vertical-align: middle;
  margin-right: 8px;
}
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
.flash {
  animation: flash 1s ease-in-out infinite alternate;
}
@keyframes flash {
  from {opacity: 1;}
  to {opacity: .4;}
}
.success-box, .error-box {
  text-align: left;
  padding: 14px;
  margin-top: 16px;
  border-radius: 6px;
  font-size: 15px;
  line-height: 1.6;
}
.success-box {
  background: #f1fff5;
  color: #2e7d32;
  border: 1px solid #a5d6a7;
}
.error-box {
  background: #fff5f5;
  color: #c62828;
  border: 1px solid #ffcdd2;
}
</style>
</head>
<body>
<div class="container">
<?php if ($need_update): ?>
<?php if ($is_first_visitor): ?>
  <div class="egg">
    <div class="egg-badge"><span class="dot"></span>今日首位访客<span style="opacity:.65">·</span>FIRST VISITOR</div>
    <p class="egg-zh">
      恭喜你作为本站今日的<em>第一个访客</em>，<br>
      可以最先看到今日更新影片。<br>
      正在为你同步更新内容，稍等片刻，精彩即将呈现。
    </p>
    <p class="egg-en">
      You're our first visitor today — the newest releases are yours to see first.<br>
      We're syncing today's updates for you. Sit tight, something good is on the way.
    </p>
  </div>
<?php endif; ?>
  <h1><span class="loader"></span> <?php echo $page_title; ?>，请稍候...</h1>
  <div class="progress"><div class="bar" id="bar"></div></div>
  <div class="status" id="status"><?php echo $status_init; ?></div>
  <small><?php echo $page_hint; ?>更新完成后将自动返回首页</small>

  <script>
  const bar = document.getElementById('bar');
  const status = document.getElementById('status');
  let progress = 0;

  // 真实进度：轮询 collect_status.json
  function poll() {
    fetch('collect.php?t=' + Date.now())
      .then(r => r.json())
      .then(d => {
        if (d && d['状态']) {
          if (d['状态'].indexOf('失败') === 0) {
            clearInterval(timer);
            status.innerHTML = '<div class="error-box">❌ ' + d['状态'] + (d['原因'] ? '<br>' + d['原因'] : '') + '</div>';
            return;
          }
          if (d['状态'].indexOf('每日增量采集') === 0 && (!d['分类明细'] || !d['分类明细'].length)) {
            status.textContent = '正在启动每日增量采集，请稍候…';
          }
          if (d['状态'].indexOf('完成') === 0) {
            bar.style.width = '100%';
            bar.style.background = 'linear-gradient(90deg,#00bfa5,#00c853)';
            status.innerHTML = '<div class="success-box flash">✅ ' + d['状态'] + '，正在跳转首页...</div>';
            clearInterval(timer);
            setTimeout(() => { location.href = '/' }, 2000);
            return;
          }
        }
        if (d && d['分类明细'] && d['分类明细'].length) {
          let done = 0, total = 0;
          d['分类明细'].forEach(c => { done += c['实际']; total += c['期望']; });
          if (total > 0) {
            let pct = Math.min(99, Math.round(done / total * 100));
            bar.style.width = pct + '%';
            status.textContent = '已采集 ' + done + ' / 约 ' + total + ' 条（' + d['分类明细'].length + ' 个分类完成）';
          }
        }
      })
      .catch(()=>{});
  }
  const timer = setInterval(poll, 1500);
  poll();

  // 触发更新
  fetch('API.php?t=' + Date.now())
    .then(r => r.text())
    .then(tx => {
      // 不立即结束，等 poll 检测到"完成"再跳转
      if (/Permission|denied|权限|拒绝/i.test(tx)) {
        clearInterval(timer);
        bar.style.background = '#f44336';
        status.innerHTML = '<div class="error-box">❌ 权限错误<br>系统无法写入更新文件，请检查 PPQSQL 目录权限（建议 755）</div>';
        return;
      }
      if (/失败|错误|error/i.test(tx)) {
        // 非致命错误，仍等待 poll 结果
      }
    })
    .catch(() => {
      // 跨域或网络错误，poll 仍可能成功
    });
  </script>
<?php else: ?>
  <h1>✅ 今日内容已是最新</h1>
  <div class="success-box flash">系统检测到当前内容无需更新，将自动跳转首页...</div>
  <script>setTimeout(()=>{location.href='/'},1500);</script>
<?php endif; ?>
</div>
</body>
</html>
