<?php
// 先清除所有session
session_start();
session_destroy();
session_start();

// 启用错误报告（仅用于调试，生产环境请注释掉这两行）
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 包含数据库连接函数文件
require_once __DIR__ . '/../includes/db.php';

// 如果已经登录，直接跳转到后台首页
if (isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in']) {
    header('Location: index.php');
    exit;
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = isset($_POST['username']) ? trim($_POST['username']) : '';
    $password = isset($_POST['password']) ? trim($_POST['password']) : '';

    if (empty($username) || empty($password)) {
        $error = '用户名和密码不能为空';
    } else {
        try {
            // 验证用户名和密码
            $conn = db_connect();
            
            // 检查admin表是否存在
            $check_table = $conn->query("SHOW TABLES LIKE 'admin'");
            if (!$check_table || $check_table->num_rows == 0) {
                // 表不存在，尝试创建
                $create_result = $conn->query("CREATE TABLE IF NOT EXISTS admin (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    username VARCHAR(50) NOT NULL,
                    password VARCHAR(255) NOT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
                
                if ($create_result) {
                    // 创建默认管理员账户 admin/admin123
                    $default_username = 'admin';
                    $default_password = hash('sha256', 'admin123' . SALT);
                    $insert_result = $conn->query("INSERT INTO admin (username, password) VALUES ('$default_username', '$default_password')");
                    if (!$insert_result) {
                        error_log("创建默认管理员账户失败: " . $conn->error);
                    } else {
                        error_log("成功创建默认管理员账户");
                    }
                } else {
                    error_log("创建admin表失败: " . $conn->error);
                }
            }
            
            // 尝试使用直接SQL查询替代预处理语句
            $username_safe = $conn->real_escape_string($username);
            $result = $conn->query("SELECT id, password FROM admin WHERE username = '$username_safe' LIMIT 1");
            
            if ($result && $result->num_rows === 1) {
                $user = $result->fetch_assoc();
                $stored_password = $user['password'];
                $input_password_hash = hash('sha256', $password . SALT);
                
                if ($input_password_hash === $stored_password) {
                    $_SESSION['admin_logged_in'] = true;
                    $_SESSION['admin_id'] = $user['id'];
                    header('Location: index.php');
                    exit;
                }
            }
            
            $error = '用户名或密码错误';
            $conn->close();
        } catch (Exception $e) {
            error_log("Login error: " . $e->getMessage());
            $error = '登录过程中发生错误，请稍后再试';
        }
    }
}

$page_title = '登录';
?>
<!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 href="../assets/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .login-container {
            margin-top: 100px;
        }
        .card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
        }
        .card-header {
            background: #0d6efd;
            border-radius: 10px 10px 0 0;
            padding: 20px;
        }
        .card-body {
            padding: 30px;
        }
        .form-control {
            border-radius: 5px;
            padding: 10px 15px;
        }
        .btn-primary {
            padding: 10px;
            font-weight: 500;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center login-container">
            <div class="col-md-6 col-lg-4">
                <div class="card">
                    <div class="card-header bg-primary text-white text-center">
                        <h4 class="mb-0">导航管理系统</h4>
                    </div>
                    <div class="card-body">
                        <?php if ($error): ?>
                            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
                        <?php endif; ?>
                        
                        <form method="post" class="needs-validation" novalidate>
                            <div class="mb-3">
                                <label for="username" class="form-label">用户名</label>
                                <input type="text" class="form-control" id="username" name="username" required value="<?php echo htmlspecialchars($username ?? ''); ?>">
                            </div>
                            
                            <div class="mb-3">
                                <label for="password" class="form-label">密码</label>
                                <input type="password" class="form-control" id="password" name="password" required>
                            </div>
                            
                            <div class="d-grid">
                                <button type="submit" class="btn btn-primary">登录</button>
                            </div>
                            
                            <?php if (!isset($check_table) || !$check_table || $check_table->num_rows == 0): ?>
                            <div class="mt-3 text-center">
                                <small class="text-muted">默认用户名：admin，密码：admin123</small>
                            </div>
                            <?php endif; ?>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="../assets/js/bootstrap.bundle.min.js"></script>
    <script>
    // 表单验证
    (function () {
        'use strict'
        var forms = document.querySelectorAll('.needs-validation')
        Array.prototype.slice.call(forms).forEach(function (form) {
            form.addEventListener('submit', function (event) {
                if (!form.checkValidity()) {
                    event.preventDefault()
                    event.stopPropagation()
                }
                form.classList.add('was-validated')
            }, false)
        })
    })()
    </script>
</body>
</html>
