<?php
declare(strict_types=1);

/**
 * /functional/files/index.php
 * "Мої файли":
 * - перегляд папок і файлів
 * - завантаження (до 50MB/файл)
 * - квота 1GB на користувача
 * - share-link (token) + перемикач public/private
 * - видалення файлів і папок (папку можна видалити лише якщо порожня)
 * - layout як у group/view.php: feed-layout + sidebar-sticky + blocks/profile.php + blocks/groups.php
 * - UI: Upload + Create folder + Folders -> НАД Files, а Files на всю ширину
 *
 * SEO: персональний розділ => noindex
 */

require_once dirname(__DIR__, 2) . '/includes/start.php';

/** @var PDO|null $pdo */
/** @var array|null $me */
$pdo = (isset($pdo) && $pdo instanceof PDO) ? $pdo : db();
$me  = $me ?? current_user();
$u   = $me; // для сайдбарів, якщо вони очікують $u

/* ===== helpers/fallbacks ===== */
if (!function_exists('h')) {
    function h(?string $s): string { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('redirect')) {
    function redirect(string $to): void { header('Location: ' . $to, true, 303); exit; }
}
if (!function_exists('csrf_token')) {
    function csrf_token(): string {
        if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(32));
        return (string)$_SESSION['csrf'];
    }
}

/* локальний helper: безпечний flash для header.php */
if (!function_exists('mf_flash_set')) {
    function mf_flash_set(string $k, string $v): void {
        if (!isset($_SESSION)) return;
        if (!isset($_SESSION['_flash']) || !is_array($_SESSION['_flash'])) $_SESSION['_flash'] = [];
        $_SESSION['_flash'][$k] = $v;
    }
}

function mf_int(string $k, int $default = 0): int {
    $v = $_GET[$k] ?? $default;
    if (is_string($v) && $v !== '' && preg_match('~^-?\d+$~', $v)) return (int)$v;
    if (is_int($v)) return $v;
    return $default;
}

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

/* SEO: персональна зона */
$meta_robots = 'noindex, nofollow, noarchive, nosnippet';
$seo_noindex = true;
if (!headers_sent()) {
    header('X-Robots-Tag: ' . $meta_robots, true);
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0', true);
    header('Pragma: no-cache', true);
    header('Expires: 0', true);
    header('X-Content-Type-Options: nosniff', true);
    header('Referrer-Policy: same-origin', true);
}

/* ===== локальний переклад (мінімальний) ===== */
$mf_lang = (string)($_SESSION['lang'] ?? ($me['lang'] ?? 'ua'));
$mf_lang = strtolower(trim($mf_lang));
if ($mf_lang === 'ua') $mf_lang = 'uk';
if (!in_array($mf_lang, ['uk','ru','en'], true)) $mf_lang = 'uk';

$MF_I18N = [
    'uk' => [
        'title' => 'Мої файли',
        'root' => 'Корінь',
        'used' => 'Використано',
        'of' => 'з',
        'upload' => 'Завантажити',
        'create_folder' => 'Створити папку',
        'folder_name' => 'Назва папки',
        'delete_folder' => 'Видалити папку',
        'folders' => 'Папки',
        'files' => 'Файли',
        'empty' => 'Порожньо',
        'name' => 'Назва',
        'size' => 'Розмір',
        'type' => 'Тип',
        'created' => 'Створено',
        'access' => 'Доступ',
        'public' => 'Відкрито',
        'private' => 'Закрито',
        'link' => 'Посилання',
        'copy' => 'Копіювати',
        'open' => 'Відкрити',
        'download' => 'Завантажити',
        'toggle' => 'Перемкнути',
        'delete' => 'Видалити',
        'max50' => 'max 50MB / file',
        'folder_delete_hint' => '(видалиться тільки якщо папка порожня)',
        'confirm_delete_file' => 'Видалити файл?',
        'confirm_delete_folder' => 'Видалити папку?',
        'copied' => 'Скопійовано',
        'page' => 'Сторінка',
        'prev' => 'Назад',
        'next' => 'Далі',
    ],
    'ru' => [
        'title' => 'Мои файлы',
        'root' => 'Корень',
        'used' => 'Использовано',
        'of' => 'из',
        'upload' => 'Загрузить',
        'create_folder' => 'Создать папку',
        'folder_name' => 'Название папки',
        'delete_folder' => 'Удалить папку',
        'folders' => 'Папки',
        'files' => 'Файлы',
        'empty' => 'Пусто',
        'name' => 'Название',
        'size' => 'Размер',
        'type' => 'Тип',
        'created' => 'Создано',
        'access' => 'Доступ',
        'public' => 'Открыто',
        'private' => 'Закрыто',
        'link' => 'Ссылка',
        'copy' => 'Копировать',
        'open' => 'Открыть',
        'download' => 'Скачать',
        'toggle' => 'Переключить',
        'delete' => 'Удалить',
        'max50' => 'max 50MB / file',
        'folder_delete_hint' => '(удалится только если папка пустая)',
        'confirm_delete_file' => 'Удалить файл?',
        'confirm_delete_folder' => 'Удалить папку?',
        'copied' => 'Скопировано',
        'page' => 'Страница',
        'prev' => 'Назад',
        'next' => 'Далее',
    ],
    'en' => [
        'title' => 'My files',
        'root' => 'Root',
        'used' => 'Used',
        'of' => 'of',
        'upload' => 'Upload',
        'create_folder' => 'Create folder',
        'folder_name' => 'Folder name',
        'delete_folder' => 'Delete folder',
        'folders' => 'Folders',
        'files' => 'Files',
        'empty' => 'Empty',
        'name' => 'Name',
        'size' => 'Size',
        'type' => 'Type',
        'created' => 'Created',
        'access' => 'Access',
        'public' => 'Public',
        'private' => 'Private',
        'link' => 'Link',
        'copy' => 'Copy',
        'open' => 'Open',
        'download' => 'Download',
        'toggle' => 'Toggle',
        'delete' => 'Delete',
        'max50' => 'max 50MB / file',
        'folder_delete_hint' => '(only if folder is empty)',
        'confirm_delete_file' => 'Delete file?',
        'confirm_delete_folder' => 'Delete folder?',
        'copied' => 'Copied',
        'page' => 'Page',
        'prev' => 'Prev',
        'next' => 'Next',
    ],
];

function mf_t(string $k): string {
    global $MF_I18N, $mf_lang;
    return $MF_I18N[$mf_lang][$k] ?? $MF_I18N['uk'][$k] ?? $k;
}

function format_bytes(int $b): string {
    $units = ['B','KB','MB','GB','TB'];
    $i = 0;
    $v = (float)$b;
    while ($v >= 1024 && $i < count($units)-1) { $v /= 1024; $i++; }
    return rtrim(rtrim(number_format($v, 2, '.', ''), '0'), '.') . ' ' . $units[$i];
}

function abs_url_local(string $path): string {
    if (function_exists('abs_url')) return (string)abs_url($path);
    $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
    $host  = (string)($_SERVER['HTTP_HOST'] ?? 'localhost');
    return ($https ? 'https://' : 'http://') . $host . $path;
}

/* ===== current folder ===== */
$folderId = mf_int('folder', 0);
if ($folderId < 0) $folderId = 0;

$folder = null;
if ($folderId > 0) {
    $st = $pdo->prepare("SELECT id, user_id, parent_id, name, created_at FROM myfile_folders WHERE id=? AND user_id=? LIMIT 1");
    $st->execute([$folderId, (int)$me['id']]);
    $folder = $st->fetch(PDO::FETCH_ASSOC);
    if (!$folder) {
        mf_flash_set('err', 'Folder not found');
        redirect('/functional/files/');
    }
}

/* ===== breadcrumbs (обмежимо глибину) ===== */
$breadcrumbs = [];
if ($folder) {
    $cur = $folder;
    $guard = 0;
    while ($cur && $guard < 30) {
        $guard++;
        $breadcrumbs[] = $cur;
        $pid = (int)($cur['parent_id'] ?? 0);
        if ($pid <= 0) break;
        $st = $pdo->prepare("SELECT id, user_id, parent_id, name, created_at FROM myfile_folders WHERE id=? AND user_id=? LIMIT 1");
        $st->execute([$pid, (int)$me['id']]);
        $cur = $st->fetch(PDO::FETCH_ASSOC) ?: null;
    }
    $breadcrumbs = array_reverse($breadcrumbs);
}

/* ===== folders list (children) ===== */
if ($folderId > 0) {
    $st = $pdo->prepare("SELECT id, parent_id, name, created_at FROM myfile_folders WHERE user_id=? AND parent_id=? ORDER BY name ASC");
    $st->execute([(int)$me['id'], $folderId]);
} else {
    $st = $pdo->prepare("SELECT id, parent_id, name, created_at FROM myfile_folders WHERE user_id=? AND parent_id IS NULL ORDER BY name ASC");
    $st->execute([(int)$me['id']]);
}
$folders = $st->fetchAll(PDO::FETCH_ASSOC);

/* ===== files list (pagination) ===== */
$page = mf_int('p', 1);
if ($page < 1) $page = 1;

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

if ($folderId > 0) {
    $st = $pdo->prepare("SELECT COUNT(*) FROM myfiles WHERE user_id=? AND folder_id=?");
    $st->execute([(int)$me['id'], $folderId]);
} else {
    $st = $pdo->prepare("SELECT COUNT(*) FROM myfiles WHERE user_id=? AND folder_id IS NULL");
    $st->execute([(int)$me['id']]);
}
$totalFiles = (int)$st->fetchColumn();
$totalPages = max(1, (int)ceil($totalFiles / $perPage));
if ($page > $totalPages) $page = $totalPages;
$offset = ($page - 1) * $perPage;

if ($folderId > 0) {
    $st = $pdo->prepare("
        SELECT id, folder_id, original_name, mime, size_bytes, created_at, is_public, share_token
        FROM myfiles
        WHERE user_id=? AND folder_id=?
        ORDER BY created_at DESC
        LIMIT {$perPage} OFFSET {$offset}
    ");
    $st->execute([(int)$me['id'], $folderId]);
} else {
    $st = $pdo->prepare("
        SELECT id, folder_id, original_name, mime, size_bytes, created_at, is_public, share_token
        FROM myfiles
        WHERE user_id=? AND folder_id IS NULL
        ORDER BY created_at DESC
        LIMIT {$perPage} OFFSET {$offset}
    ");
    $st->execute([(int)$me['id']]);
}
$files = $st->fetchAll(PDO::FETCH_ASSOC);

/* ===== quota ===== */
$quotaMax = 1024 * 1024 * 1024; // 1GB
$st = $pdo->prepare("SELECT COALESCE(SUM(size_bytes),0) FROM myfiles WHERE user_id=?");
$st->execute([(int)$me['id']]);
$usedBytes = (int)$st->fetchColumn();
$usedPct = $quotaMax > 0 ? min(100, (int)round($usedBytes * 100 / $quotaMax)) : 0;

$title = mf_t('title');

/* canonical: поточна папка/сторінка */
$canonicalPath = '/functional/files/' . ($folderId > 0 ? ('?folder=' . $folderId) : '');
if ($page > 1) $canonicalPath .= ($folderId > 0 ? '&' : '?') . 'p=' . $page;
$canonical = abs_url_local($canonicalPath);

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

<style>
.mf-link-input{font-size:12px}
.mf-table td,.mf-table th{vertical-align:middle}
.mf-table th{white-space:nowrap}
.mf-name{min-width: 280px;}
.mf-linkcol{min-width: 240px;}
.mf-actions{min-width: 260px;}
.mf-copy-hint{display:none;font-size:12px}
@media (max-width: 992px){
  .mf-name{min-width: 220px;}
  .mf-linkcol{min-width: 220px;}
  .mf-actions{min-width: 220px;}
}
</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(mf_t('title')) ?></h1>
              <div class="small text-muted">
                <a href="/functional/files/"><?= h(mf_t('root')) ?></a>
                <?php foreach ($breadcrumbs as $bc): ?>
                  &nbsp;/&nbsp;<a href="/functional/files/?folder=<?= (int)$bc['id'] ?>"><?= h((string)$bc['name']) ?></a>
                <?php endforeach; ?>
              </div>
            </div>

            <div style="min-width:280px">
              <div class="small text-muted mb-1">
                <?= h(mf_t('used')) ?>: <b><?= h(format_bytes($usedBytes)) ?></b> <?= h(mf_t('of')) ?> <b><?= h(format_bytes($quotaMax)) ?></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>

        </div>
      </div>

      <!-- TOP AREA: Upload + Create folder + Folders -->
      <div class="row g-3 mb-3">
        <div class="col-12 col-lg-4">
          <div class="card h-100">
            <div class="card-body">
              <div class="fw-semibold mb-2"><?= h(mf_t('upload')) ?></div>

              <form action="/functional/files/upload.php" method="post" enctype="multipart/form-data">
                <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                <input type="hidden" name="folder_id" value="<?= (int)$folderId ?>">

                <input class="form-control form-control-sm" type="file" name="files[]" multiple>
                <div class="form-text"><?= h(mf_t('max50')) ?></div>

                <button class="btn btn-sm btn-primary mt-2" type="submit"><?= h(mf_t('upload')) ?></button>
              </form>
            </div>
          </div>
        </div>

        <div class="col-12 col-lg-4">
          <div class="card h-100">
            <div class="card-body">
              <div class="fw-semibold mb-2"><?= h(mf_t('create_folder')) ?></div>

              <form action="/functional/files/folder_create.php" method="post">
                <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                <input type="hidden" name="parent_id" value="<?= (int)$folderId ?>">

                <input class="form-control form-control-sm" type="text" name="name" maxlength="190" placeholder="<?= h(mf_t('folder_name')) ?>" required>
                <button class="btn btn-sm btn-outline-secondary mt-2" type="submit"><?= h(mf_t('create_folder')) ?></button>
              </form>

              <?php if ($folderId > 0): ?>
                <hr>
                <div class="fw-semibold mb-2"><?= h(mf_t('delete_folder')) ?></div>
                <form action="/functional/files/folder_delete.php" method="post" onsubmit="return confirm(<?= json_encode(mf_t('confirm_delete_folder'), JSON_UNESCAPED_UNICODE) ?>);">
                  <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                  <input type="hidden" name="folder_id" value="<?= (int)$folderId ?>">
                  <button class="btn btn-sm btn-outline-danger" type="submit"><?= h(mf_t('delete_folder')) ?></button>
                </form>
                <div class="small text-muted mt-2"><?= h(mf_t('folder_delete_hint')) ?></div>
              <?php endif; ?>
            </div>
          </div>
        </div>

        <div class="col-12 col-lg-4">
          <div class="card h-100">
            <div class="card-body">
              <div class="fw-semibold mb-2"><?= h(mf_t('folders')) ?></div>

              <?php if (!$folders): ?>
                <div class="text-muted"><?= h(mf_t('empty')) ?></div>
              <?php else: ?>
                <div class="list-group">
                  <?php foreach ($folders as $f): ?>
                    <a class="list-group-item list-group-item-action d-flex align-items-center justify-content-between"
                       href="/functional/files/?folder=<?= (int)$f['id'] ?>">
                      <span>📁 <?= h((string)$f['name']) ?></span>
                      <span class="text-muted small">id: <?= (int)$f['id'] ?></span>
                    </a>
                  <?php endforeach; ?>
                </div>
              <?php endif; ?>
            </div>
          </div>
        </div>
      </div>

      <!-- FILES: на всю ширину -->
      <div class="card">
        <div class="card-body">
          <div class="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-2">
            <div class="fw-semibold"><?= h(mf_t('files')) ?></div>

            <?php if ($totalPages > 1): ?>
              <?php
                $base = '/functional/files/' . ($folderId > 0 ? ('?folder=' . $folderId . '&') : '?');
                $prevUrl = $base . 'p=' . max(1, $page - 1);
                $nextUrl = $base . 'p=' . min($totalPages, $page + 1);
              ?>
              <div class="d-flex align-items-center gap-2">
                <a class="btn btn-sm btn-outline-secondary <?= $page <= 1 ? 'disabled' : '' ?>" href="<?= h($prevUrl) ?>"><?= h(mf_t('prev')) ?></a>
                <span class="small text-muted"><?= h(mf_t('page')) ?> <?= (int)$page ?> / <?= (int)$totalPages ?></span>
                <a class="btn btn-sm btn-outline-secondary <?= $page >= $totalPages ? 'disabled' : '' ?>" href="<?= h($nextUrl) ?>"><?= h(mf_t('next')) ?></a>
              </div>
            <?php endif; ?>
          </div>

          <?php if (!$files): ?>
            <div class="text-muted"><?= h(mf_t('empty')) ?></div>
          <?php else: ?>
            <div class="table-responsive">
              <table class="table table-sm mf-table mb-0">
                <thead>
                  <tr>
                    <th><?= h(mf_t('name')) ?></th>
                    <th><?= h(mf_t('size')) ?></th>
                    <th><?= h(mf_t('type')) ?></th>
                    <th><?= h(mf_t('created')) ?></th>
                    <th><?= h(mf_t('access')) ?></th>
                    <th><?= h(mf_t('link')) ?></th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($files as $it): ?>
                    <?php
                      $token = (string)($it['share_token'] ?? '');
                      $tokenOk = (bool)preg_match('~^[a-f0-9]{64}$~', $token);
                      $isPublic = (int)($it['is_public'] ?? 0) === 1;

                      $openUrl = $tokenOk ? ('/functional/files/file.php?t=' . rawurlencode($token)) : '#';
                      $dlUrl   = $tokenOk ? ('/functional/files/file.php?dl=1&t=' . rawurlencode($token)) : '#';
                      $shareAbs = $tokenOk ? abs_url_local('/functional/files/file.php?t=' . rawurlencode($token)) : '';
                    ?>
                    <tr>
                      <td class="mf-name">
                        <?= h((string)($it['original_name'] ?? '')) ?>
                        <div class="text-muted small">#<?= (int)($it['id'] ?? 0) ?></div>
                      </td>
                      <td><?= h(format_bytes((int)($it['size_bytes'] ?? 0))) ?></td>
                      <td class="text-muted"><?= h((string)($it['mime'] ?? '')) ?></td>
                      <td class="text-muted"><?= h((string)($it['created_at'] ?? '')) ?></td>
                      <td>
                        <?php if ($isPublic): ?>
                          <span class="badge text-bg-success"><?= h(mf_t('public')) ?></span>
                        <?php else: ?>
                          <span class="badge text-bg-secondary"><?= h(mf_t('private')) ?></span>
                        <?php endif; ?>
                      </td>
                      <td class="mf-linkcol">
                        <?php if ($tokenOk): ?>
                          <input class="form-control form-control-sm mf-link-input" readonly value="<?= h($shareAbs) ?>" id="link<?= (int)$it['id'] ?>">
                          <div class="d-flex align-items-center gap-2 mt-2">
                            <button class="btn btn-sm btn-outline-secondary" type="button" onclick="copyLink(<?= (int)$it['id'] ?>)"><?= h(mf_t('copy')) ?></button>
                            <span class="text-success mf-copy-hint" id="hint<?= (int)$it['id'] ?>"><?= h(mf_t('copied')) ?></span>
                          </div>
                        <?php else: ?>
                          <span class="text-muted">—</span>
                        <?php endif; ?>
                      </td>
                      <td class="mf-actions">
                        <div class="d-flex flex-wrap gap-2">
                          <a class="btn btn-sm btn-outline-primary <?= $tokenOk ? '' : 'disabled' ?>" href="<?= h($openUrl) ?>" target="_blank"><?= h(mf_t('open')) ?></a>
                          <a class="btn btn-sm btn-outline-primary <?= $tokenOk ? '' : 'disabled' ?>" href="<?= h($dlUrl) ?>"><?= h(mf_t('download')) ?></a>

                          <form action="/functional/files/file_toggle.php" method="post" style="display:inline">
                            <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                            <input type="hidden" name="id" value="<?= (int)$it['id'] ?>">
                            <input type="hidden" name="back_folder" value="<?= (int)$folderId ?>">
                            <button class="btn btn-sm btn-outline-secondary" type="submit"><?= h(mf_t('toggle')) ?></button>
                          </form>

                          <form action="/functional/files/file_delete.php" method="post" style="display:inline" onsubmit="return confirm(<?= json_encode(mf_t('confirm_delete_file'), JSON_UNESCAPED_UNICODE) ?>);">
                            <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                            <input type="hidden" name="id" value="<?= (int)$it['id'] ?>">
                            <input type="hidden" name="back_folder" value="<?= (int)$folderId ?>">
                            <button class="btn btn-sm btn-outline-danger" type="submit"><?= h(mf_t('delete')) ?></button>
                          </form>
                        </div>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>

            <?php if ($totalPages > 1): ?>
              <?php
                $base2 = '/functional/files/' . ($folderId > 0 ? ('?folder=' . $folderId . '&') : '?');
                $prevUrl2 = $base2 . 'p=' . max(1, $page - 1);
                $nextUrl2 = $base2 . 'p=' . min($totalPages, $page + 1);
              ?>
              <div class="d-flex align-items-center justify-content-end gap-2 mt-3">
                <a class="btn btn-sm btn-outline-secondary <?= $page <= 1 ? 'disabled' : '' ?>" href="<?= h($prevUrl2) ?>"><?= h(mf_t('prev')) ?></a>
                <span class="small text-muted"><?= h(mf_t('page')) ?> <?= (int)$page ?> / <?= (int)$totalPages ?></span>
                <a class="btn btn-sm btn-outline-secondary <?= $page >= $totalPages ? 'disabled' : '' ?>" href="<?= h($nextUrl2) ?>"><?= h(mf_t('next')) ?></a>
              </div>
            <?php endif; ?>

          <?php endif; ?>

        </div>
      </div>

    </div>
  </section>

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

<script>
async function copyLink(id){
  var el = document.getElementById('link'+id);
  var hint = document.getElementById('hint'+id);
  if(!el) return;

  var val = el.value || '';
  try{
    if(navigator.clipboard && navigator.clipboard.writeText){
      await navigator.clipboard.writeText(val);
    } else {
      el.focus();
      el.select();
      el.setSelectionRange(0, 999999);
      document.execCommand('copy');
      el.blur();
    }
    if(hint){
      hint.style.display = 'inline';
      setTimeout(function(){ hint.style.display = 'none'; }, 1200);
    }
  }catch(e){}
}
</script>

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