<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

function buildConfig($host, $db, $user, $pass) {
    $config = array(
        'host' => $host,
        'db' => $db,
        'user' => $user,
        'pass' => $pass
    );

    $php = "<?php\n";
    $php .= "define('DB_HOST', " . var_export($host, true) . ");\n";
    $php .= "define('DB_NAME', " . var_export($db, true) . ");\n";
    $php .= "define('DB_USER', " . var_export($user, true) . ");\n";
    $php .= "define('DB_PASS', " . var_export($pass, true) . ");\n";
    $php .= "define('DB_PREFIX', '');\n\n";
    $php .= "define('APP_URL', 'https://' . \$_SERVER['HTTP_HOST'] . dirname(\$_SERVER['PHP_SELF'], 2));\n";
    $php .= "define('APP_VERSION', '1.0.0');\n";
    $php .= "define('APP_NAME', 'SMM Panel');\n\n";
    $php .= "try {\n";
    $php .= "    \$pdo = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4', DB_USER, DB_PASS, [\n";
    $php .= "        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,\n";
    $php .= "        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,\n";
    $php .= "        PDO::ATTR_EMULATE_PREPARES => false\n";
    $php .= "    ]);\n";
    $php .= "} catch (PDOException \$e) {\n";
    $php .= "    die('Database connection failed: ' . \$e->getMessage());\n";
    $php .= "}\n\n";
    $php .= "if (session_status() === PHP_SESSION_NONE) {\n";
    $php .= "    session_start();\n";
    $php .= "}\n\n";
    $php .= "function getSetting(\$key) {\n";
    $php .= "    global \$pdo;\n";
    $php .= "    \$stmt = \$pdo->prepare('SELECT setting_value FROM ' . DB_PREFIX . 'settings WHERE setting_key = ?');\n";
    $php .= "    \$stmt->execute([\$key]);\n";
    $php .= "    \$result = \$stmt->fetch();\n";
    $php .= "    return \$result ? \$result['setting_value'] : null;\n";
    $php .= "}\n\n";
    $php .= "function isLoggedIn() {\n";
    $php .= "    return isset(\$_SESSION['user_id']);\n";
    $php .= "}\n\n";
    $php .= "function isAdmin() {\n";
    $php .= "    return isset(\$_SESSION['user_role']) && \$_SESSION['user_role'] === 'admin';\n";
    $php .= "}\n\n";
    $php .= "function requireAuth() {\n";
    $php .= "    if (!isLoggedIn()) {\n";
    $php .= "        header('Location: login.php');\n";
    $php .= "        exit;\n";
    $php .= "    }\n";
    $php .= "}\n\n";
    $php .= "function requireAdmin() {\n";
    $php .= "    requireAuth();\n";
    $php .= "    if (!isAdmin()) {\n";
    $php .= "        header('Location: index.php');\n";
    $php .= "        exit;\n";
    $php .= "    }\n";
    $php .= "}\n\n";
    $php .= "function sanitize(\$data) {\n";
    $php .= "    return htmlspecialchars(trim(\$data), ENT_QUOTES, 'UTF-8');\n";
    $php .= "}\n";

    return $php;
}
?>
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Установка SMM Panel</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
}
.installer-card {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(20px);
    border-radius: 24px;
    box-shadow: 0 25px 80px rgba(0,0,0,0.25), 0 0 0 1px rgba(255,255,255,0.1);
    width: 100%;
    max-width: 560px;
    overflow: hidden;
    animation: slideUp 0.6s ease-out;
}
@keyframes slideUp {
    from { opacity: 0; transform: translateY(40px); }
    to { opacity: 1; transform: translateY(0); }
}
.header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 40px 30px;
    text-align: center;
    position: relative;
    overflow: hidden;
}
.header::before {
    content: '';
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 60%);
    animation: pulse 4s ease-in-out infinite;
}
@keyframes pulse {
    0%, 100% { transform: scale(1); opacity: 0.5; }
    50% { transform: scale(1.1); opacity: 0.8; }
}
.logo-icon {
    width: 70px;
    height: 70px;
    background: rgba(255,255,255,0.2);
    border-radius: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 16px;
    font-size: 32px;
    position: relative;
    z-index: 1;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255,255,255,0.2);
}
.header h1 {
    color: white;
    font-size: 26px;
    font-weight: 700;
    position: relative;
    z-index: 1;
}
.header p {
    color: rgba(255,255,255,0.8);
    font-size: 14px;
    margin-top: 6px;
    position: relative;
    z-index: 1;
}
.body { padding: 32px; }
.section-title {
    font-size: 13px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 1px;
    color: #667eea;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    gap: 8px;
}
.section-title::before {
    content: '';
    width: 4px;
    height: 16px;
    background: linear-gradient(180deg, #667eea, #764ba2);
    border-radius: 2px;
}
.form-group {
    margin-bottom: 18px;
    position: relative;
}
.form-group label {
    display: block;
    font-size: 13px;
    font-weight: 500;
    color: #374151;
    margin-bottom: 6px;
}
.form-group input, .form-group select {
    width: 100%;
    padding: 12px 14px;
    border: 2px solid #e5e7eb;
    border-radius: 12px;
    font-size: 14px;
    font-family: inherit;
    background: #fafafa;
    transition: all 0.2s;
    outline: none;
}
.form-group input:focus, .form-group select:focus {
    border-color: #667eea;
    background: white;
    box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
}
.form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 14px;
}
.btn-install {
    width: 100%;
    padding: 16px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    border-radius: 14px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    position: relative;
    overflow: hidden;
    margin-top: 8px;
}
.btn-install::after {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
    transition: left 0.5s;
}
.btn-install:hover::after { left: 100%; }
.btn-install:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
}
.success-box {
    background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
    border: 1px solid #6ee7b7;
    border-radius: 16px;
    padding: 24px;
    text-align: center;
    animation: slideUp 0.5s ease-out;
    margin-bottom: 20px;
}
.success-box .icon { font-size: 48px; margin-bottom: 12px; }
.success-box h2 { color: #065f46; font-size: 22px; margin-bottom: 8px; }
.success-box p { color: #047857; font-size: 14px; margin-bottom: 4px; }
.error-box {
    background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
    border: 1px solid #fca5a5;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 20px;
    color: #991b1b;
    font-size: 14px;
}
.warning-box {
    background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
    border: 1px solid #fbbf24;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 20px;
    color: #92400e;
    font-size: 14px;
}
.info-box {
    background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
    border: 1px solid #93c5fd;
    border-radius: 12px;
    padding: 14px 16px;
    margin-bottom: 20px;
    color: #1e40af;
    font-size: 13px;
    display: flex;
    align-items: flex-start;
    gap: 10px;
}
.info-box .icon { font-size: 18px; flex-shrink: 0; }
.creds {
    background: #f3f4f6;
    border-radius: 12px;
    padding: 16px;
    margin: 16px 0;
    font-family: 'SF Mono', monospace;
    font-size: 13px;
}
.creds .label {
    color: #6b7280;
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 4px;
}
.creds .value { color: #1f2937; font-weight: 600; }
.code-block {
    background: #1f2937;
    color: #e5e7eb;
    border-radius: 12px;
    padding: 16px;
    font-family: 'SF Mono', monospace;
    font-size: 12px;
    overflow-x: auto;
    margin: 12px 0;
    white-space: pre-wrap;
    word-break: break-all;
}
.footer {
    text-align: center;
    padding: 20px;
    color: #9ca3af;
    font-size: 12px;
    border-top: 1px solid #f3f4f6;
}
.step-indicator {
    display: flex;
    justify-content: center;
    gap: 8px;
    margin-bottom: 24px;
}
.step-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #e5e7eb;
    transition: all 0.3s;
}
.step-dot.active {
    background: linear-gradient(135deg, #667eea, #764ba2);
    width: 24px;
    border-radius: 4px;
}
</style>
</head>
<body>

<?php
$step = $_GET['step'] ?? 'form';
$host = $_POST['host'] ?? 'localhost';
$db   = $_POST['db'] ?? 'smm_panel';
$user = $_POST['user'] ?? 'root';
$pass = $_POST['pass'] ?? '';
$admin_login = $_POST['admin_login'] ?? 'admin';
$admin_pass  = $_POST['admin_pass'] ?? 'admin123';

if ($step === 'install' && $_SERVER['REQUEST_METHOD'] === 'POST') {
?>

<div class="installer-card">
    <div class="header">
        <div class="logo-icon">🚀</div>
        <h1>Установка</h1>
        <p>Создание базы данных и настройка</p>
    </div>
    <div class="body">
        <?php
        $errors = [];
        $configPath = dirname(__DIR__) . '/includes/config.php';
        $includesDir = dirname(__DIR__) . '/includes';

        if (!is_writable($includesDir)) {
            $errors[] = "Папка <code>includes/</code> недоступна для записи. Установите права: <code>chmod 777 includes/</code>";
        }

        try {
            $pdo = new PDO("mysql:host=$host;charset=utf8mb4", $user, $pass);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            echo '<p style="color:green;">✅ Подключение к MySQL установлено</p>';

            $pdo->exec("CREATE DATABASE IF NOT EXISTS `$db` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
            $pdo->exec("USE `$db`");
            echo '<p style="color:green;">✅ База данных готова</p>';

            $pdo->exec("CREATE TABLE IF NOT EXISTS users (
                id INT AUTO_INCREMENT PRIMARY KEY,
                login VARCHAR(50) NOT NULL UNIQUE,
                email VARCHAR(100) DEFAULT '',
                password VARCHAR(255) NOT NULL,
                role ENUM('admin','manager','client') DEFAULT 'client',
                status ENUM('active','blocked') DEFAULT 'active',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )");

            $pdo->exec("CREATE TABLE IF NOT EXISTS clients (
                id INT AUTO_INCREMENT PRIMARY KEY,
                name VARCHAR(100) NOT NULL,
                email VARCHAR(100) DEFAULT NULL,
                phone VARCHAR(20) DEFAULT NULL,
                status ENUM('active','inactive') DEFAULT 'active',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )");

            $pdo->exec("CREATE TABLE IF NOT EXISTS projects (
                id INT AUTO_INCREMENT PRIMARY KEY,
                client_id INT NOT NULL,
                name VARCHAR(150) NOT NULL,
                description TEXT,
                status ENUM('active','paused','completed','cancelled') DEFAULT 'active',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )");

            $pdo->exec("CREATE TABLE IF NOT EXISTS posts (
                id INT AUTO_INCREMENT PRIMARY KEY,
                project_id INT NOT NULL,
                title VARCHAR(255) NOT NULL,
                content TEXT,
                platform VARCHAR(20) NOT NULL,
                status ENUM('draft','scheduled','published') DEFAULT 'draft',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )");

            $pdo->exec("CREATE TABLE IF NOT EXISTS tasks (
                id INT AUTO_INCREMENT PRIMARY KEY,
                project_id INT NOT NULL,
                title VARCHAR(255) NOT NULL,
                description TEXT,
                priority ENUM('low','medium','high','urgent') DEFAULT 'medium',
                status ENUM('pending','in_progress','completed') DEFAULT 'pending',
                due_date DATE,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )");

            $pdo->exec("CREATE TABLE IF NOT EXISTS calendar_events (
                id INT AUTO_INCREMENT PRIMARY KEY,
                project_id INT NOT NULL,
                title VARCHAR(255) NOT NULL,
                event_type ENUM('post','story','campaign','meeting','deadline') DEFAULT 'post',
                event_date DATE NOT NULL,
                event_time TIME DEFAULT NULL,
                description TEXT,
                color VARCHAR(7) DEFAULT '#4F46E5',
                created_by INT DEFAULT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )");

            $pdo->exec("CREATE TABLE IF NOT EXISTS analytics (
                id INT AUTO_INCREMENT PRIMARY KEY,
                post_id INT NOT NULL,
                date DATE NOT NULL,
                likes INT DEFAULT 0,
                comments INT DEFAULT 0,
                shares INT DEFAULT 0,
                views INT DEFAULT 0,
                clicks INT DEFAULT 0,
                reach INT DEFAULT 0,
                followers_gained INT DEFAULT 0,
                UNIQUE KEY unique_post_date (post_id, date)
            )");

            $pdo->exec("CREATE TABLE IF NOT EXISTS settings (
                id INT AUTO_INCREMENT PRIMARY KEY,
                setting_key VARCHAR(100) NOT NULL UNIQUE,
                setting_value TEXT DEFAULT NULL,
                setting_group VARCHAR(50) DEFAULT 'general',
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            )");
            echo '<p style="color:green;">✅ Таблицы созданы</p>';

            $stmt = $pdo->prepare("INSERT INTO users (login, email, password, role, status) VALUES (?, '', ?, 'admin', 'active')");
            $stmt->execute([$admin_login, password_hash($admin_pass, PASSWORD_DEFAULT)]);
            echo '<p style="color:green;">✅ Администратор создан: ' . htmlspecialchars($admin_login) . '</p>';

            $settings = [
                ['app_name', 'SMM Panel', 'general'],
                ['timezone', 'Europe/Moscow', 'general'],
                ['date_format', 'd.m.Y', 'general'],
                ['items_per_page', '20', 'general'],
                ['theme', 'light', 'appearance']
            ];
            $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value, setting_group) VALUES (?, ?, ?)");
            foreach ($settings as $s) { $stmt->execute($s); }
            echo '<p style="color:green;">✅ Настройки по умолчанию добавлены</p>';

            $config = buildConfig($host, $db, $user, $pass);
            $configSaved = false;

            if (is_writable($includesDir)) {
                $configSaved = file_put_contents($configPath, $config);
                if ($configSaved) {
                    echo '<p style="color:green;">✅ Файл конфигурации сохранён</p>';
                } else {
                    $errors[] = "Не удалось записать файл конфигурации";
                }
            } else {
                $errors[] = "Нет прав на запись в папку <code>includes/</code>";
            }

            if (empty($errors)) {
        ?>

        <div class="success-box">
            <div class="icon">🎉</div>
            <h2>Установка завершена!</h2>
            <p>SMM Panel успешно установлен и готов к работе.</p>
        </div>

        <div class="creds">
            <div class="label">Логин</div>
            <div class="value"><?php echo htmlspecialchars($admin_login); ?></div>
            <div style="margin-top: 10px;"></div>
            <div class="label">Пароль</div>
            <div class="value"><?php echo htmlspecialchars($admin_pass); ?></div>
        </div>

        <div class="info-box">
            <span class="icon">⚠️</span>
            <div><strong>Важно:</strong> Удалите папку <code>install/</code> с сервера для безопасности.</div>
        </div>

        <a href="../index.php" class="btn-install" style="display: block; text-align: center; text-decoration: none;">
            Перейти в панель управления →
        </a>

        <?php } else { ?>

        <div class="warning-box">
            <strong>⚠️ Установка частично завершена</strong><br>
            База данных создана, но файл конфигурации не сохранён.
        </div>

        <?php foreach ($errors as $error): ?>
        <div class="error-box"><?php echo $error; ?></div>
        <?php endforeach; ?>

        <div class="info-box">
            <span class="icon">📝</span>
            <div>Создайте файл <code>includes/config.php</code> вручную и вставьте следующий код:</div>
        </div>

        <div class="code-block"><?php echo htmlspecialchars($config); ?></div>

        <a href="" class="btn-install" style="display: block; text-align: center; text-decoration: none;">
            ← Попробовать снова
        </a>

        <?php } ?>

        <?php } catch (Exception $e) { ?>
        <div class="error-box">
            <strong>Ошибка установки:</strong> <?php echo htmlspecialchars($e->getMessage()); ?>
        </div>
        <a href="" class="btn-install" style="display: block; text-align: center; text-decoration: none;">
            ← Попробовать снова
        </a>
        <?php } ?>
    </div>
</div>

<?php } else { ?>

<div class="installer-card">
    <div class="header">
        <div class="logo-icon">🚀</div>
        <h1>SMM Panel</h1>
        <p>Установка системы управления соцсетями</p>
    </div>
    <div class="body">
        <div class="step-indicator">
            <div class="step-dot active"></div>
            <div class="step-dot"></div>
            <div class="step-dot"></div>
        </div>

        <?php
        $includesDir = dirname(__DIR__) . '/includes';
        if (!is_writable($includesDir)) {
            echo '<div class="warning-box">
                <strong>⚠️ Внимание:</strong> Папка <code>includes/</code> недоступна для записи.<br>
                Перед установкой выполните: <code>chmod 777 ' . realpath($includesDir) . '</code>
            </div>';
        }
        ?>

        <div class="info-box">
            <span class="icon">💡</span>
            <div>Укажите параметры подключения к MySQL. База данных будет создана автоматически.</div>
        </div>

        <form method="POST" action="?step=install">
            <div class="section-title">База данных</div>
            <div class="form-row">
                <div class="form-group"><label>Сервер</label><input type="text" name="host" value="localhost" required></div>
                <div class="form-group"><label>База данных</label><input type="text" name="db" value="smm_panel" required></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label>Пользователь</label><input type="text" name="user" value="root" required></div>
                <div class="form-group"><label>Пароль</label><input type="password" name="pass" placeholder="••••••"></div>
            </div>

            <div class="section-title" style="margin-top: 24px;">Администратор</div>
            <div class="form-row">
                <div class="form-group"><label>Логин</label><input type="text" name="admin_login" value="admin" required></div>
                <div class="form-group"><label>Пароль</label><input type="text" name="admin_pass" value="admin123" required></div>
            </div>

            <button type="submit" name="install" class="btn-install">Установить систему →</button>
        </form>
    </div>
    <div class="footer">SMM Panel v1.0.0 · Установщик</div>
</div>

<?php } ?>

</body>
</html>
