<?php
$cfg = app_config();
$appName = $cfg['app_name'] ?? app_zh('管理后台');
$assets = rtrim(asset_url(), '/');
$faviconUrl = public_file_url('favicon.ico');

$isAdminUser = (($user['role'] ?? '') === 'admin');
$remoteNotices = $isAdminUser ? remote_notice_data() : ['site_notice' => null, 'update_notice' => null];
$siteNotice = $remoteNotices['site_notice'] ?? null;
$updateNotice = $remoteNotices['update_notice'] ?? null;

$isSystemUpdatePage = (($view ?? '') === 'admin/system');
$currentVersion = trim((string)($cfg['app_version'] ?? '0.0.0'));
$latestVersion = trim((string)($updateNotice['version'] ?? ''));
$noticeUser = (string)($user['username'] ?? 'guest');

$maskText = static function ($value): string {
    return e(app_mask_sensitive_text((string)$value));
};

$showUpdateNotice = $isAdminUser
    && !$isSystemUpdatePage
    && $latestVersion !== ''
    && station_is_version_newer($latestVersion, $currentVersion);
$showSiteNotice = $isAdminUser && !empty($siteNotice);

$updateItems = station_release_note_items($updateNotice['update_note'] ?? ($updateNotice['update_items'] ?? ''));
$optItems = station_release_note_items($updateNotice['optimize_note'] ?? ($updateNotice['optimize_items'] ?? ''));
$fixItems = station_release_note_items($updateNotice['fix_note'] ?? ($updateNotice['fix_items'] ?? ''));
$updateChannel = station_front_release_channel_normalize((string)($updateNotice['release_channel'] ?? ($updateNotice['channel'] ?? '')));
$updatePointsCount = count($updateItems) + count($optItems) + count($fixItems);
$showPointsTag = $updatePointsCount > 0;
$hasUpdateDetails = !empty($updateItems) || !empty($optItems) || !empty($fixItems);

$siteNoticeHash = md5(json_encode($siteNotice, JSON_UNESCAPED_UNICODE));
$updateNoticeHash = md5(json_encode([$currentVersion, $updateNotice], JSON_UNESCAPED_UNICODE));
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <title><?= e($title ?? $appName) ?></title>
  <link rel="icon" href="<?= e_url($faviconUrl) ?>" type="image/ico">
  <link href="<?= e_url($assets . '/css/bootstrap.min.css') ?>" rel="stylesheet">
  <link href="<?= e_url($assets . '/css/materialdesignicons.min.css') ?>" rel="stylesheet">
  <link href="<?= e_url($assets . '/css/style.min.css') ?>" rel="stylesheet">
  <link href="<?= e_url($assets . '/css/custom.css') ?>" rel="stylesheet">
  <style>
    .ios-popup-lock {
      overflow: hidden;
    }
    .ios-popup {
      position: fixed;
      inset: 0;
      display: none;
      align-items: center;
      justify-content: center;
      background: rgba(8, 12, 22, 0.38);
      backdrop-filter: blur(8px);
      -webkit-backdrop-filter: blur(8px);
      z-index: 9999;
      padding: 16px;
    }
    .ios-popup.is-open {
      display: flex;
      animation: iosFadeIn .24s ease;
    }
    .ios-box {
      width: min(520px, 100%);
      border-radius: 20px;
      background: rgba(255, 255, 255, 0.94);
      border: 1px solid rgba(255, 255, 255, 0.86);
      box-shadow: 0 26px 60px rgba(15, 23, 42, 0.3);
      overflow: hidden;
      animation: iosPop .34s cubic-bezier(.24,1.22,.44,1);
      transform-origin: 50% 60%;
    }
    .ios-head {
      padding: 18px 18px 14px;
      border-bottom: 1px solid #e6edf7;
      background: linear-gradient(180deg, #fdfefe 0%, #f4f8ff 100%);
    }
    .ios-head h3 {
      margin: 0;
      font-size: 20px;
      font-weight: 700;
      color: #0f172a;
    }
    .ios-head p {
      margin: 6px 0 0;
      color: #586780;
      font-size: 13px;
    }
    .ios-body {
      padding: 14px 18px 8px;
      max-height: 56vh;
      overflow: auto;
    }
    .ios-card {
      border-radius: 14px;
      border: 1px solid #e6edf7;
      background: #fff;
      padding: 12px 13px;
      margin-bottom: 10px;
    }
    .ios-card h4 {
      margin: 0 0 8px;
      font-size: 15px;
      font-weight: 700;
      color: #102a4c;
    }
    .ios-card p {
      margin: 0;
      color: #334155;
      line-height: 1.7;
      word-break: break-word;
    }
    .ios-section-label {
      margin: 0 0 6px;
      color: #0f294a;
      font-size: 13px;
      font-weight: 700;
    }
    .ios-list {
      margin: 6px 0 8px 18px;
      color: #334155;
    }
    .ios-list li {
      margin: 4px 0;
      line-height: 1.65;
    }
    .ios-list:last-child {
      margin-bottom: 0;
    }
    .ios-empty-note {
      color: #64748b;
      font-size: 13px;
      line-height: 1.7;
    }
    .ios-meta {
      margin-top: 8px;
      color: #64748b;
      font-size: 12px;
    }
    .ios-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 6px;
      margin-bottom: 10px;
    }
    .ios-tag {
      display: inline-flex;
      align-items: center;
      border-radius: 999px;
      font-size: 12px;
      line-height: 1;
      padding: 6px 10px;
      border: 1px solid #e2e8f0;
      background: #f8fafc;
      color: #334155;
    }
    .ios-tag-beta {
      border-color: #bfdbfe;
      background: #eff6ff;
      color: #1d4ed8;
    }
    .ios-tag-stable {
      border-color: #bbf7d0;
      background: #f0fdf4;
      color: #166534;
    }
    .ios-tag-free {
      border-color: #fde68a;
      background: #fffbeb;
      color: #b45309;
    }
    .ios-version-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 9px;
      margin-bottom: 10px;
    }
    .ios-version-item {
      border-radius: 12px;
      border: 1px solid #e6edf7;
      background: #f8fbff;
      padding: 10px 11px;
    }
    .ios-version-item .k {
      color: #62748d;
      font-size: 12px;
      margin-bottom: 4px;
    }
    .ios-version-item .v {
      color: #0f294a;
      font-size: 15px;
      font-weight: 700;
      word-break: break-all;
    }
    .ios-foot {
      padding: 10px 18px 16px;
      border-top: 1px solid #e6edf7;
      background: #fff;
    }
    .ios-check {
      margin: 0 0 10px;
      color: #64748b;
      display: inline-flex;
      align-items: center;
      gap: 6px;
      user-select: none;
      font-size: 13px;
    }
    .ios-buttons {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 8px;
    }
    .ios-btn {
      border: 0;
      border-radius: 12px;
      height: 40px;
      font-size: 14px;
      font-weight: 600;
      cursor: pointer;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      text-decoration: none;
    }
    .ios-btn-ghost {
      background: #e9eef7;
      color: #1e2d44;
    }
    .ios-btn-primary {
      background: #007aff;
      color: #fff;
    }
    .ios-btn-primary:hover {
      background: #0066d6;
      color: #fff;
      text-decoration: none;
    }
    @keyframes iosFadeIn {
      from { opacity: 0; }
      to { opacity: 1; }
    }
    @keyframes iosPop {
      0% { transform: scale(0.76); opacity: 0; }
      100% { transform: scale(1); opacity: 1; }
    }
    @media (max-width: 560px) {
      .ios-box {
        border-radius: 16px;
      }
      .ios-version-grid {
        grid-template-columns: 1fr;
      }
      .ios-buttons {
        grid-template-columns: 1fr;
      }
    }
  </style>
</head>
<body>
<div class="lyear-layout-web">
  <div class="lyear-layout-container">
    <?php include __DIR__ . '/../partials/sidebar.php'; ?>
    <header class="lyear-layout-header">
      <nav class="navbar navbar-default">
        <div class="topbar">
          <div class="topbar-left">
            <div class="lyear-aside-toggler">
              <span class="lyear-toggler-bar"></span>
              <span class="lyear-toggler-bar"></span>
              <span class="lyear-toggler-bar"></span>
            </div>
          </div>
          <ul class="topbar-right">
            <li class="dropdown dropdown-profile">
              <a href="javascript:void(0)" data-toggle="dropdown">
                <img class="img-avatar img-avatar-48" src="<?= e_url($assets . '/images/users/avatar.jpg') ?>" alt="user">
                <span><?= e($user['username'] ?? app_zh('访客')) ?> <span class="caret"></span></span>
              </a>
              <ul class="dropdown-menu dropdown-menu-right">
                <li><a href="<?= e_url(base_url('settings')) ?>"><?= e(app_zh('个人设置')) ?></a></li>
                <li>
                  <form method="post" action="<?= e_url(base_url('logout')) ?>" style="margin:0;">
                    <?= csrf_field() ?>
                    <button type="submit" class="btn btn-link" style="display:block;width:100%;text-align:left;padding:3px 20px;color:#333;text-decoration:none;"><?= e(app_zh('退出登录')) ?></button>
                  </form>
                </li>
              </ul>
            </li>
          </ul>
        </div>
      </nav>
    </header>

    <main class="lyear-layout-content">
      <div class="container-fluid">
        <?php if ($msg = flash('success')): ?>
          <div class="alert alert-success"><?= e($msg) ?></div>
        <?php endif; ?>
        <?php if ($msg = flash('error')): ?>
          <div class="alert alert-danger"><?= e($msg) ?></div>
        <?php endif; ?>
        <?php include __DIR__ . '/../' . $view . '.php'; ?>
      </div>
    </main>
  </div>
</div>

<?php if ($showSiteNotice): ?>
<div class="ios-popup" id="iosSiteNoticePopup" aria-hidden="true">
  <div class="ios-box" role="dialog" aria-modal="true" aria-labelledby="iosSiteTitle">
    <div class="ios-head">
      <h3 id="iosSiteTitle"><?= e(app_zh('系统公告')) ?></h3>
      <p><?= e(app_zh('来自云端公告中心的最新消息')) ?></p>
    </div>
    <div class="ios-body">
      <div class="ios-card">
        <h4><?= $maskText($siteNotice['title'] ?? app_zh('公告')) ?></h4>
        <p><?= nl2br($maskText($siteNotice['content'] ?? '')) ?></p>
        <?php if (!empty($siteNotice['updated_at'])): ?>
          <div class="ios-meta"><?= e(app_zh('更新时间：')) ?> <?= e((string)$siteNotice['updated_at']) ?></div>
        <?php endif; ?>
      </div>
    </div>
    <div class="ios-foot">
      <label class="ios-check">
        <input type="checkbox" id="siteNoticeSkipToday"> <?= e(app_zh('今天不再提醒')) ?>
      </label>
      <div class="ios-buttons">
        <button type="button" class="ios-btn ios-btn-primary" data-popup-close><?= e(app_zh('确定')) ?></button>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>

<?php if ($showUpdateNotice): ?>
<div class="ios-popup" id="iosUpdateNoticePopup" aria-hidden="true">
  <div class="ios-box" role="dialog" aria-modal="true" aria-labelledby="iosUpdateTitle">
    <div class="ios-head">
      <h3 id="iosUpdateTitle"><?= e(app_zh('版本更新提醒')) ?></h3>
      <p><?= e(app_zh('检测到新版本，建议尽快处理')) ?></p>
    </div>
    <div class="ios-body">
      <div class="ios-version-grid">
        <div class="ios-version-item">
          <div class="k"><?= e(app_zh('当前版本')) ?></div>
          <div class="v"><?= e($currentVersion) ?></div>
        </div>
        <div class="ios-version-item">
          <div class="k"><?= e(app_zh('最新版本')) ?></div>
          <div class="v"><?= e($latestVersion) ?></div>
        </div>
      </div>
      <div class="ios-tags">
        <?php if ($updateChannel === 'beta'): ?>
          <span class="ios-tag ios-tag-beta"><?= e(app_zh('测试版通道')) ?></span>
        <?php elseif ($updateChannel === 'paid'): ?>
          <span class="ios-tag ios-tag-stable"><?= e(app_zh('付费版通道')) ?></span>
        <?php elseif ($updateChannel === 'free'): ?>
          <span class="ios-tag ios-tag-free"><?= e(app_zh('免费版通道')) ?></span>
        <?php endif; ?>
        <?php if ($showPointsTag): ?>
          <span class="ios-tag"><?= e(app_zh('更新点')) ?> <?= e((string)$updatePointsCount) ?></span>
        <?php endif; ?>
      </div>
      <div class="ios-card">
        <h4><?= e(app_zh('更新内容')) ?></h4>
        <?php if (!empty($updateItems)): ?>
          <p class="ios-section-label"><?= e(app_zh('更新：')) ?></p>
          <ul class="ios-list">
            <?php foreach ($updateItems as $item): ?>
              <li><?= $maskText($item) ?></li>
            <?php endforeach; ?>
          </ul>
        <?php endif; ?>
        <?php if (!empty($optItems)): ?>
          <p class="ios-section-label"><?= e(app_zh('优化：')) ?></p>
          <ul class="ios-list">
            <?php foreach ($optItems as $item): ?>
              <li><?= $maskText($item) ?></li>
            <?php endforeach; ?>
          </ul>
        <?php endif; ?>
        <?php if (!empty($fixItems)): ?>
          <p class="ios-section-label"><?= e(app_zh('修复：')) ?></p>
          <ul class="ios-list">
            <?php foreach ($fixItems as $item): ?>
              <li><?= $maskText($item) ?></li>
            <?php endforeach; ?>
          </ul>
        <?php endif; ?>
        <?php if (!$hasUpdateDetails): ?>
          <p class="ios-empty-note"><?= e(app_zh('该版本暂未提供详细更新项，可直接前往更新中心处理。')) ?></p>
        <?php endif; ?>
        <?php if (!empty($updateNotice['created_at'])): ?>
          <div class="ios-meta"><?= e(app_zh('发布时间：')) ?> <?= e((string)$updateNotice['created_at']) ?></div>
        <?php endif; ?>
      </div>
    </div>
    <div class="ios-foot">
      <label class="ios-check">
        <input type="checkbox" id="updateNoticeSkipToday"> <?= e(app_zh('今天不再提醒')) ?>
      </label>
      <label class="ios-check">
        <input type="checkbox" id="updateNoticeSkipWeek"> <?= e(app_zh('7天内不再提醒')) ?>
      </label>
      <label class="ios-check">
        <input type="checkbox" id="updateNoticeSkipVersion"> <?= e(app_zh('该版本不再提醒')) ?>
      </label>
      <div class="ios-buttons">
        <button type="button" class="ios-btn ios-btn-ghost" data-popup-close><?= e(app_zh('稍后')) ?></button>
        <a class="ios-btn ios-btn-primary" data-popup-close href="<?= e_url(base_url('admin/system')) ?>"><?= e(app_zh('去更新')) ?></a>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>

<script src="<?= e_url($assets . '/js/jquery.min.js') ?>"></script>
<script src="<?= e_url($assets . '/js/bootstrap.min.js') ?>"></script>
<script src="<?= e_url($assets . '/js/perfect-scrollbar.min.js') ?>"></script>
<script src="<?= e_url($assets . '/js/main.min.js') ?>"></script>

<?php if ($showSiteNotice || $showUpdateNotice): ?>
<script>
(function () {
  var today = new Date().toISOString().slice(0, 10);
  var nowTs = Date.now();
  var weekMs = 7 * 24 * 60 * 60 * 1000;
  var username = <?= app_json_for_html($noticeUser) ?>;
  var scope = location.host + '|' + username;

  function wasSkipped(kind, hash) {
    var foreverKey = 'ly_notice_skip_forever_' + kind + '_' + scope;
    if (localStorage.getItem(foreverKey) === hash) {
      return true;
    }

    var weekKey = 'ly_notice_skip_week_' + kind + '_' + scope;
    var weekRaw = localStorage.getItem(weekKey);
    if (weekRaw) {
      try {
        var weekData = JSON.parse(weekRaw);
        if (weekData && weekData.hash === hash && Number(weekData.until || 0) > nowTs) {
          return true;
        }
        if (weekData && Number(weekData.until || 0) <= nowTs) {
          localStorage.removeItem(weekKey);
        }
      } catch (e) {}
    }

    var sessionKey = 'ly_notice_seen_session_' + kind + '_' + scope + '_' + hash;
    if (sessionStorage.getItem(sessionKey) === '1') {
      return true;
    }

    var dayKey = 'ly_notice_skip_today_' + kind + '_' + scope;
    var dayRaw = localStorage.getItem(dayKey);
    if (!dayRaw) {
      return false;
    }

    try {
      var dayData = JSON.parse(dayRaw);
      if (dayData && dayData.date === today && dayData.hash === hash) {
        sessionStorage.setItem(sessionKey, '1');
        return true;
      }
    } catch (e) {}
    return false;
  }

  function markSeen(kind, hash, skipToday, skipVersion, skipWeek) {
    var sessionKey = 'ly_notice_seen_session_' + kind + '_' + scope + '_' + hash;
    sessionStorage.setItem(sessionKey, '1');
    if (skipToday) {
      var dayKey = 'ly_notice_skip_today_' + kind + '_' + scope;
      localStorage.setItem(dayKey, JSON.stringify({ date: today, hash: hash }));
    }
    if (skipVersion) {
      var foreverKey = 'ly_notice_skip_forever_' + kind + '_' + scope;
      localStorage.setItem(foreverKey, hash);
    }
    if (skipWeek) {
      var weekKey = 'ly_notice_skip_week_' + kind + '_' + scope;
      localStorage.setItem(weekKey, JSON.stringify({ hash: hash, until: Date.now() + weekMs }));
    }
  }

  function showPopup(options, next) {
    if (!options.enabled || wasSkipped(options.kind, options.hash)) {
      next();
      return;
    }

    var popup = document.querySelector(options.popupSelector);
    if (!popup) {
      next();
      return;
    }
    var skipInput = document.querySelector(options.skipSelector);
    var skipWeekInput = options.weekSelector ? document.querySelector(options.weekSelector) : null;
    var skipVersionInput = options.permanentSelector ? document.querySelector(options.permanentSelector) : null;
    var closeButtons = popup.querySelectorAll('[data-popup-close]');
    var done = false;

    function finish() {
      if (done) {
        return;
      }
      done = true;
      markSeen(
        options.kind,
        options.hash,
        !!(skipInput && skipInput.checked),
        !!(skipVersionInput && skipVersionInput.checked),
        !!(skipWeekInput && skipWeekInput.checked)
      );
      popup.classList.remove('is-open');
      popup.setAttribute('aria-hidden', 'true');
      document.body.classList.remove('ios-popup-lock');
      document.removeEventListener('keydown', onEsc);
      popup.removeEventListener('click', onMaskClick);
      closeButtons.forEach(function (btn) {
        btn.removeEventListener('click', finish);
      });
      setTimeout(next, 160);
    }

    function onEsc(e) {
      if (e.key === 'Escape') {
        finish();
      }
    }

    function onMaskClick(e) {
      if (e.target === popup) {
        finish();
      }
    }

    closeButtons.forEach(function (btn) {
      btn.addEventListener('click', finish);
    });
    popup.addEventListener('click', onMaskClick);
    document.addEventListener('keydown', onEsc);

    document.body.classList.add('ios-popup-lock');
    popup.classList.add('is-open');
    popup.setAttribute('aria-hidden', 'false');
  }

  var siteOptions = {
    enabled: <?= app_json_for_html((bool)$showSiteNotice) ?>,
    kind: 'site',
    hash: <?= app_json_for_html($siteNoticeHash) ?>,
    popupSelector: '#iosSiteNoticePopup',
    skipSelector: '#siteNoticeSkipToday',
    weekSelector: '',
    permanentSelector: ''
  };
  var updateOptions = {
    enabled: <?= app_json_for_html((bool)$showUpdateNotice) ?>,
    kind: 'update',
    hash: <?= app_json_for_html($updateNoticeHash) ?>,
    popupSelector: '#iosUpdateNoticePopup',
    skipSelector: '#updateNoticeSkipToday',
    weekSelector: '#updateNoticeSkipWeek',
    permanentSelector: '#updateNoticeSkipVersion'
  };

  var updateSkipVersion = document.querySelector('#updateNoticeSkipVersion');
  var updateSkipToday = document.querySelector('#updateNoticeSkipToday');
  var updateSkipWeek = document.querySelector('#updateNoticeSkipWeek');
  if (updateSkipVersion) {
    updateSkipVersion.addEventListener('change', function () {
      if (!updateSkipVersion.checked) {
        return;
      }
      if (updateSkipToday) {
        updateSkipToday.checked = false;
      }
      if (updateSkipWeek) {
        updateSkipWeek.checked = false;
      }
    });
  }

  showPopup(siteOptions, function () {
    showPopup(updateOptions, function () {});
  });
})();
</script>
<?php endif; ?>

<script>
(function () {
  function applyTableLabels() {
    var tables = document.querySelectorAll('.table');
    tables.forEach(function (table) {
      var heads = table.querySelectorAll('thead th');
      if (!heads.length) {
        return;
      }
      table.querySelectorAll('tbody tr').forEach(function (row) {
        row.querySelectorAll('td').forEach(function (td, idx) {
          if (!td.getAttribute('data-label') && heads[idx]) {
            td.setAttribute('data-label', (heads[idx].textContent || '').trim());
          }
        });
      });
    });
  }

  function lockSubmitButtons() {
    document.querySelectorAll('form').forEach(function (form) {
      form.addEventListener('submit', function (event) {
        var submit = form.querySelector('button[type="submit"], input[type="submit"]');
        if (!submit) {
          return;
        }
        if (submit.dataset.submitting === '1') {
          event.preventDefault();
          return;
        }
        submit.dataset.submitting = '1';
        submit.disabled = true;
        submit.classList.add('is-submitting');
      });
    });
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function () {
      applyTableLabels();
      lockSubmitButtons();
    });
  } else {
    applyTableLabels();
    lockSubmitButtons();
  }
})();
</script>
</body>
</html>
