<?php
$dir = __DIR__;
$uploadMsg = '';
$uploadOk = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $file = $_FILES['file'];
    $title = trim($_POST['title'] ?? '');
    if ($file['error'] === UPLOAD_ERR_OK && $file['size'] > 0) {
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!preg_match('/^[a-z0-9]{1,10}$/', $ext)) $ext = '';
        // Санитизация названия: буквы, цифры, пробелы, . _ -
        $title = preg_replace('/[^\p{L}\p{N}\s._-]+/u', '', $title);
        $title = preg_replace('/\s+/u', ' ', $title);
        $title = trim($title);
        if ($title === '') $title = pathinfo($file['name'], PATHINFO_FILENAME);
        $base = $title;
        $newname = $base . ($ext !== '' ? '.' . $ext : '');
        $dest = $dir . '/' . $newname;
        $i = 1;
        while (file_exists($dest)) {
            $newname = $base . " ($i)" . ($ext !== '' ? '.' . $ext : '');
            $dest = $dir . '/' . $newname;
            $i++;
        }
        if (move_uploaded_file($file['tmp_name'], $dest)) {
            chmod($dest, 0644);
            $uploadOk = true;
            $uploadMsg = 'Файл успешно загружен: ' . basename($dest);
        } else {
            $uploadOk = false;
            $uploadMsg = 'Ошибка сохранения файла. Проверьте права на папку.';
        }
    } else {
        $uploadOk = false;
        $uploadMsg = 'Ошибка загрузки (код ' . $file['error'] . '). Максимальный размер файла — 600 МБ.';
    }
}

// Список файлов (по дате, новые сверху)
$items = array_diff(scandir($dir), ['.', '..', 'index.php']);
$files = [];
foreach ($items as $f) {
    $p = $dir . '/' . $f;
    if (is_file($p)) {
        $files[] = ['name' => $f, 'size' => filesize($p), 'mtime' => filemtime($p)];
    }
}
usort($files, fn($a, $b) => $b['mtime'] <=> $a['mtime']);

function fmtSize($bytes) {
    if ($bytes >= 1073741824) return round($bytes / 1073741824, 2) . ' ГБ';
    if ($bytes >= 1048576) return round($bytes / 1048576, 1) . ' МБ';
    if ($bytes >= 1024) return round($bytes / 1024) . ' КБ';
    return $bytes . ' Б';
}
?>
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Файлы мастерской</title>
<style>
body { font-family: 'Segoe UI', Roboto, Arial, sans-serif; max-width: 860px; margin: 0 auto; padding: 24px 16px 60px; color: #1f2328; line-height: 1.5; background: #fff; }
h1 { font-size: 1.6em; border-bottom: 2px solid #0969da; padding-bottom: 10px; }
.upload-box { border: 2px dashed #0969da; border-radius: 12px; padding: 20px; margin: 24px 0; background: #f6f8fa; }
.upload-box label { display: block; margin: 10px 0 4px; font-weight: 600; font-size: 0.95em; }
.upload-box input[type=text] { width: 100%; max-width: 420px; padding: 8px 10px; border: 1px solid #ccc; border-radius: 6px; font-size: 1em; box-sizing: border-box; }
.upload-box input[type=file] { display: block; margin: 6px 0 14px; font-size: 0.95em; }
.btn { background: #0969da; color: #fff; border: none; padding: 10px 24px; border-radius: 6px; font-size: 1em; cursor: pointer; }
.btn:hover { background: #0756b0; }
.msg-ok { background: #dafbe1; border: 1px solid #4ac26b; color: #1a7f37; padding: 10px 14px; border-radius: 8px; margin: 12px 0; }
.msg-err { background: #ffebe9; border: 1px solid #ff8182; color: #cf222e; padding: 10px 14px; border-radius: 8px; margin: 12px 0; }
.file-list { list-style: none; padding: 0; margin: 16px 0 0; }
.file-list li { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 10px 12px; border-bottom: 1px solid #eee; flex-wrap: wrap; }
.file-list a { color: #0969da; text-decoration: none; word-break: break-all; }
.file-list a:hover { text-decoration: underline; }
.file-meta { color: #656d76; font-size: 0.85em; white-space: nowrap; }
.hint { color: #656d76; font-size: 0.85em; margin-top: 4px; }
.guide-box {
    background: linear-gradient(135deg, #0b5fff 0%, #0847c4 100%);
    color: #fff; border-radius: 14px; padding: 22px 24px; margin: 24px 0;
    box-shadow: 0 4px 16px rgba(11, 95, 255, 0.25);
}
.guide-box .guide-title { font-size: 1.25em; font-weight: 700; margin-bottom: 6px; }
.guide-box .guide-text { font-size: 0.95em; opacity: 0.92; margin-bottom: 14px; line-height: 1.55; }
.guide-box .guide-links { display: flex; gap: 10px; flex-wrap: wrap; }
.guide-box a {
    display: inline-block; background: #fff; color: #0b5fff; font-weight: 600;
    padding: 9px 18px; border-radius: 8px; text-decoration: none; font-size: 0.95em;
}
.guide-box a:hover { background: #eef4ff; }
</style>
</head>
<body>
<h1>Файлы мастерской</h1>

<div class="guide-box">
    <div class="guide-title">Инструкция: квиз-лендинг 4 поколения</div>
    <div class="guide-text">Готовая методика Quiz24 — суть, этапы разработки, оферы, механики, чек-лист и грабли. Изучите перед стартом проекта.</div>
    <div class="guide-links">
        <a href="https://gubtor.ru/quiz24/" target="_blank">Открыть инструкцию</a>
        <a href="https://gubtor.ru/quiz24/brief.html" target="_blank">Бриф клиента</a>
        <a href="https://gubtor.ru/quiz24/config.html" target="_blank">Конфиг квиза</a>
    </div>
</div>

<div class="upload-box">
    <form method="post" enctype="multipart/form-data">
        <label for="title">Название файла (как будет отображаться на странице):</label>
        <input type="text" id="title" name="title" placeholder="Например: Презентация Quiz24">
        <label for="file">Выберите файл (до 600 МБ):</label>
        <input type="file" id="file" name="file" required>
        <button type="submit" class="btn">Загрузить</button>
        <div class="hint">Расширение файла подставится автоматически. Если файл с таким названием уже есть — добавится номер.</div>
    </form>
</div>

<?php if ($uploadOk === true): ?><div class="msg-ok"><?= htmlspecialchars($uploadMsg) ?></div><?php endif; ?>
<?php if ($uploadOk === false): ?><div class="msg-err"><?= htmlspecialchars($uploadMsg) ?></div><?php endif; ?>

<h2>Загруженные файлы (<?= count($files) ?>)</h2>
<ul class="file-list">
<?php foreach ($files as $f): ?>
    <li>
        <a href="<?= htmlspecialchars(rawurlencode($f['name'])) ?>"><?= htmlspecialchars($f['name']) ?></a>
        <span class="file-meta"><?= fmtSize($f['size']) ?> · <?= date('d.m.Y H:i', $f['mtime']) ?></span>
    </li>
<?php endforeach; ?>
</ul>
</body>
</html>
