<?php
$cfg = app_config();
$mask = static function ($value): string {
    return e(app_mask_sensitive_text((string)$value));
};

$latest = is_array($update_latest ?? null) ? $update_latest : [];
$logs = is_array($migration_logs ?? null) ? $migration_logs : [];
$updateItems = station_release_note_items($latest['update_note'] ?? ($latest['update_items'] ?? ''));
$optItems = station_release_note_items($latest['optimize_note'] ?? ($latest['optimize_items'] ?? ''));
$fixItems = station_release_note_items($latest['fix_note'] ?? ($latest['fix_items'] ?? ''));
$releaseChannel = station_front_release_channel_normalize((string)($latest['release_channel'] ?? ($latest['channel'] ?? '')));
$summaryCount = count($updateItems) + count($optItems) + count($fixItems);
?>

<style>
  .sys-hero {
    border: 1px solid #d9e8ff;
    border-radius: 16px;
    padding: 16px 18px;
    margin-bottom: 16px;
    background: linear-gradient(135deg, #f7fbff 0%, #eef5ff 100%);
  }
  .sys-hero h4 {
    margin: 0 0 4px;
    color: #0f2e65;
    font-weight: 700;
  }
  .sys-hero p {
    margin: 0;
    color: #486a97;
  }
  .sys-alert-top {
    border-radius: 12px;
    margin-bottom: 14px;
  }
  .sys-alert-wrap {
    position: sticky;
    top: 8px;
    z-index: 20;
  }
  .sys-card {
    border-radius: 16px;
    border: 1px solid #e5edf8;
    box-shadow: 0 10px 30px rgba(16, 24, 40, 0.04);
  }
  .sys-card .card-header h4 {
    margin: 0;
    font-weight: 700;
  }
  .sys-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
    margin-bottom: 12px;
  }
  .sys-box {
    border: 1px solid #e7eef9;
    border-radius: 12px;
    padding: 12px;
    background: #f8fbff;
  }
  .sys-box .label {
    display: inline-block;
    margin-bottom: 4px;
    color: #54719a;
    font-size: 12px;
    font-weight: 600;
  }
  .sys-box .value {
    color: #17325d;
    font-size: 16px;
    font-weight: 700;
    word-break: break-all;
  }
  .sys-actions {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    margin-bottom: 10px;
  }
  .sys-note {
    color: #5f7088;
    margin: 4px 0;
  }
  .sys-list {
    margin: 6px 0 10px 16px;
    padding: 0;
    color: #314a72;
  }
  .sys-list li {
    margin: 4px 0;
  }
  .sys-badge-ok {
    color: #0f766e;
    background: #e6fffb;
    border: 1px solid #a7f3d0;
    border-radius: 999px;
    padding: 3px 10px;
    font-size: 12px;
    font-weight: 700;
  }
  .sys-badge-warn {
    color: #9a3412;
    background: #fff7ed;
    border: 1px solid #fdba74;
    border-radius: 999px;
    padding: 3px 10px;
    font-size: 12px;
    font-weight: 700;
  }
  .sys-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    margin: 8px 0 4px;
  }
  .sys-tag {
    display: inline-flex;
    align-items: center;
    border-radius: 999px;
    border: 1px solid #dbe6f5;
    background: #f6fafe;
    color: #334e77;
    padding: 2px 10px;
    font-size: 12px;
    font-weight: 600;
  }
  .sys-tag-stable {
    border-color: #bbf7d0;
    background: #f0fdf4;
    color: #166534;
  }
  .sys-tag-free {
    border-color: #fde68a;
    background: #fffbeb;
    color: #b45309;
  }
  .sys-tag-beta {
    border-color: #bfdbfe;
    background: #eff6ff;
    color: #1d4ed8;
  }
  @media (max-width: 900px) {
    .sys-grid {
      grid-template-columns: 1fr;
    }
  }
</style>

<div class="row">
  <div class="col-md-12">
    <div class="sys-hero">
      <h4><?= e(app_zh('系统设置与更新中心')) ?></h4>
      <p><?= e(app_zh('已启用安全更新链路，页面展示内容会自动隐藏敏感外部链接和域名明文。')) ?></p>
    </div>

    <?php if (!empty($update_error)): ?>
      <div class="sys-alert-wrap">
        <div class="alert alert-danger sys-alert-top"><?= $mask($update_error) ?></div>
      </div>
    <?php endif; ?>
    <?php if (!empty($update_success)): ?>
      <div class="sys-alert-wrap">
        <div class="alert alert-success sys-alert-top"><?= $mask($update_success) ?></div>
      </div>
    <?php endif; ?>
  </div>

  <div class="col-md-12">
    <div class="card sys-card">
      <div class="card-header"><h4><?= e(app_zh('基础配置')) ?></h4></div>
      <div class="card-body">
        <form method="post" action="<?= e_url(base_url('admin/system')) ?>">
          <?= csrf_field() ?>

          <div class="form-group">
            <label><?= e(app_zh('项目名称')) ?></label>
            <input class="form-control" name="app_name" value="<?= e((string)($app_name ?? '')) ?>">
          </div>

          <div class="form-group">
            <label><?= e(app_zh('卡密单价（每行格式：小时=价格）')) ?></label>
            <textarea class="form-control" name="key_prices" rows="5" placeholder="1=0&#10;24=10"><?= e((string)($price_lines ?? '')) ?></textarea>
          </div>

          <div class="form-group">
            <label><?= e(app_zh('远程更新授权')) ?></label>
            <div class="sys-note"><?= e(app_zh('当前为域名授权模式，由远程服务端控制本站是否可更新。')) ?></div>
            <small style="color:#7c8aa0;"><?= e(app_zh('本页不显示也不保存任何远程服务域名明文。')) ?></small>
          </div>

          <div class="form-group">
            <label>MOD <?= e(app_zh('名称')) ?></label>
            <input class="form-control" name="mod_name" value="<?= e((string)($system['mod_name'] ?? '')) ?>">
          </div>

          <div class="form-group">
            <label>MOD <?= e(app_zh('状态')) ?></label>
            <select class="form-control" name="mod_status">
              <option value="on" <?= ($system['mod_status'] ?? 'on') === 'on' ? 'selected' : '' ?>><?= e(app_zh('开启')) ?></option>
              <option value="off" <?= ($system['mod_status'] ?? 'on') === 'off' ? 'selected' : '' ?>><?= e(app_zh('关闭')) ?></option>
            </select>
          </div>

          <div class="form-group">
            <label><?= e(app_zh('公告状态')) ?></label>
            <input class="form-control" name="notice_status" value="<?= e((string)($system['notice_status'] ?? '')) ?>" placeholder="<?= e(app_zh('例如：版本更新中')) ?>">
          </div>

          <div class="form-group">
            <label><?= e(app_zh('公告内容')) ?></label>
            <textarea class="form-control" name="notice_text" rows="3" placeholder="<?= e(app_zh('请输入公告内容')) ?>"><?= e((string)($system['notice_text'] ?? '')) ?></textarea>
          </div>

          <div class="form-group">
            <label><?= e(app_zh('维护原因')) ?></label>
            <input class="form-control" name="maintenance_reason" value="<?= e((string)($system['maintenance_reason'] ?? '')) ?>" placeholder="<?= e(app_zh('系统维护中')) ?>">
          </div>

          <div class="form-group">
            <label><?= e(app_zh('用户自助解绑')) ?></label>
            <select class="form-control" name="allow_self_unbind">
              <option value="0" <?= empty($system['allow_self_unbind']) ? 'selected' : '' ?>><?= e(app_zh('关闭')) ?></option>
              <option value="1" <?= !empty($system['allow_self_unbind']) ? 'selected' : '' ?>><?= e(app_zh('开启')) ?></option>
            </select>
            <small style="color:#7c8aa0;"><?= e(app_zh('开启后，用户可在查卡页面自助解绑设备。')) ?></small>
          </div>

          <button class="btn btn-primary" type="submit"><?= e(app_zh('保存设置')) ?></button>
        </form>
      </div>
    </div>
  </div>

  <div class="col-md-12">
    <div class="card sys-card">
      <div class="card-header"><h4><?= e(app_zh('版本检测')) ?></h4></div>
      <div class="card-body">
        <div class="sys-grid">
          <div class="sys-box">
            <div class="label"><?= e(app_zh('当前版本')) ?></div>
            <div class="value"><?= e((string)($app_version ?? '0.0.0')) ?></div>
          </div>
          <div class="sys-box">
            <div class="label"><?= e(app_zh('最新可用版本')) ?></div>
            <div class="value"><?= e((string)($latest['version'] ?? app_zh('未检测'))) ?></div>
          </div>
        </div>

        <?php if (!empty($latest)): ?>
          <div class="sys-box" style="margin-bottom:10px;">
            <div><span class="sys-badge-ok"><?= e(app_zh('更新摘要')) ?></span></div>
            <div class="sys-tags">
              <?php if ($releaseChannel === 'free'): ?>
                <span class="sys-tag sys-tag-free"><?= e(app_zh('免费版通道')) ?></span>
              <?php elseif ($releaseChannel === 'paid'): ?>
                <span class="sys-tag sys-tag-stable"><?= e(app_zh('付费版通道')) ?></span>
              <?php elseif ($releaseChannel === 'beta'): ?>
                <span class="sys-tag sys-tag-beta"><?= e(app_zh('测试版通道')) ?></span>
              <?php endif; ?>
              <?php if ($summaryCount > 0): ?>
                <span class="sys-tag"><?= e(app_zh('更新点')) ?> <?= e((string)$summaryCount) ?></span>
              <?php endif; ?>
            </div>
            <?php if (!empty($updateItems)): ?>
              <p class="sys-note"><strong><?= e(app_zh('更新：')) ?></strong></p>
              <ul class="sys-list">
                <?php foreach ($updateItems as $item): ?>
                  <li><?= $mask($item) ?></li>
                <?php endforeach; ?>
              </ul>
            <?php endif; ?>
            <?php if (!empty($optItems)): ?>
              <p class="sys-note"><strong><?= e(app_zh('优化：')) ?></strong></p>
              <ul class="sys-list">
                <?php foreach ($optItems as $item): ?>
                  <li><?= $mask($item) ?></li>
                <?php endforeach; ?>
              </ul>
            <?php endif; ?>
            <?php if (!empty($fixItems)): ?>
              <p class="sys-note"><strong><?= e(app_zh('修复：')) ?></strong></p>
              <ul class="sys-list">
                <?php foreach ($fixItems as $item): ?>
                  <li><?= $mask($item) ?></li>
                <?php endforeach; ?>
              </ul>
            <?php endif; ?>
            <?php if (empty($updateItems) && empty($optItems) && empty($fixItems)): ?>
              <p class="sys-note"><?= e(app_zh('该版本暂未提供详细更新项。')) ?></p>
            <?php endif; ?>
          </div>
        <?php endif; ?>

        <div class="sys-actions">
          <form method="post" action="<?= e_url(base_url('admin/update/check')) ?>">
            <?= csrf_field() ?>
            <button class="btn btn-default" type="submit"><?= e(app_zh('检测更新')) ?></button>
          </form>
          <form method="post" action="<?= e_url(base_url('admin/update/apply')) ?>" onsubmit="return confirm('<?= e(app_zh('确认执行在线更新？建议先备份站点和数据库。')) ?>');">
            <?= csrf_field() ?>
            <button class="btn btn-primary" type="submit"><?= e(app_zh('立即更新')) ?></button>
          </form>
          <a class="btn btn-default" href="<?= e_url(base_url('admin/update-debug')) ?>"><?= e(app_zh('更新调试')) ?></a>
        </div>

        <p class="sys-note"><?= e(app_zh('支持在线更新，更新前建议先备份站点文件和数据库。')) ?></p>
      </div>
    </div>
  </div>

  <div class="col-md-12">
    <div class="card sys-card">
      <div class="card-header"><h4><?= e(app_zh('数据库迁移日志')) ?></h4></div>
      <div class="card-body">
        <?php if (empty($logs)): ?>
          <p style="color:#6b7280;margin:0;"><?= e(app_zh('暂无迁移记录')) ?></p>
        <?php else: ?>
          <div class="table-responsive">
            <table class="table table-bordered table-hover">
              <thead>
                <tr>
                  <th><?= e(app_zh('时间')) ?></th>
                  <th><?= e(app_zh('版本')) ?></th>
                  <th><?= e(app_zh('状态')) ?></th>
                  <th><?= e(app_zh('耗时(ms)')) ?></th>
                  <th><?= e(app_zh('SQL条数')) ?></th>
                  <th><?= e(app_zh('信息')) ?></th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($logs as $row): ?>
                  <tr>
                    <td><?= e((string)($row['started_at'] ?? '')) ?></td>
                    <td><?= e((string)($row['version'] ?? '')) ?></td>
                    <td>
                      <?php if (($row['status'] ?? '') === 'success'): ?>
                        <span class="sys-badge-ok"><?= e(app_zh('成功')) ?></span>
                      <?php elseif (($row['status'] ?? '') === 'skipped'): ?>
                        <span class="sys-badge-warn"><?= e(app_zh('跳过')) ?></span>
                      <?php else: ?>
                        <span class="badge-status badge-danger"><?= e(app_zh('失败')) ?></span>
                      <?php endif; ?>
                    </td>
                    <td><?= e((string)($row['duration_ms'] ?? 0)) ?></td>
                    <td><?= e((string)($row['statement_count'] ?? 0)) ?></td>
                    <td style="max-width:560px;word-break:break-all;">
                      <?= $mask((string)($row['error'] ?? '')) ?>
                      <?php if (!empty($row['statement_index'])): ?>
                        <br><small><?= e(app_zh('语句序号：')) ?><?= e((string)$row['statement_index']) ?></small>
                      <?php endif; ?>
                      <?php if (!empty($row['statement_preview'])): ?>
                        <br><small><?= e((string)$row['statement_preview']) ?></small>
                      <?php endif; ?>
                    </td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>
