<?php
/**
 * 图床：上传图片、生成外链 / Markdown / HTML、图床广场
 */
$me = current_user();
if ($me) { feature_guard('gallery'); }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_login();
    check_csrf();
    $act = input('act');

    if ($act === 'upload') {
        try {
            $stored = upload_store('image', 'gallery', ['image' => true, 'max' => 0, 'allow' => image_upload_extensions()]);
            list($quotaOk, $quotaBytes, $usedBytes) = storage_quota_check((int) $me['id'], 'gallery', (int) ($stored['size'] ?? 0));
            if (!$quotaOk) {
                throw new Exception('图床配额不足：已用 ' . format_size($usedBytes) . ' / ' . format_size($quotaBytes));
            }
            $view = image_make_compatible($stored['path']);
            if ($view && $view !== $stored['path']) {
                $stored['path'] = $view;
            }
            $gallerySize = (int) @filesize(APP_ROOT . '/' . $stored['path']);
            if ($gallerySize <= 0) { $gallerySize = (int) ($stored['size'] ?? 0); }
            DB::insert('gallery', [
                'user_id'    => $me['id'],
                'path'       => $stored['path'],
                'title'      => mb_substr(trim((string) ($_POST['title'] ?? '')), 0, 60),
                'size'       => $gallerySize,
                'is_public'  => input('is_public') === '1' ? 1 : 0,
                'created_at' => now(),
            ]);
            flash('图片已上传，可直接复制外链');
        } catch (Exception $e) {
            flash('上传失败：' . $e->getMessage(), 'err');
        }
        redirect(page_url('gallery'));
    }

    if ($act === 'report') {
        $gid = (int) input('id');
        $reason = mb_substr(trim((string) input('reason')), 0, 200);
        $img = DB::one('SELECT * FROM ' . DB::table('gallery') . ' WHERE id = ? AND is_public = 1', [$gid]);
        if (!$img) {
            flash('这张图片不存在或未公开', 'err');
        } elseif (feature_denied($me, 'report')) {
            flash('「举报」功能已被管理员关闭', 'err');
        } elseif ((int) $img['user_id'] === (int) $me['id']) {
            flash('不能举报自己的图片', 'err');
        } else {
            $reportReason = $reason !== '' ? $reason : '未填写原因';
            DB::insert('reports', [
                'target_type' => 'gallery',
                'target_id'   => $gid,
                'user_id'     => (int) $me['id'],
                'reason'      => $reportReason,
                'status'      => 0,
                'created_at'  => now(),
            ]);
            notify_admins_report($me['id'], 'gallery', $gid, $reportReason, $img['title'] !== '' ? $img['title'] : basename((string) $img['path']));
            flash('举报已提交，管理员会尽快处理');
        }
        redirect(page_url('gallery'));
    }

    if ($act === 'delete') {
        $gid = (int) input('id');
        $img = DB::one('SELECT * FROM ' . DB::table('gallery') . ' WHERE id = ?', [$gid]);
        $imgAuthorSuper = $img ? is_superadmin(user_by_id((int) $img['user_id'])) : false;
        if ($img && ((int) $img['user_id'] === (int) $me['id'] || (is_admin(current_user()) && (!$imgAuthorSuper || is_superadmin(current_user()))))) {
            if (strpos($img['path'], 'uploads/') === 0) {
                @unlink(APP_ROOT . '/' . $img['path']);
            }
            DB::delete('gallery', 'id = ?', [$gid]);
            flash('图片已删除');
        } elseif ($img && $imgAuthorSuper) {
            flash('超级管理员分享的图片不能由管理员删除', 'err');
        } else {
            flash('无权删除这张图片', 'err');
        }
        redirect(page_url('gallery'));
    }

    if ($act === 'toggle') {
        $gid = (int) input('id');
        $img = DB::one('SELECT * FROM ' . DB::table('gallery') . ' WHERE id = ? AND user_id = ?', [$gid, $me['id']]);
        if ($img) {
            DB::run('UPDATE ' . DB::table('gallery') . ' SET is_public = ? WHERE id = ?', [(int) $img['is_public'] === 1 ? 0 : 1, $gid]);
        }
        redirect(page_url('gallery'));
    }
}

$myImages = $me ? DB::all('SELECT * FROM ' . DB::table('gallery') . ' WHERE user_id = ? ORDER BY id DESC LIMIT 60', [$me['id']]) : [];
$square = DB::all('SELECT g.*, u.nickname, u.username FROM ' . DB::table('gallery') . ' g
                   LEFT JOIN ' . DB::table('users') . ' u ON u.id = g.user_id
                   WHERE g.is_public = 1 ORDER BY g.id DESC LIMIT 40');

$GLOBALS['PAGE'] = 'gallery';
render_header('图床');
?>
<section class="ext-hero small">
  <span class="hero-kicker">IMAGE HOST</span>
  <h1>图床</h1>
  <p>把图片放在茶室的雪架上，随时取用外链。</p>
</section>

<?php if ($me): ?>
<section class="panel">
  <h2 class="section-title">上传图片</h2>
  <form method="post" enctype="multipart/form-data" class="form-card">
    <?= csrf_field() ?>
    <input type="hidden" name="act" value="upload">
    <div class="upload-drop" data-drop-upload>
      <input type="file" name="image" id="galleryImage" accept="image/*,.heic,.heif,.avif,.tif,.tiff,.ico,.svg" hidden>
      <div class="ud-ico">🖼</div>
      <strong>点击选择图片，或把图片拖到这里</strong>
      <small data-file-name>支持 JPG / PNG / GIF 动图 / WEBP / HEIC / AVIF / SVG 等所有图片格式，不设应用层大小上限</small>
    </div>
    <div class="field-row">
      <div class="field">
        <label>图片名称（可选）</label>
        <input type="text" name="title" maxlength="60">
      </div>
    </div>
    <label class="check-line"><input type="checkbox" name="is_public" value="1" checked> 公开到图床广场</label>
    <button class="btn-primary" type="submit">上传</button>
  </form>
</section>

<?php if ($myImages): ?>
<section class="panel">
  <h2 class="section-title">我的图片 <small><?= count($myImages) ?></small></h2>
  <div class="img-grid">
    <?php foreach ($myImages as $img): $url = full_url($img['path']); ?>
      <figure class="img-cell">
        <a href="<?= e($url) ?>" target="_blank" rel="noopener"><img src="<?= e(upload_url($img['path'])) ?>" alt="<?= e($img['title']) ?>" loading="lazy"></a>
        <figcaption>
          <span class="img-name"><?= e($img['title'] !== '' ? $img['title'] : basename($img['path'])) ?></span>
          <div class="img-ops">
            <button class="btn-mini" type="button" data-gallery-code="link" data-code-value="<?= e($url) ?>">外链</button>
            <button class="btn-mini ghost" type="button" data-gallery-code="md" data-code-value="<?= e('![' . $img['title'] . '](' . $url . ')') ?>">MD</button>
            <button class="btn-mini ghost" type="button" data-gallery-code="html" data-code-value="<?= e('<img src="' . $url . '" alt="' . $img['title'] . '">') ?>">HTML</button>
          </div>
          <div class="img-code-box" hidden>
            <div class="img-code-head"><span class="img-code-label">外链</span><button class="btn-mini" type="button" data-copy-code>复制</button></div>
            <pre class="img-code-text"></pre>
          </div>
          <div class="img-ops">
            <form method="post" class="inline-form">
              <?= csrf_field() ?><input type="hidden" name="act" value="toggle"><input type="hidden" name="id" value="<?= (int) $img['id'] ?>">
              <button class="link-btn" type="submit"><?= (int) $img['is_public'] === 1 ? '设为私密' : '公开' ?></button>
            </form>
            <form method="post" class="inline-form" data-confirm="删除这张图片？">
              <?= csrf_field() ?><input type="hidden" name="act" value="delete"><input type="hidden" name="id" value="<?= (int) $img['id'] ?>">
              <button class="link-btn danger" type="submit">删除</button>
            </form>
          </div>
        </figcaption>
      </figure>
    <?php endforeach; ?>
  </div>
</section>
<?php endif; ?>
<?php else: ?>
  <div class="notice">登录后即可上传图片并使用图床。<a href="<?= e(page_url('login', ['next' => page_url('gallery')])) ?>">去登录</a></div>
<?php endif; ?>

<section class="panel">
  <h2 class="section-title">图床广场</h2>
  <?php if (!$square): ?>
    <?php empty_state('广场还很空', '公开一张图片，让它落在这里'); ?>
  <?php else: ?>
    <div class="img-grid square">
      <?php foreach ($square as $img): ?>
        <figure class="img-cell" id="g<?= (int) $img['id'] ?>">
          <a href="<?= e(upload_url($img['path'])) ?>" target="_blank" rel="noopener">
            <img src="<?= e(upload_url($img['path'])) ?>" alt="<?= e($img['title']) ?>" loading="lazy">
          </a>
          <figcaption>
            <span class="img-name"><?= e($img['title'] !== '' ? $img['title'] : '无题') ?></span>
            <span class="muted">by <?= e(display_name($img)) ?></span>
            <button class="btn-mini" type="button" data-copy="<?= e(full_url($img['path'])) ?>">复制外链</button>
            <?php if ($me && (int) $img['user_id'] !== (int) $me['id']): ?>
              <button class="link-btn report-link-btn" type="button" data-report-open data-report-id="<?= (int) $img['id'] ?>">⚑ 举报</button>
            <?php endif; ?>
          </figcaption>
        </figure>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
</section>

<section class="modal" id="galleryReportModal" hidden>
  <div class="modal-mask" data-report-close></div>
  <div class="modal-card report-modal-card">
    <div class="report-modal-head">
      <h3>举报这张图片</h3>
      <button class="readers-close" type="button" data-report-close aria-label="关闭">×</button>
    </div>
    <form method="post" class="form-card">
      <?= csrf_field() ?>
      <input type="hidden" name="act" value="report">
      <input type="hidden" name="id" value="0" data-report-id-input>
      <label>举报原因（可选）</label>
      <textarea name="reason" maxlength="200" rows="3" placeholder="请说明这张图片的问题"></textarea>
      <div class="report-modal-actions">
        <button type="button" class="btn-mini ghost" data-report-close>取消</button>
        <button type="submit" class="btn-mini danger">提交举报</button>
      </div>
    </form>
  </div>
</section>
<script>
(function () {
  var modal = document.getElementById('galleryReportModal');
  if (!modal) return;
  var idInput = modal.querySelector('[data-report-id-input]');
  document.addEventListener('click', function (e) {
    var open = e.target.closest('[data-report-open]');
    if (open) {
      e.preventDefault();
      if (idInput) idInput.value = open.getAttribute('data-report-id') || '0';
      modal.hidden = false;
      return;
    }
    if (e.target.closest('[data-report-close]') || e.target === modal) {
      modal.hidden = true;
    }
  });
  document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape') modal.hidden = true;
  });
})();
</script>
<?php render_footer(); ?>