<?php
$user_id = $_SESSION['user_id'];
$user = currentUser();

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $old_password = $_POST['old_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    if (empty($old_password) || empty($new_password) || empty($confirm_password)) {
        $error = '请填写完整信息';
    } elseif (strlen($new_password) < 6) {
        $error = '新密码至少需要6位';
    } elseif ($new_password !== $confirm_password) {
        $error = '两次输入的新密码不一致';
    } elseif (!password_verify($old_password, $user['password'])) {
        $error = '原密码错误';
    } else {
        $hashed = password_hash($new_password, PASSWORD_DEFAULT);
        $db->query("UPDATE users SET password = '$hashed' WHERE id = $user_id");
        $success = '密码修改成功，请重新登录';
        // 清除会话，要求重新登录
        session_destroy();
        echo '<script>setTimeout(function(){ window.location.href = "/modules/home/login.php"; }, 2000);</script>';
    }
}
?>

<div class="changepwd-container">
    <div class="page-header">
        <h2>修改密码</h2>
    </div>
    
    <?php if ($success): ?>
        <div class="alert alert-success"><?php echo $success; ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="alert alert-error"><?php echo $error; ?></div>
    <?php endif; ?>
    
    <div class="password-card">
        <form method="POST" class="password-form">
            <div class="form-group">
                <label>原密码</label>
                <input type="password" name="old_password" required autofocus>
            </div>
            
            <div class="form-group">
                <label>新密码</label>
                <input type="password" name="new_password" required>
                <small>密码长度至少6位</small>
            </div>
            
            <div class="form-group">
                <label>确认新密码</label>
                <input type="password" name="confirm_password" required>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">修改密码</button>
                <a href="?page=profile" class="btn btn-secondary">返回</a>
            </div>
        </form>
    </div>
</div>

<style>
.password-card {
    max-width: 400px;
    margin: 0 auto;
    background: var(--bg-primary);
    border-radius: var(--radius-md);
    padding: 30px;
    border: 1px solid var(--border-color);
}
.password-form .form-group {
    margin-bottom: 20px;
}
.form-actions {
    display: flex;
    gap: 10px;
    margin-top: 20px;
}
</style>