<?php
declare(strict_types=1);

/**
 * /functional/video/index.php
 * "Мої відеозаписи":
 * - відеотека з превʼю та назвою
 * - завантаження відео (до 500MB/файл), квота 10GB/користувача
 * - видалення відео
 * - layout як у /functional/files/index.php: feed-layout + sidebar-sticky + blocks/profile.php + blocks/groups.php
 *
 * Оптимізація:
 * - квота через mv_user_used_bytes() (SUM(size_bytes) + fallback по FS)
 * - пагінація замість LIMIT 200
 * - SELECT тільки потрібних колонок (без *)
 *
 * 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;

/* ===== quota ===== */
$quotaMax = MV_QUOTA_MAX_BYTES; // 10GB
// ensure dir (також дає fallback для підрахунку по FS)
[$fsDir, $webDir, $safeU] = mv_ensure_video_dir((string)($me['username'] ?? 'user'));

$usedBytes = mv_user_used_bytes($pdo, (int)($me['id'] ?? 0), $fsDir);
$freeBytes = mv_quota_left_bytes($usedBytes);
$usedPct   = $quotaMax > 0 ? (int)min(100, round($usedBytes * 100 / $quotaMax)) : 0;

/* ===== pagination ===== */
$page = (int)($_GET['page'] ?? 1);
if ($page < 1) $page = 1;

$perPage = 24;
$offset  = ($page - 1) * $perPage;

$total = 0;
$videos = [];

try {
  if (db_has_table($pdo, 'myvideos')) {
    $st = $pdo->prepare("SELECT COUNT(*) FROM myvideos WHERE user_id=?");
    $st->execute([(int)$me['id']]);
    $total = (int)$st->fetchColumn();

    $st = $pdo->prepare("
      SELECT id, title, mime, size_bytes, created_at
      FROM myvideos
      WHERE user_id=?
      ORDER BY created_at DESC, id DESC
      LIMIT {$perPage} OFFSET {$offset}
    ");
    $st->execute([(int)$me['id']]);
    $videos = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
  }
} catch (Throwable $e) {
  $total = 0;
  $videos = [];
}

$pages = $total > 0 ? (int)max(1, ceil($total / $perPage)) : 1;
if ($page > $pages) $page = $pages;

$err = flash_get('err');
$ok  = flash_get('ok');

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

/* canonical без параметрів */
$canonical = function_exists('abs_url') ? abs_url('/functional/video/') : '/functional/video/';

/* приватна сторінка */
$seo_noindex = true;

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

$csrf = csrf_token();

/* small dt format */
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);
}

$baseList = '/functional/video/';
function mv_page_url(int $p): string {
  $p = max(1, $p);
  return $p <= 1 ? '/functional/video/' : ('/functional/video/?page=' . $p);
}
?>

<style>
.mv-grid{
  display:grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 14px;
}
@media (max-width: 1200px){ .mv-grid{ grid-template-columns: repeat(3, minmax(0, 1fr)); } }
@media (max-width: 992px){ .mv-grid{ grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 576px){ .mv-grid{ grid-template-columns: 1fr; } }

.mv-card{
  border:1px solid rgba(0,0,0,.08);
  border-radius:14px;
  overflow:hidden;
  background:#fff;
}
.mv-thumb-wrap{
  position:relative;
  aspect-ratio: 16/9;
  background:#000;
}
.mv-thumb{
  width:100%;
  height:100%;
  object-fit:cover;
  display:block;
}
.mv-body{
  padding:10px 12px 12px;
}
.mv-title{
  font-weight:600;
  line-height:1.25;
  margin:0 0 6px;
  font-size:14px;
  word-break: break-word;
}
.mv-meta{
  color:#6c757d;
  font-size:12px;
  display:flex;
  justify-content:space-between;
  gap:10px;
  flex-wrap:wrap;
}
.mv-actions{
  margin-top:10px;
  display:flex;
  gap:8px;
  flex-wrap:wrap;
}
.mv-upload-row{
  display:grid;
  grid-template-columns: 1fr 1fr auto;
  gap:10px;
  align-items:end;
}
@media (max-width: 992px){
  .mv-upload-row{ grid-template-columns: 1fr; }
}
.mv-pager{
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:10px;
  flex-wrap:wrap;
}
</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-start justify-content-between flex-wrap gap-3">
            <div>
              <h1 class="h4 mb-1"><?= h(mv_t('title', $lang)) ?></h1>
              <div class="small text-muted"><?= h(mv_t('quota10', $lang)) ?></div>
            </div>

            <div style="min-width:320px">
              <div class="small text-muted mb-1">
                <?= h(mv_t('used', $lang)) ?>: <b><?= h(mv_format_bytes($usedBytes)) ?></b>
                <?= h(mv_t('of', $lang)) ?> <b><?= h(mv_format_bytes($quotaMax)) ?></b>
                • <?= h(mv_t('free', $lang)) ?>: <b><?= h(mv_format_bytes($freeBytes)) ?></b>
              </div>
              <div class="progress" style="height:10px;">
                <div class="progress-bar" role="progressbar"
                     style="width: <?= (int)$usedPct ?>%;"
                     aria-valuenow="<?= (int)$usedPct ?>" aria-valuemin="0" aria-valuemax="100"></div>
              </div>
            </div>
          </div>

          <?php if ($err): ?>
            <div class="alert alert-danger mt-3 mb-0"><?= h($err) ?></div>
          <?php endif; ?>

          <?php if ($ok): ?>
            <div class="alert alert-success mt-3 mb-0"><?= h($ok) ?></div>
          <?php endif; ?>

        </div>
      </div>

      <!-- Upload -->
      <div class="card mb-3">
        <div class="card-body">
          <div class="fw-semibold mb-2"><?= h(mv_t('upload', $lang)) ?></div>

          <form action="/functional/video/upload.php" method="post" enctype="multipart/form-data" id="mvUploadForm">
            <input type="hidden" name="csrf" value="<?= h($csrf) ?>">

            <div id="mvRows" class="d-grid gap-2">
              <div class="mv-upload-row">
                <div>
                  <label class="form-label mb-1 small text-muted"><?= h(mv_t('video_title', $lang)) ?></label>
                  <input class="form-control form-control-sm" type="text" name="title[]" maxlength="190" required>
                </div>
                <div>
                  <label class="form-label mb-1 small text-muted"><?= h(mv_t('choose_file', $lang)) ?></label>
                  <input class="form-control form-control-sm" type="file" name="video[]" accept="video/*" required>
                  <div class="form-text"><?= h(mv_t('max500', $lang)) ?></div>
                </div>
                <div>
                  <button class="btn btn-sm btn-outline-danger" type="button" onclick="mvRemoveRow(this)">✕</button>
                </div>
              </div>
            </div>

            <div class="d-flex gap-2 flex-wrap mt-2">
              <button class="btn btn-sm btn-outline-secondary" type="button" onclick="mvAddRow()">
                <?= h(mv_t('add_row', $lang)) ?>
              </button>
              <button class="btn btn-sm btn-primary" type="submit">
                <?= h(mv_t('upload', $lang)) ?>
              </button>
            </div>
          </form>
        </div>
      </div>

      <!-- Library -->
      <div class="card">
        <div class="card-body">
          <div class="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-3">
            <div class="fw-semibold"><?= h(mv_t('library', $lang)) ?></div>
            <?php if ($total > 0): ?>
              <div class="small text-muted">
                <?= (int)$total ?> • <?= (int)$page ?>/<?= (int)$pages ?>
              </div>
            <?php endif; ?>
          </div>

          <?php if (!$videos): ?>
            <div class="text-muted"><?= h(mv_t('empty', $lang)) ?></div>
          <?php else: ?>
            <div class="mv-grid">
              <?php foreach ($videos as $v): ?>
                <?php
                  $vid   = (int)($v['id'] ?? 0);
                  $mime  = (string)($v['mime'] ?? 'video/mp4');
                  $watch = '/functional/video/watch.php?id=' . $vid . '&lang=' . urlencode($langNow);
                  $src   = '/functional/video/stream.php?id=' . $vid;
                ?>
                <div class="mv-card">
                  <a class="mv-thumb-wrap" href="<?= h($watch) ?>" style="display:block;text-decoration:none;">
                    <video class="mv-thumb" preload="metadata" muted playsinline data-mv-thumb="1">
                      <source src="<?= h($src) ?>" type="<?= h($mime) ?>">
                    </video>
                  </a>
                  <div class="mv-body">
                    <p class="mv-title"><?= h((string)($v['title'] ?? '')) ?></p>
                    <div class="mv-meta">
                      <span><?= h(mv_format_bytes((int)($v['size_bytes'] ?? 0))) ?></span>
                      <span><?= h(mv_fmt_dt((string)($v['created_at'] ?? ''))) ?></span>
                    </div>
                    <div class="mv-actions">
                      <a class="btn btn-sm btn-outline-primary" href="<?= h($watch) ?>">
                        <?= h(mv_t('watch', $lang)) ?>
                      </a>
                      <form action="/functional/video/delete.php" method="post"
                            onsubmit="return confirm(<?= json_encode(mv_t('confirm_del', $lang), JSON_UNESCAPED_UNICODE) ?>);">
                        <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
                        <input type="hidden" name="id" value="<?= $vid ?>">
                        <button class="btn btn-sm btn-outline-danger" type="submit"><?= h(mv_t('delete', $lang)) ?></button>
                      </form>
                    </div>
                  </div>
                </div>
              <?php endforeach; ?>
            </div>

            <?php if ($pages > 1): ?>
              <div class="mv-pager mt-3">
                <div>
                  <?php if ($page > 1): ?>
                    <a class="btn btn-sm btn-outline-secondary" href="<?= h(mv_page_url($page - 1)) ?>">
                      ← <?= h(mv_t('prev', $lang)) ?>
                    </a>
                  <?php endif; ?>
                </div>
                <div>
                  <?php if ($page < $pages): ?>
                    <a class="btn btn-sm btn-outline-secondary" href="<?= h(mv_page_url($page + 1)) ?>">
                      <?= h(mv_t('next', $lang)) ?> →
                    </a>
                  <?php endif; ?>
                </div>
              </div>
            <?php endif; ?>

          <?php endif; ?>

        </div>
      </div>

    </div>
  </section>

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

<script>
(function(){
  const MV_TX = {
    titleLabel: <?= json_encode(mv_t('video_title', $lang), JSON_UNESCAPED_UNICODE) ?>,
    fileLabel:  <?= json_encode(mv_t('choose_file', $lang), JSON_UNESCAPED_UNICODE) ?>,
    maxText:    <?= json_encode(mv_t('max500', $lang), JSON_UNESCAPED_UNICODE) ?>,
    minRows: 1,
    maxRows: 10
  };

  window.mvAddRow = function(){
    var wrap = document.getElementById('mvRows');
    if(!wrap) return;

    var rows = wrap.querySelectorAll('.mv-upload-row');
    if(rows.length >= MV_TX.maxRows) return;

    var div = document.createElement('div');
    div.className = 'mv-upload-row';
    div.innerHTML =
      '<div>' +
        '<label class="form-label mb-1 small text-muted">' + MV_TX.titleLabel + '</label>' +
        '<input class="form-control form-control-sm" type="text" name="title[]" maxlength="190" required>' +
      '</div>' +
      '<div>' +
        '<label class="form-label mb-1 small text-muted">' + MV_TX.fileLabel + '</label>' +
        '<input class="form-control form-control-sm" type="file" name="video[]" accept="video/*" required>' +
        '<div class="form-text">' + MV_TX.maxText + '</div>' +
      '</div>' +
      '<div>' +
        '<button class="btn btn-sm btn-outline-danger" type="button" onclick="mvRemoveRow(this)">✕</button>' +
      '</div>';

    wrap.appendChild(div);
  };

  window.mvRemoveRow = function(btn){
    var rows = document.querySelectorAll('#mvRows .mv-upload-row');
    if(rows.length <= MV_TX.minRows) return; // мінімум 1 рядок
    var row = btn && btn.closest ? btn.closest('.mv-upload-row') : null;
    if(row) row.remove();
  };

  // "превʼю" — підтягуємо перший кадр
  var vids = document.querySelectorAll('video[data-mv-thumb="1"]');
  vids.forEach(function(v){
    v.addEventListener('loadedmetadata', function(){
      try { v.currentTime = 0.2; } catch(e) {}
    }, { once:true });
  });
})();
</script>

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