<?php
session_start();
require_once __DIR__ . '/config.php';

ini_set('display_errors', '1');
ini_set('memory_limit', '512M');

if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: admin.php");
    exit;
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login'])) {
    if (($_POST['username'] ?? '') === ADMIN_LOGIN && ($_POST['password'] ?? '') === ADMIN_PASS) {
        $_SESSION['is_admin'] = true;
        header("Location: admin.php");
        exit;
    }
    $error = "Неверный логин или пароль";
}

$isAdmin = !empty($_SESSION['is_admin']);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['start_process']) && $isAdmin) {
    session_write_close();
    set_time_limit(0);
    ignore_user_abort(true);

    @ini_set('zlib.output_compression', '0');
    @ini_set('output_buffering', '0');
    @ini_set('implicit_flush', '1');
    while (ob_get_level() > 0) { @ob_end_flush(); }

    header('Content-Type: text/html; charset=utf-8');
    header('X-Accel-Buffering: no');

    $TIME_BUDGET = 600;
    $MAX_FILES   = 2000;
    $startedAt   = time();

    echo "<!DOCTYPE html><html lang='ru'><head><meta charset='UTF-8'>
    <title>Обработка файлов</title><style>
    body{font-family:'Courier New',monospace;background:#1e1e1e;color:#d4d4d4;padding:20px}
    .log-container{background:#252526;padding:20px;border-radius:8px}
    .log-entry{margin:4px 0;padding:7px;border-left:3px solid #4ec9b0;background:#2d2d30;word-break:break-all}
    .success{color:#4ec9b0}.error{color:#f48771;border-left-color:#f48771}
    .info{color:#569cd6;border-left-color:#569cd6}.warn{color:#dcdcaa;border-left-color:#dcdcaa}
    .summary{margin-top:20px;padding:15px;background:#0e639c;border-radius:4px}
    h2{color:#569cd6}a.btn{color:#fff;background:#007bff;padding:10px 20px;text-decoration:none;border-radius:4px}
    button{padding:10px 20px;background:#28a745;color:#fff;border:0;border-radius:4px;cursor:pointer}
    </style></head><body><h2>🔄 Обработка файлов</h2><div class='log-container'>";
    echo str_repeat(' ', 4096);
    @flush();

    function out($html) { echo $html; @ob_flush(); @flush(); }
    function line($cls, $text) { out("<div class='log-entry $cls'>$text</div>"); }

    function scanJpg($root, &$problems) {
        $stack = [[$root, 0]];
        while ($stack) {
            [$dir, $depth] = array_pop($stack);
            $dh = @opendir($dir);
            if ($dh === false) {
                $problems[] = "Нет доступа: $dir";
                line('warn', "⚠ Пропуск папки (нет прав): <b>" . htmlspecialchars($dir) . "</b>");
                continue;
            }
            while (($entry = readdir($dh)) !== false) {
                if ($entry === '.' || $entry === '..') continue;
                $path = $dir . '/' . $entry;
                if (@is_dir($path)) {
                    if ($depth < 30) $stack[] = [$path, $depth + 1];
                    continue;
                }
                if (preg_match('/\.jpe?g$/i', $entry)) {
                    yield $path;
                }
            }
            closedir($dh);
        }
    }

    /**
     * Рекурсивное удаление пустых папок
     */
    function removeEmptyDirs($path, &$removedCount) {
        if (!@is_dir($path)) return;
        
        $dh = @opendir($path);
        if ($dh === false) return;
        
        while (($entry = readdir($dh)) !== false) {
            if ($entry === '.' || $entry === '..') continue;
            $fullPath = $path . '/' . $entry;
            
            if (@is_dir($fullPath)) {
                removeEmptyDirs($fullPath, $removedCount);
            }
        }
        closedir($dh);
        
        // Проверяем, пуста ли папка (нет файлов и подпапок)
        $items = @scandir($path);
        if ($items !== false && count($items) === 2) { // только '.' и '..'
            if (@rmdir($path)) {
                $removedCount++;
                line('success', "🗑 Удалена пустая папка: <b>" . htmlspecialchars($path) . "</b>");
            } else {
                line('warn', "⚠ Не удалось удалить папку: " . htmlspecialchars($path));
            }
        }
    }

    $lockFile = sys_get_temp_dir() . '/photodetok.lock';
    $lock = @fopen($lockFile, 'c');
    if (!$lock || !flock($lock, LOCK_EX | LOCK_NB)) {
        line('error', '⛔ Обработка уже запущена в другом окне.');
        out("</div><p><a class='btn' href='admin.php'>← Назад</a></p></body></html>");
        exit;
    }

    $processed = 0; $skipped = 0; $problems = []; $stopped = false;
    $mapping = getMapping();
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $inLen = strlen(DIR_IN);

    line('info', "Старт. Структура подпапок будет сохранена.");

    foreach (scanJpg(DIR_IN, $problems) as $oldPath) {
        if ($processed >= $MAX_FILES || (time() - $startedAt) >= $TIME_BUDGET) {
            $stopped = true;
            break;
        }

        $relativePath = ltrim(substr($oldPath, $inLen), '/');
        $relativeDir  = dirname($relativePath);
        $prefix       = ($relativeDir === '.' || $relativeDir === '') ? '' : $relativeDir . '/';
        $originalName = basename($oldPath);

        line('info', "→ <b>" . htmlspecialchars($relativePath) . "</b>");

        if (!@is_readable($oldPath)) {
            $skipped++;
            $problems[] = "Нет прав на чтение: $relativePath";
            line('error', "✗ Нет прав на чтение (загружен от root?)");
            continue;
        }

        $tries = 0;
        do {
            $newId = '';
            for ($i = 0; $i < 8; $i++) $newId .= $chars[random_int(0, 35)];
            if (++$tries > 20) { $newId = ''; break; }
        } while (isset($mapping[$newId]));

        if ($newId === '') {
            $skipped++; continue;
        }

        $newRel        = $prefix . $newId . '.jpg';
        $newPathOut    = rtrim(DIR_OUT, '/') . '/' . $newRel;
        $newPathPechat = rtrim(DIR_PECHAT, '/') . '/' . $newRel;

        $ok = true;
        foreach ([dirname($newPathOut), dirname($newPathPechat)] as $d) {
            if (!@is_dir($d) && !@mkdir($d, 0775, true) && !@is_dir($d)) {
                $problems[] = "Не создана папка: $d";
                line('error', "✗ Не удалось создать папку: " . htmlspecialchars($d));
                $ok = false; break;
            }
        }
        if (!$ok) { $skipped++; continue; }

        clearstatcache(true, $oldPath);
        $srcSize = @filesize($oldPath);

        if (!@copy($oldPath, $newPathOut)) {
            $err = error_get_last()['message'] ?? 'неизвестно';
            $skipped++; $problems[] = "$relativePath: $err";
            line('error', "✗ Копирование в ftpout: " . htmlspecialchars($err));
            continue;
        }
        line('success', "✓ ftpout/<b>" . htmlspecialchars($newRel) . "</b>");

        if (@copy($newPathOut, $newPathPechat)) {
            line('success', "✓ ftp_pechat/" . htmlspecialchars($newRel));
        } else {
            $problems[] = "Не скопирован в ftp_pechat: $newRel";
            line('warn', "⚠ Не скопирован в ftp_pechat (в ftpout файл есть)");
        }

        $mapping[$newId] = ['path' => $newRel, 'time' => time()];
        line('success', "✓ Записано в mapping.json (ID: <b>$newId</b>)");

        clearstatcache(true, $newPathOut);
        if ($srcSize !== false && @filesize($newPathOut) === $srcSize) {
            if (@unlink($oldPath)) {
                line('success', '✓ Оригинал удалён из ftpin');
            } else {
                $problems[] = "Не удалён оригинал: $relativePath";
                line('warn', '⚠ Оригинал не удалён (будет обработан повторно)');
            }
        } else {
            $problems[] = "Размер копии не совпал, оригинал оставлен: $relativePath";
            line('warn', '⚠ Размер копии не совпал — оригинал НЕ удалён');
        }

        $processed++;
        
        if ($processed % 50 === 0) {
            saveMapping($mapping);
        }
    }

    saveMapping($mapping);

    // ========== УДАЛЕНИЕ ПУСТЫХ ПАПОК ==========
    out("<div class='log-entry info' style='margin-top:20px;border-left-color:#f59e0b'>🧹 Очистка пустых папок в ftpin...</div>");
    @flush();
    
    $removedDirs = 0;
    removeEmptyDirs(DIR_IN, $removedDirs);
    
    if ($removedDirs > 0) {
        line('success', "✓ Удалено пустых папок: <b>$removedDirs</b>");
    } else {
        line('info', "ℹ Пустых папок не обнаружено (или остались файлы без прав доступа)");
    }
    // ========== КОНЕЦ ОЧИСТКИ ==========

// ========== МОДАЛЬНОЕ ОКНО С ИТОГАМИ ==========
out("</div>"); // Закрываем log-container

// Добавляем стили и скрипты для модального окна
out("<style>
.modal-overlay {
    display: none;
    position: fixed;
    top: 0; left: 0; right: 0; bottom: 0;
    background: rgba(0,0,0,0.6);
    z-index: 9999;
    justify-content: center;
    align-items: center;
    animation: fadeIn 0.3s;
}
.modal-overlay.active { display: flex; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
@keyframes slideIn { from { transform: translateY(-50px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
.modal-window {
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 20px 60px rgba(0,0,0,0.3);
    max-width: 600px;
    width: 90%;
    max-height: 85vh;
    overflow-y: auto;
    animation: slideIn 0.3s;
    position: relative;
}
.modal-header {
    background: linear-gradient(135deg, #0e639c 0%, #007bff 100%);
    color: #fff;
    padding: 20px 24px;
    border-radius: 16px 16px 0 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.modal-header h3 { margin: 0; font-size: 22px; }
.modal-close {
    background: rgba(255,255,255,0.2);
    border: none;
    color: #fff;
    width: 36px;
    height: 36px;
    border-radius: 50%;
    font-size: 20px;
    cursor: pointer;
    transition: background 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;
}
.modal-close:hover { background: rgba(255,255,255,0.3); }
.modal-body { padding: 24px; color: #334155; }
.stat-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
    margin-bottom: 20px;
}
.stat-card {
    background: #f8fafc;
    border-radius: 10px;
    padding: 16px;
    text-align: center;
    border-left: 4px solid #3b82f6;
}
.stat-card.success { border-left-color: #10b981; }
.stat-card.warn { border-left-color: #f59e0b; }
.stat-card.info { border-left-color: #0ea5e9; }
.stat-value { font-size: 28px; font-weight: 700; color: #1a2b48; }
.stat-label { font-size: 13px; color: #64748b; margin-top: 4px; }
.problems-list {
    background: #fef3c7;
    border-left: 4px solid #f59e0b;
    padding: 16px;
    border-radius: 8px;
    margin: 16px 0;
    max-height: 200px;
    overflow-y: auto;
}
.problems-list h4 { margin: 0 0 10px 0; color: #92400e; font-size: 15px; }
.problems-list ul { margin: 0; padding-left: 20px; color: #78350f; font-size: 13px; }
.problems-list li { margin-bottom: 4px; }
.modal-actions {
    display: flex;
    gap: 10px;
    margin-top: 20px;
    flex-wrap: wrap;
}
.btn-modal {
    flex: 1;
    min-width: 140px;
    padding: 12px 20px;
    font-size: 15px;
    font-weight: 600;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    text-decoration: none;
    text-align: center;
    transition: all 0.2s;
    display: inline-block;
}
.btn-primary { background: #007bff; color: #fff; }
.btn-primary:hover { background: #0056b3; transform: translateY(-1px); }
.btn-success { background: #10b981; color: #fff; }
.btn-success:hover { background: #059669; transform: translateY(-1px); }
.btn-secondary { background: #e2e8f0; color: #334155; }
.btn-secondary:hover { background: #cbd5e1; }
</style>");

// Само модальное окно
out("<div class='modal-overlay active' id='summaryModal'>
    <div class='modal-window'>
        <div class='modal-header'>
            <h3>📊 Итоги обработки</h3>
            <button class='modal-close' onclick='closeModal()' title='Закрыть'>✕</button>
        </div>
        <div class='modal-body'>");

// Статистика карточками
$elapsed = time() - $startedAt;
out("<div class='stat-grid'>
    <div class='stat-card success'>
        <div class='stat-value'>$processed</div>
        <div class='stat-label'>Обработано файлов</div>
    </div>
    <div class='stat-card warn'>
        <div class='stat-value'>$skipped</div>
        <div class='stat-label'>Пропущено</div>
    </div>
    <div class='stat-card info'>
        <div class='stat-value'>$removedDirs</div>
        <div class='stat-label'>Удалено пустых папок</div>
    </div>
    <div class='stat-card'>
        <div class='stat-value'>$elapsed</div>
        <div class='stat-label'>Время (сек)</div>
    </div>
</div>");

// Предупреждение об остановке
if ($stopped) {
    out("<div style='background:#fee2e2;border-left:4px solid #ef4444;padding:14px;border-radius:8px;margin-bottom:16px;color:#991b1b'>
        <b>⏸ Прогон остановлен по лимиту.</b><br>
        В папке ftpin остались необработанные файлы. Нажмите «Продолжить обработку», чтобы обработать оставшиеся.
    </div>");
}

// Список замечаний
if ($problems) {
    out("<div class='problems-list'>
        <h4>⚠ Замечания (" . count($problems) . "):</h4>
        <ul>");
    foreach (array_slice($problems, 0, 100) as $p) {
        out("<li>" . htmlspecialchars($p) . "</li>");
    }
    out("</ul></div>");
}

// Кнопки действий
out("<div class='modal-actions'>");
if ($stopped) {
    out("<form method='POST' style='flex:1;min-width:140px;margin:0'>
        <button type='submit' name='start_process' value='1' class='btn-modal btn-success' style='width:100%'>▶ Продолжить обработку</button>
    </form>");
}
out("<a href='admin.php' class='btn-modal btn-primary'>← В панель управления</a>");
out("<button onclick='closeModal()' class='btn-modal btn-secondary'>Закрыть</button>");
out("</div>");

out("</div></div></div>");

// JavaScript для управления модальным окном
out("<script>
function closeModal() {
    document.getElementById('summaryModal').classList.remove('active');
}
// Закрытие по клику на overlay (вне окна)
document.getElementById('summaryModal').addEventListener('click', function(e) {
    if (e.target === this) closeModal();
});
// Закрытие по Escape
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') closeModal();
});
</script>");

out("</body></html>");
// ========== КОНЕЦ МОДАЛЬНОГО ОКНА ==========

    flock($lock, LOCK_UN);
    fclose($lock);
    exit;
}
?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title>Панель управления</title>
    <style>
        body{font-family:Arial,sans-serif;max-width:700px;margin:50px auto;padding:20px;border:1px solid #ccc;border-radius:8px}
        input[type=submit]{padding:10px 20px;background:#007bff;color:#fff;border:0;border-radius:4px;cursor:pointer}
        .error{color:red}
        .info-box{background:#f0f8ff;padding:15px;border-radius:8px;margin:15px 0;border-left:4px solid #007bff;font-size:14px}
        code{background:#e8e8e8;padding:2px 6px;border-radius:3px}
    </style>
</head>
<body>
<h2>Сервис обработки фотографий</h2>
<?php if (!$isAdmin): ?>
    <h3>Авторизация</h3>
    <?php if ($error) echo "<p class='error'>$error</p>"; ?>
    <form method="POST">
        <p><input type="text" name="username" placeholder="Логин" required></p>
        <p><input type="password" name="password" placeholder="Пароль" required></p>
        <p><input type="submit" name="login" value="Войти"></p>
    </form>
<?php else: ?>
    <p>Вы вошли как <b><?= htmlspecialchars(ADMIN_LOGIN) ?></b>. <a href="?logout=1">Выйти</a></p>
    <div class="info-box">
        • Рекурсивный поиск JPG в <code><?= DIR_IN ?></code><br>
        • Переименование в 8-значный ID (A–Z, 0–9)<br>
        • <b>Структура подпапок сохраняется</b> в ftpout и ftp_pechat<br>
        • <b>Пустые папки автоматически удаляются</b> из ftpin после обработки<br>
        • Маппинг сохраняется в локальный <code>mapping.json</code><br>
        • Нечитаемые файлы (от root) пропускаются с предупреждением
    </div>
    <form method="POST">
        <input type="submit" name="start_process" value="Запустить обработку файлов" onclick="return confirm('Начать обработку? Пустые папки будут удалены.');">
    </form>
<?php endif; ?>
</body>
</html>