<?php
include 'includes/db.php';
include 'includes/header.php';

$message = "";
$error = "";
$valid_token = false;

if (isset($_GET['token'])) {
    $token = $conn->real_escape_string($_GET['token']);
    $current_time = date('Y-m-d H:i:s');
    
    $sql = "SELECT id FROM users WHERE reset_token = '$token' AND reset_expires_at > '$current_time'";
    $result = $conn->query($sql);
    
    if ($result->num_rows > 0) {
        $valid_token = true;
        $user = $result->fetch_assoc();
        $user_id = $user['id'];
    } else {
        $error = "Invalid or expired password reset token.";
    }
} else {
    $error = "No token provided.";
}

if ($_SERVER["REQUEST_METHOD"] == "POST" && $valid_token) {
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    
    if ($password === $confirm_password) {
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        
        $sql = "UPDATE users SET password = '$hashed_password', reset_token = NULL, reset_expires_at = NULL WHERE id = $user_id";
        
        if ($conn->query($sql) === TRUE) {
            $message = "Password has been reset successfully! You can now <a href='login.php'>login</a>.";
            $valid_token = false; // Hide form
        } else {
            $error = "Error updating password.";
        }
    } else {
        $error = "Passwords do not match.";
    }
}
?>

<div class="auth-wrapper">
    <div class="auth-box">
        <h2>Reset Password</h2>
        
        <?php if($message): ?>
            <div class="alert alert-success"><?php echo $message; ?></div>
        <?php endif; ?>
        
        <?php if($error): ?>
            <div class="alert alert-danger"><?php echo $error; ?></div>
        <?php endif; ?>
        
        <?php if($valid_token): ?>
        <form method="POST" action="">
            <div class="form-group">
                <label>New Password</label>
                <input type="password" name="password" class="form-control" required>
            </div>
            <div class="form-group">
                <label>Confirm New Password</label>
                <input type="password" name="confirm_password" class="form-control" required>
            </div>
            <button type="submit" class="btn-primary btn-block">Reset Password</button>
        </form>
        <?php elseif(!$message): ?>
            <p class="text-center">
                <a href="forgot_password.php" class="btn-primary" style="text-decoration: none; padding: 10px 20px;">Request New Link</a>
            </p>
        <?php endif; ?>
        
        <p class="text-center" style="margin-top: 15px;">
            <a href="login.php" style="text-decoration: none;">Back to Login</a>
        </p>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
