<?php
/**
 * 麟泓授权系统安装程序
 * 要求：PHP >= 8.0
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error.log');


session_start();

if (file_exists(__DIR__ . '/install.lock') && !isset($_GET['step'])) {
    header('Location: index.php');
    exit;
}

// 主站API地址（使用IP直连绕过CDN/防火墙问题）
define('LICENSE_API_URL', 'https://38.76.165.134/api/license/');
// 主站域名（用于Host头）
define('LICENSE_HOST', 'auth.lhwks.cn');
// 硬编码应用标识（与主站 apps 表中 app_key 一致）
define('APP_KEY', 'licenses_app');

// 步骤控制
$step = isset($_GET['step']) ? intval($_GET['step']) : 1;
$error = '';

// 处理步骤提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($step == 1 && isset($_POST['agree'])) {
        $_SESSION['agree'] = true;
        header('Location: install.php?step=2');
        exit;
    } elseif ($step == 2) {
        $env_check = checkEnvironment();
        if ($env_check === true) {
            header('Location: install.php?step=3');
            exit;
        } else {
            $error = '环境检查未通过，请根据提示修正后重试。';
            $env_messages = $env_check;
        }
    } elseif ($step == 3) {
        $license_key = trim($_POST['license_key'] ?? '');
        $domain = $_SERVER['HTTP_HOST'];
        $site_name = trim($_POST['site_name'] ?? '');
        $customer_email = trim($_POST['customer_email'] ?? '');
        $app_key = APP_KEY;

        if (empty($license_key)) {
            $error = '请输入授权码';
        } else {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, LICENSE_API_URL . 'verify.php');
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
                'license_key'    => $license_key,
                'domain'         => $domain,
                'site_name'      => $site_name,
                'customer_email' => $customer_email,
                'app_key'        => $app_key
            ]));
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Host: ' . LICENSE_HOST]);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            $result = json_decode($response, true);

            if ($http_code == 200 && isset($result['code']) && $result['code'] == 200) {
                $_SESSION['license'] = [
                    'license_key' => $license_key,
                    'site_id'     => $result['data']['site_id'] ?? '',
                    'domain'      => $domain,
                    'app_key'     => $app_key
                ];
                $_SESSION['site_name'] = $site_name;
                $_SESSION['customer_email'] = $customer_email;
                
                header('Location: install.php?step=4');
                exit;
            } else {
                $error = $result['message'] ?? '授权码验证失败';
            }
        }
    } elseif ($step == 4) {
        $db_host = trim($_POST['db_host'] ?? '');
        $db_user = trim($_POST['db_user'] ?? '');
        $db_pass = $_POST['db_pass'] ?? '';
        $db_name = trim($_POST['db_name'] ?? 'lhlhauth');

        $conn = @new mysqli($db_host, $db_user, $db_pass);
        if ($conn->connect_error) {
            $error = '数据库连接失败：' . $conn->connect_error;
        } else {
            if (!$conn->select_db($db_name)) {
                $sql = "CREATE DATABASE IF NOT EXISTS `$db_name` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci";
                if ($conn->query($sql)) {
                    $conn->select_db($db_name);
                } else {
                    $error = '创建数据库失败：' . $conn->error;
                }
            }
            if (empty($error)) {
                $result = $conn->query("SHOW TABLES LIKE 'users'");
                if ($result && $result->num_rows > 0) {
                    $error = '数据库已存在安装数据，请清空或选择其他数据库。';
                } else {
                    $_SESSION['db'] = [
                        'host' => $db_host,
                        'user' => $db_user,
                        'pass' => $db_pass,
                        'name' => $db_name
                    ];
                    header('Location: install.php?step=5');
                    exit;
                }
            }
        }
        if (!empty($error)) {
            $step = 4;
        }
        if (isset($conn)) $conn->close();
    } elseif ($step == 5) {
        $admin_user = trim($_POST['admin_user'] ?? '');
        $admin_pass = $_POST['admin_pass'] ?? '';
        $admin_pass2 = $_POST['admin_pass2'] ?? '';
        $admin_email = trim($_POST['admin_email'] ?? '');

        if (empty($admin_user) || empty($admin_pass) || empty($admin_email)) {
            $error = '请填写完整信息';
        } elseif (strlen($admin_pass) < 6) {
            $error = '密码长度至少6位';
        } elseif ($admin_pass !== $admin_pass2) {
            $error = '两次输入的密码不一致';
        } elseif (!filter_var($admin_email, FILTER_VALIDATE_EMAIL)) {
            $error = '邮箱格式不正确';
        } else {
            $_SESSION['admin'] = [
                'user'  => $admin_user,
                'pass'  => password_hash($admin_pass, PASSWORD_DEFAULT),
                'email' => $admin_email
            ];
            $install_result = doInstall();
            if ($install_result === true) {
                file_put_contents(__DIR__ . '/install.lock', date('Y-m-d H:i:s'));
                session_destroy();
                header('Location: install.php?step=6');
                exit;
            } else {
                $error = $install_result;
            }
        }
    }
}

/**
 * 环境检查
 */
function checkEnvironment() {
    $errors = [];
    if (version_compare(PHP_VERSION, '8.0.0', '<')) {
        $errors[] = 'PHP版本过低，当前版本：' . PHP_VERSION . '，需要 ≥ 8.0.0';
    }
    $extensions = ['mysqli', 'curl', 'json', 'session', 'fileinfo', 'gd', 'zip'];
    foreach ($extensions as $ext) {
        if (!extension_loaded($ext)) {
            $errors[] = "扩展 $ext 未启用";
        }
    }
    $dirs = ['assets/uploads', 'cache', 'storage/logs'];
    foreach ($dirs as $dir) {
        if (!is_dir($dir)) {
            @mkdir($dir, 0755, true);
        }
        if (!is_writable($dir)) {
            $errors[] = "目录 $dir 不可写，请设置权限为 755";
        }
    }
    return empty($errors) ? true : $errors;
}

/**
 * 执行安装
 */
function doInstall() {
    $db = $_SESSION['db'];
    $admin = $_SESSION['admin'];
    $license = $_SESSION['license'];

    $conn = new mysqli($db['host'], $db['user'], $db['pass'], $db['name']);
    if ($conn->connect_error) {
        return '数据库连接失败：' . $conn->connect_error;
    }

    $sql_file = __DIR__ . '/install.sql';
    if (!file_exists($sql_file)) {
        return '安装文件 install.sql 不存在，请检查。';
    }

    $sql_content = file_get_contents($sql_file);
    if (empty($sql_content)) {
        return 'install.sql 文件为空。';
    }

    $sql_content = str_replace("\r\n", "\n", $sql_content);
    $sql_content = str_replace("\r", "\n", $sql_content);
    $queries = preg_split('/;\s*\n/', $sql_content);

    $conn->begin_transaction();
    try {
        foreach ($queries as $query) {
            $query = trim($query);
            if (!empty($query)) {
                if (!$conn->query($query)) {
                    throw new Exception("SQL执行错误：" . $conn->error);
                }
            }
        }
        $conn->commit();
    } catch (Exception $e) {
        $conn->rollback();
        return '导入数据库失败：' . $e->getMessage();
    }

    $check = $conn->query("SHOW TABLES LIKE 'users'");
    if (!$check || $check->num_rows == 0) {
        return '数据库表创建失败，请检查 install.sql 文件是否正确。';
    }

    $hashed = $admin['pass'];
    $username = $conn->real_escape_string($admin['user']);
    $email = $conn->real_escape_string($admin['email']);
    $sql = "INSERT INTO users (username, password, email, role) VALUES ('$username', '$hashed', '$email', 'admin')";
    if (!$conn->query($sql)) {
        return '创建管理员账号失败：' . $conn->error;
    }

    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
    $host = $_SERVER['HTTP_HOST'];
    $site_url = $protocol . $host . '/';

    $config_template = '<?php
// ========== Session 配置 ==========
ini_set(\'session.cookie_httponly\', 1);
ini_set(\'session.use_only_cookies\', 1);
session_start();

define(\'DB_HOST\', \'' . addslashes($db['host']) . '\');
define(\'DB_USER\', \'' . addslashes($db['user']) . '\');
define(\'DB_PASS\', \'' . addslashes($db['pass']) . '\');
define(\'DB_NAME\', \'' . addslashes($db['name']) . '\');

define(\'SITE_URL\', \'' . $site_url . '\');
define(\'SITE_ID\', \'' . addslashes($license['site_id']) . '\');
define(\'LICENSE_KEY\', \'' . addslashes($license['license_key']) . '\');
define(\'APP_KEY\', \'' . addslashes($license['app_key']) . '\');
define(\'APP_VERSION\', \'3.1.8\');

define(\'EPAY_API_URL\', \'\');
define(\'EPAY_PID\', \'\');
define(\'EPAY_KEY\', \'\');

define(\'PAY_NOTIFY_URL\', SITE_URL . \'modules/payment/notify.php\');
define(\'PAY_RETURN_URL\', SITE_URL . \'modules/payment/return.php\');

define(\'UPLOAD_DIR\', dirname(__FILE__) . \'/assets/uploads/\');
define(\'UPLOAD_URL\', SITE_URL . \'assets/uploads/\');

define(\'SYS_VERSION\', \'3.1.8\');

spl_autoload_register(function ($class) {
    $file = __DIR__ . \'/includes/\' . $class . \'.php\';
    if (file_exists($file)) require $file;
});

require_once __DIR__ . \'/includes/functions.php\';

$db = Database::getInstance();

// ========== 移动端自动跳转 ==========
function isMobileDevice() {
    $userAgent = $_SERVER[\'HTTP_USER_AGENT\'] ?? \'\';
    $mobileKeywords = [\'Mobile\', \'Android\', \'iPhone\', \'iPad\', \'iPod\', \'webOS\', \'BlackBerry\', \'Windows Phone\', \'Opera Mini\', \'IEMobile\'];
    foreach ($mobileKeywords as $keyword) {
        if (stripos($userAgent, $keyword) !== false) {
            return true;
        }
    }
    return false;
}

if (isMobileDevice()) {
    $currentUri = $_SERVER[\'REQUEST_URI\'] ?? \'\';
    
    if (strpos($currentUri, \'/m/\') === 0) {
        return;
    }
    
    $excludePaths = [\'/api/\', \'/modules/payment/\', \'/assets/\', \'/includes/\', \'/install.php\'];
    foreach ($excludePaths as $path) {
        if (strpos($currentUri, $path) !== false) {
            return;
        }
    }
    
    if (strpos($currentUri, \'/admin.php\') !== false) {
        $page = $_GET[\'page\'] ?? \'\';
        $mobileUrl = \'/m/\' . ($page ? \'?page=\' . urlencode($page) : \'\');
        header(\'Location: \' . $mobileUrl);
        exit;
    }
    
    if ($currentUri == \'/\' || $currentUri == \'/index.php\') {
        header(\'Location: /m/\');
        exit;
    }
}
// ========== 移动端跳转结束 ==========

$siteConfig = getSiteConfig();
';

    if (file_exists(__DIR__ . '/config.php')) {
        @rename(__DIR__ . '/config.php', __DIR__ . '/config.php.bak');
    }
    if (!file_put_contents(__DIR__ . '/config.php', $config_template)) {
        return '无法写入 config.php 文件，请检查目录权限。';
    }

    // 注册站点到主站
    $site_name = $_SESSION['site_name'] ?? $host;
    $customer_email = $_SESSION['customer_email'] ?? $admin['email'];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, LICENSE_API_URL . 'register.php');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'license_key'    => $license['license_key'],
        'site_id'        => $license['site_id'],
        'domain'         => $host,
        'version'        => '3.1.8',
        'app_key'        => $license['app_key'],
        'site_name'      => $site_name,
        'customer_email' => $customer_email
    ]));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Host: ' . LICENSE_HOST]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $response = curl_exec($ch);
    curl_close($ch);

    $conn->close();
    return true;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>麟泓授权系统 - 安装向导</title>
    <link rel="shortcut icon" href="https://host.lhwks.icu/static/upload/543b9a3e135faf20/f3da968e546a86f9.png" />
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%); min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 20px; }
        .install-container { background: #fff; border-radius: 20px; box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25); width: 100%; max-width: 700px; overflow: hidden; }
        .install-header { background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%); color: white; padding: 30px; text-align: center; }
        .install-header h1 { font-size: 24px; margin-bottom: 8px; }
        .install-header p { opacity: 0.9; }
        .install-body { padding: 30px; }
        .step-indicator { display: flex; justify-content: space-between; margin-bottom: 30px; position: relative; }
        .step { flex: 1; text-align: center; position: relative; z-index: 2; }
        .step .circle { width: 40px; height: 40px; background: #e5e7eb; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; font-weight: bold; color: #6b7280; margin-bottom: 8px; }
        .step.active .circle { background: #2a5298; color: white; }
        .step.completed .circle { background: #10b981; color: white; }
        .step .label { font-size: 12px; color: #6b7280; }
        .step.active .label { color: #2a5298; font-weight: 500; }
        .step-line { position: absolute; top: 20px; left: 0; right: 0; height: 2px; background: #e5e7eb; z-index: 1; }
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; margin-bottom: 8px; font-weight: 500; color: #374151; }
        .form-group input { width: 100%; padding: 12px 16px; border: 1px solid #e5e7eb; border-radius: 10px; font-size: 14px; }
        .form-group input:focus { outline: none; border-color: #2a5298; box-shadow: 0 0 0 3px rgba(42,82,152,0.1); }
        .btn { display: inline-block; padding: 12px 24px; border-radius: 10px; font-weight: 500; cursor: pointer; border: none; background: #2a5298; color: white; font-size: 16px; }
        .btn:hover { background: #1e3c72; }
        .btn-block { width: 100%; }
        .alert { padding: 12px 16px; border-radius: 10px; margin-bottom: 20px; }
        .alert-error { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }
        .alert-success { background: #d1fae5; color: #065f46; border: 1px solid #a7f3d0; }
        .protocol-box { max-height: 400px; overflow-y: auto; border: 1px solid #e5e7eb; border-radius: 10px; padding: 20px; margin-bottom: 20px; background: #f9fafb; }
        .agree-checkbox { margin: 20px 0; text-align: center; }
        .license-tip { background: #fef3c7; border-left: 4px solid #f59e0b; padding: 12px 16px; border-radius: 8px; margin-bottom: 20px; font-size: 13px; color: #92400e; }
        .footer { text-align: center; margin-top: 20px; font-size: 12px; color: #9ca3af; }
    </style>
</head>
<body>
<div class="install-container">
    <div class="install-header">
        <h1>麟泓授权系统 安装向导</h1>
        <p>欢迎使用，请按照步骤完成安装</p>
    </div>
    <div class="install-body">
        <div class="step-indicator">
            <div class="step-line"></div>
            <?php for ($i = 1; $i <= 6; $i++): ?>
                <div class="step <?php echo $step == $i ? 'active' : ($step > $i ? 'completed' : ''); ?>">
                    <div class="circle"><?php echo $step > $i ? '✓' : $i; ?></div>
                    <div class="label"><?php echo ['协议', '环境', '授权', '数据库', '管理员', '完成'][$i-1]; ?></div>
                </div>
            <?php endfor; ?>
        </div>

        <?php if (!empty($error)): ?>
            <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        
        <?php if ($step == 1): ?>
            <div class="protocol-box">
                <?php include __DIR__ . '/modules/home/protocol.php'; ?>
            </div>
            <form method="POST">
                <div class="agree-checkbox">
                    <label><input type="checkbox" name="agree" value="1" required> 我已阅读并同意《软件许可协议》</label>
                </div>
                <button type="submit" class="btn btn-block">我同意，继续安装</button>
            </form>
        <?php elseif ($step == 2): ?>
            <h3 style="margin-bottom: 20px;">环境检查</h3>
            <?php if (isset($env_messages)): ?>
                <div class="alert alert-error"><strong>检查未通过：</strong><br><?php foreach ($env_messages as $msg) echo "• $msg<br>"; ?></div>
                <a href="install.php?step=2" class="btn btn-block">重新检查</a>
            <?php else: ?>
                <?php $check = checkEnvironment(); ?>
                <?php if ($check === true): ?>
                    <div class="alert alert-success">✓ 环境检查通过，可以继续安装。</div>
                    <form method="POST"><button type="submit" class="btn btn-block">下一步</button></form>
                <?php else: ?>
                    <div class="alert alert-error"><strong>环境不满足要求：</strong><br><?php foreach ($check as $msg) echo "• $msg<br>"; ?></div>
                    <a href="install.php?step=2" class="btn btn-block">重新检查</a>
                <?php endif; ?>
            <?php endif; ?>
        <?php elseif ($step == 3): ?>
            <h3 style="margin-bottom: 20px;">授权验证</h3>
            <div class="license-tip"><strong>📌 提示：</strong> 请填写购买时获得的授权码，验证通过后继续安装。</div>
            <form method="POST">
                <div class="form-group"><label>授权码</label><input type="text" name="license_key" placeholder="例如：LH-ABCD-1234-EFGH" required autofocus></div>
                <div class="form-group"><label>站点名称</label><input type="text" name="site_name" placeholder="您的网站名称"></div>
                <div class="form-group"><label>管理员邮箱</label><input type="email" name="customer_email" placeholder="用于接收通知"></div>
                <button type="submit" class="btn btn-block">验证授权码</button>
            </form>
        <?php elseif ($step == 4): ?>
            <h3 style="margin-bottom: 20px;">数据库配置</h3>
            <form method="POST">
                <div class="form-group"><label>数据库主机</label><input type="text" name="db_host" value="localhost" required></div>
                <div class="form-group"><label>数据库用户名</label><input type="text" name="db_user" required></div>
                <div class="form-group"><label>数据库密码</label><input type="password" name="db_pass"></div>
                <div class="form-group"><label>数据库名</label><input type="text" name="db_name" value="lhlhauth" required></div>
                <button type="submit" class="btn btn-block">下一步</button>
            </form>
        <?php elseif ($step == 5): ?>
            <h3 style="margin-bottom: 20px;">设置管理员账号</h3>
            <form method="POST">
                <div class="form-group"><label>管理员用户名</label><input type="text" name="admin_user" required placeholder="admin"></div>
                <div class="form-group"><label>密码</label><input type="password" name="admin_pass" required></div>
                <div class="form-group"><label>确认密码</label><input type="password" name="admin_pass2" required></div>
                <div class="form-group"><label>管理员邮箱</label><input type="email" name="admin_email" required></div>
                <button type="submit" class="btn btn-block">开始安装</button>
            </form>
        <?php elseif ($step == 6): ?>
            <div class="alert alert-success">
                <strong>✓ 安装成功！</strong>
                <p>系统已配置完成，您现在可以登录后台了。</p>
            </div>
            <div style="text-align: center; margin-top: 20px;">
                <a href="index.php" class="btn">访问前台首页</a>
                <a href="admin.php" class="btn" style="margin-left: 10px;">进入后台</a>
            </div>
        <?php endif; ?>
        <div class="footer">Copyright © 2025-2026 麟泓网科室 All rights reserved. 版权所有</div>
    </div>
</div>
</body>
</html>