<?php
declare(strict_types=1);

/**
 * /functional/video/watch.php
 * Перегляд відео:
 * - відеоплеєр (стрім через stream.php з Range)
 * - попереднє/наступне
 * - видалення
 *
 * Оптимізація/безпека:
 * - SELECT тільки потрібних колонок (без *)
 * - noindex headers через mv_private_seo_headers()
 * - коректний confirm через json_encode (без ламання лапками)
 *
 * SEO:
 * - приватна сторінка (тільки власник) => завжди noindex,nofollow
 */

require_once __DIR__ . '/../../includes/start.php';

$pdo = db();
$me  = current_user();
$u   = $me;

require_once __DIR__ . '/_lib.php';

require_login();
mv_private_seo_headers();

if (!headers_sent()) {
  header('X-Content-Type-Options: nosniff', true);
  header('Cache-Control: no-store, max-age=0', true);
}

$GLOBALS['mv_lang'] = mv_detect_lang($me);
$lang = (string)$GLOBALS['mv_lang'];

$langNow = function_exists('lang') ? (string)lang() : $lang;
if (!in_array($langNow, ['uk','ru','en'], true)) $langNow = $lang;

function mv_fmt_dt(string $s): string {
  $s = trim($s);
  if ($s === '') return '';
  $ts = strtotime($s);
  if ($ts <= 0) return $s;
  return date('d.m.Y H:i', $ts);
}

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
  flash_set('err', mv_t('not_found', $lang));
  redirect('/functional/video/');
}

$userId = (int)($me['id'] ?? 0);
if ($userId <= 0) {
  redirect('/login.php');
}

/* video */
$st = $pdo->prepare("
  SELECT id, user_id, title, mime, size_bytes, created_at
  FROM myvideos
  WHERE id=? AND user_id=?
  LIMIT 1
");
$st->execute([$id, $userId]);
$video = $st->fetch(PDO::FETCH_ASSOC);

if (!$video) {
  flash_set('err', mv_t('not_found', $lang));
  redirect('/functional/video/');
}

/* prev (newer in DESC list) */
$st = $pdo->prepare("
  SELECT id
  FROM myvideos
  WHERE user_id=?
    AND (created_at > ? OR (created_at = ? AND id > ?))
  ORDER BY created_at ASC, id ASC
  LIMIT 1
");
$st->execute([$userId, (string)$video['created_at'], (string)$video['created_at'], (int)$video['id']]);
$prevId = (int)($st->fetchColumn() ?: 0);

/* next (older in DESC list) */
$st = $pdo->prepare("
  SELECT id
  FROM myvideos
  WHERE user_id=?
    AND (created_at < ? OR (created_at = ? AND id < ?))
  ORDER BY created_at DESC, id DESC
  LIMIT 1
");
$st->execute([$userId, (string)$video['created_at'], (string)$video['created_at'], (int)$video['id']]);
$nextId = (int)($st->fetchColumn() ?: 0);

/* =========================
   SEO (перед header)
========================= */
$title = (string)($video['title'] ?? mv_t('title', $lang));
$meta_desc = mv_t('title', $lang);
$meta_robots = 'noindex, nofollow, noarchive, nosnippet';

/* canonical (формально), але все одно noindex */
$canonical = function_exists('abs_url')
  ? abs_url('/functional/video/watch.php?id=' . (int)$video['id'])
  : ('/functional/video/watch.php?id=' . (int)$video['id']);

/* завжди noindex */
$seo_noindex = true;

/* ===== header ===== */
require __DIR__ . '/../../includes/header.php';

$csrf = csrf_token();

$confirmDel = mv_t('confirm_del', $lang);

$vidId = (int)$video['id'];
$mime  = (string)($video['mime'] ?? 'video/mp4');
$mime  = trim(explode(';', $mime, 2)[0]);
if (!in_array($mime, mv_allowed_video_mimes(), true)) {
  $mime = 'video/mp4';
}
?>
<style>
.mv-player{
  width:100%;
  max-height: 70vh;
  background:#000;
  border-radius:14px;
}
</style>

<div class="feed-layout">
  <aside>
    <div class="sidebar-sticky">
      <?php require __DIR__ . '/../../blocks/profile.php'; ?>
    </div>
  </aside>

  <section>
    <div class="container my-4">

      <div class="card mb-3">
        <div class="card-body">

          <div class="d-flex align-items-center justify-content-between flex-wrap gap-2">
            <div>
              <div class="small text-muted mb-1"><?= h(mv_t('title', $lang)) ?></div>
              <h1 class="h5 mb-0"><?= h((string)$video['title']) ?></h1>
            </div>

            <div class="d-flex gap-2 flex-wrap">
              <a class="btn btn-sm btn-outline-secondary" href="/functional/video/?lang=<?= h($langNow) ?>">
                <?= h(mv_t('back', $lang)) ?>
              </a>

              <?php if ($prevId > 0): ?>
                <a class="btn btn-sm btn-outline-primary" href="/functional/video/watch.php?id=<?= (int)$prevId ?>&lang=<?= h($langNow) ?>">
                  ← <?= h(mv_t('prev', $lang)) ?>
                </a>
              <?php else: ?>
                <button class="btn btn-sm btn-outline-primary" type="button" disabled>
                  ← <?= h(mv_t('prev', $lang)) ?>
                </button>
              <?php endif; ?>

              <?php if ($nextId > 0): ?>
                <a class="btn btn-sm btn-outline-primary" href="/functional/video/watch.php?id=<?= (int)$nextId ?>&lang=<?= h($langNow) ?>">
                  <?= h(mv_t('next', $lang)) ?> →
                </a>
              <?php else: ?>
                <button class="btn btn-sm btn-outline-primary" type="button" disabled>
                  <?= h(mv_t('next', $lang)) ?> →
                </button>
              <?php endif; ?>

              <form action="/functional/video/delete.php" method="post"
                    onsubmit="return confirm(<?= json_encode($confirmDel, JSON_UNESCAPED_UNICODE) ?>);">
                <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
                <input type="hidden" name="id" value="<?= (int)$video['id'] ?>">
                <button class="btn btn-sm btn-outline-danger" type="submit">
                  <?= h(mv_t('delete', $lang)) ?>
                </button>
              </form>
            </div>
          </div>

          <hr>

          <video class="mv-player" controls preload="metadata" playsinline>
            <source src="/functional/video/stream.php?id=<?= (int)$vidId ?>" type="<?= h($mime) ?>">
          </video>

          <div class="mt-3 d-flex flex-wrap gap-3 small text-muted">
            <div><b><?= h(mv_t('size', $lang)) ?>:</b> <?= h(mv_format_bytes((int)($video['size_bytes'] ?? 0))) ?></div>
            <div><b><?= h(mv_t('created', $lang)) ?>:</b> <?= h(mv_fmt_dt((string)($video['created_at'] ?? ''))) ?></div>
          </div>

        </div>
      </div>

    </div>
  </section>

  <aside>
    <div class="sidebar-sticky">
      <?php require __DIR__ . '/../../blocks/groups.php'; ?>
    </div>
  </aside>
</div>

<?php require __DIR__ . '/../../includes/footer.php'; ?>