<?php
session_start();
date_default_timezone_set('UTC');

// === АУТЕНТИФИКАЦИЯ ===
$PASSWORD = 'avatiah2025';
if (!isset($_SESSION['cron_admin']) && ($_POST['pass'] ?? '') !== $PASSWORD) {
    echo '<form method="post" style="text-align:center;margin:100px auto;max-width:300px;font-family:sans-serif">
        <h2 style="color:#333">Cron Replacer Admin</h2>
        <input type="password" name="pass" placeholder="Пароль" required style="padding:10px;font-size:16px;width:100%;margin-bottom:10px;border:1px solid #ddd;border-radius:4px">
        <button type="submit" style="padding:10px 20px;font-size:16px;background:#1e3c72;color:white;border:none;border-radius:4px;cursor:pointer">Войти</button>
    </form>';
    exit;
}
$_SESSION['cron_admin'] = true;

// === НАСТРОЙКИ ===
$config_file = __DIR__ . '/cron_config.json';
$log_file = __DIR__ . '/cron_log.json';
$lock_file = __DIR__ . '/cron.lock';

// Загрузка конфигурации
$default_scripts = [
    'fetch_celestrak.php'     => 3600,   // 1 час
    'fetch_cyber.php'         => 1800,   // 30 мин
    'fetch_darknet.php'       => 7200,   // 2 часа
    'fetch_energy.php'        => 3600,
    'fetch_evacuation.php'    => 1800,
    'fetch_flights.php'       => 600,    // 10 мин
    'fetch_gold.php'          => 3600,
    'fetch_gov.php'           => 3600,
    'fetch_hezbollah.php'     => 1800,
    'fetch_iran.php'          => 1800,
    'fetch_launches.php'      => 1800,
    'fetch_media.php'         => 1800,
    'fetch_mfa.php'           => 1800,
    'fetch_navy.php'          => 3600,
    'fetch_news.php'          => 1800,
    'fetch_oil.php'           => 3600,
    'fetch_pm.php'            => 1800,
    'fetch_reserves.php'      => 7200,
    'fetch_satellite.php'     => 1800,
    'fetch_us.php'            => 1800,
];

$config = file_exists($config_file) ? json_decode(file_get_contents($config_file), true) : $default_scripts;
if (!is_array($config)) $config = $default_scripts;

// === Блокировка (чтобы не запускалось параллельно) ===
if (file_exists($lock_file) && (time() - filemtime($lock_file)) < 300) {
    die('<h3 style="color:#ef4444;text-align:center;">Скрипт уже запущен (блокировка 5 мин)</h3>');
}
file_put_contents($lock_file, time());

// === ОБРАБОТКА ФОРМ ===
$messages = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_config'])) {
    $new_config = [];
    foreach ($_POST['scripts'] ?? [] as $script => $interval) {
        $interval = max(60, min(86400, intval($interval))); // 1 мин — 24 ч
        if (preg_match('/^fetch_[a-z0-9_]+\.php$/', $script)) {
            $new_config[$script] = $interval;
        }
    }
    // Добавление нового
    $new_script = trim($_POST['new_script'] ?? '');
    if ($new_script && preg_match('/^fetch_[a-z0-9_]+\.php$/', $new_script)) {
        $new_config[$new_script] = max(60, min(86400, intval($_POST['new_interval'] ?? 3600)));
    }
    file_put_contents($config_file, json_encode($new_config, JSON_PRETTY_PRINT));
    $config = $new_config;
    $messages[] = ['type' => 'success', 'text' => 'Конфигурация сохранена'];
}

if (isset($_POST['remove_script'])) {
    $script = $_POST['remove_script'];
    if (isset($config[$script])) {
        unset($config[$script]);
        file_put_contents($config_file, json_encode($config, JSON_PRETTY_PRINT));
        $messages[] = ['type' => 'success', 'text' => "Скрипт $script удалён"];
    }
}

if (isset($_POST['run_now'])) {
    $script = $_POST['run_now'];
    run_script($script, $log_file);
    $messages[] = ['type' => 'success', 'text' => "Запущен: $script"];
}

// === АВТОМАТИЧЕСКИЙ ЗАПУСК ===
$log = [];
foreach ($config as $script => $interval) {
    $last_run_file = __DIR__ . '/last_run_' . preg_replace('/[^a-z0-9]/', '_', $script);
    $last_run = file_exists($last_run_file) ? (int)file_get_contents($last_run_file) : 0;
    if ((time() - $last_run) >= $interval) {
        $result = run_script($script, $log_file);
        file_put_contents($last_run_file, time());
        $log[] = $result;
    }
}

// === ФУНКЦИЯ ЗАПУСКА ===
function run_script($script, $log_file) {
    $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/' . $script;
    $context = stream_context_create(['http' => ['timeout' => 15]]);
    $start = microtime(true);
    $result = @file_get_contents($url, false, $context);
    $time = round(microtime(true) - $start, 2);

    $success = $result !== false;
    $log_entry = [
        'time' => date('d.m.Y H:i:s'),
        'script' => $script,
        'success' => $success,
        'duration' => $time . 's',
        'error' => $success ? '' : (error_get_last()['message'] ?? 'timeout')
    ];

    $log = file_exists($log_file) ? json_decode(file_get_contents($log_file), true) : [];
    $log[] = $log_entry;
    $log = array_slice($log, -100);
    file_put_contents($log_file, json_encode($log, JSON_PRETTY_PRINT));

    return $log_entry;
}

// === ЧТЕНИЕ ЛОГА ===
$log = file_exists($log_file) ? array_reverse(json_decode(file_get_contents($log_file), true)) : [];
$log = array_slice($log, 0, 20);

// === УДАЛЕНИЕ БЛОКИРОВКИ ===
unlink($lock_file);
?>

<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cron Replacer - Автообновление</title>
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline';">
    <style>
        * { margin:0; padding:0; box-sizing:border-box; }
        body { font-family: 'Segoe UI', sans-serif; background: #0a0e1a; color: #e2e8f0; padding: 20px; }
        .container { max-width: 1200px; margin: 0 auto; }
        .header { background: linear-gradient(135deg, #1e3c72, #2a5298); padding: 25px; border-radius: 16px; text-align: center; margin-bottom: 30px; }
        .header h1 { font-size: 2.2em; color: white; }
        .card { background: #1a2332; border: 1px solid #2d3748; border-radius: 12px; padding: 20px; margin-bottom: 20px; }
        .card h2 { color: #60a5fa; border-bottom: 2px solid #2d3748; padding-bottom: 8px; margin-bottom: 15px; font-size: 1.4em; }
        .message { padding: 10px; border-radius: 8px; margin-bottom: 10px; font-weight: 500; }
        .message.success { background: rgba(16,185,129,0.2); color: #10b981; border-left: 4px solid #10b981; }
        .message.error { background: rgba(239,68,68,0.2); color: #ef4444; border-left: 4px solid #ef4444; }
        table { width: 100%; border-collapse: collapse; font-size: 0.95em; }
        th, td { padding: 10px; text-align: left; border-bottom: 1px solid #2d3748; }
        th { background: #1e293b; color: #60a5fa; }
        input[type="number"] { width: 80px; padding: 6px; background: #0f172a; color: white; border: 1px solid #2d3748; border-radius: 4px; }
        .btn { padding: 6px 12px; border: none; border-radius: 6px; cursor: pointer; font-size: 0.9em; margin: 2px; }
        .btn-save { background: #059669; color: white; }
        .btn-run { background: #3b82f6; color: white; }
        .btn-remove { background: #ef4444; color: white; }
        .add-form { display: flex; gap: 10px; margin-top: 15px; flex-wrap: wrap; }
        .add-form input { flex: 1; min-width: 200px; }
        .log-item { padding: 8px; border-bottom: 1px solid #2d3748; font-size: 0.9em; display: flex; justify-content: space-between; }
        .status-ok { color: #10b981; }
        .status-error { color: #ef4444; }
        .logout { text-align: center; margin-top: 30px; }
        .logout button { background: #dc2626; color: white; padding: 10px 20px; border: none; border-radius: 8px; cursor: pointer; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Cron Replacer</h1>
            <p>Автоматическое обновление fetch-скриптов</p>
        </div>

        <?php if (!empty($messages)): ?>
            <div class="messages">
                <?php foreach ($messages as $msg): ?>
                    <div class="message <?= $msg['type'] ?>"><?= htmlspecialchars($msg['text']) ?></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <div class="card">
            <h2>Управление скриптами</h2>
            <form method="post">
                <table>
                    <tr>
                        <th>Скрипт</th>
                        <th>Период (сек)</th>
                        <th>Человекочитаемо</th>
                        <th>Действия</th>
                    </tr>
                    <?php foreach ($config as $script => $interval): 
                        $human = format_interval($interval);
                    ?>
                    <tr>
                        <td><code><?= htmlspecialchars($script) ?></code></td>
                        <td><input type="number" name="scripts[<?= $script ?>]" value="<?= $interval ?>" min="60" max="86400"></td>
                        <td><?= $human ?></td>
                        <td>
                            <button type="submit" name="run_now" value="<?= $script ?>" class="btn btn-run">Запустить</button>
                            <button type="submit" name="remove_script" value="<?= $script ?>" class="btn btn-remove" onclick="return confirm('Удалить?')">Удалить</button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </table>
                <button type="submit" name="save_config" class="btn btn-save" style="margin-top:15px;">Сохранить всё</button>
            </form>

            <div class="add-form">
                <form method="post" style="display:flex;gap:10px;flex:1;">
                    <input type="text" name="new_script" placeholder="fetch_new.php" required pattern="fetch_[a-z0-9_]+\.php">
                    <input type="number" name="new_interval" value="3600" min="60" max="86400">
                    <button type="submit" name="save_config" class="btn btn-save">Добавить</button>
                </form>
            </div>
        </div>

        <div class="card">
            <h2>Последние запуски (лог)</h2>
            <?php if (empty($log)): ?>
                <p style="color:#6b7280;text-align:center;">Лог пуст</p>
            <?php else: foreach ($log as $entry): ?>
                <div class="log-item">
                    <div>
                        <strong><?= htmlspecialchars($entry['script']) ?></strong>
                        <span class="<?= $entry['success'] ? 'status-ok' : 'status-error' ?>">
                            <?= $entry['success'] ? 'Успех' : 'Ошибка' ?>
                        </span>
                        (<?= $entry['duration'] ?>)
                        <?= $entry['error'] ? ' — ' . htmlspecialchars($entry['error']) : '' ?>
                    </div>
                    <div style="color:#94a3b8;"><?= $entry['time'] ?></div>
                </div>
            <?php endforeach; endif; ?>
        </div>

        <div class="card">
            <h2>Как использовать</h2>
            <ul style="color:#94a3b8;line-height:1.8;">
                <li><strong>Через браузер:</strong> Открывай <code>cron_replacer.php</code> — обновления запустятся автоматически</li>
                <li><strong>Через системный cron:</strong> Добавь в crontab: <code>* * * * * curl -s http://твой-сайт/cron_replacer.php</code> (каждую минуту)</li>
                <li><strong>Или:</strong> <code>*/5 * * * * curl -s http://твой-сайт/cron_replacer.php</code> (каждые 5 мин)</li>
            </ul>
        </div>

        <div class="logout">
            <form method="post">
                <button type="submit" name="logout">Выйти</button>
            </form>
        </div>
    </div>

    <script>
        // Автообновление страницы каждые 2 минуты
        setTimeout(() => location.reload(), 120000);
    </script>
</body>
</html>

<?php
function format_interval($seconds) {
    if ($seconds < 3600) return round($seconds / 60) . ' мин';
    if ($seconds < 86400) return round($seconds / 3600, 1) . ' ч';
    return round($seconds / 86400, 1) . ' д';
}
?>