<?php
require_once 'config/database.php';

// Get the email and token from the URL
$email = $_GET['email'] ?? '';
$token = $_GET['token'] ?? '';

echo "<h1>Token Test</h1>";
echo "<p>Testing token for email: " . htmlspecialchars($email) . "</p>";
echo "<p>Token: " . htmlspecialchars(substr($token, 0, 10)) . "...</p>";

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Check if token exists in the database
    $stmt = $db->prepare("SELECT * FROM password_resets WHERE token = ?");
    $stmt->execute([$token]);
    $reset = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($reset) {
        echo "<p style='color:green'>Token found in database!</p>";
        echo "<p>Associated email: " . htmlspecialchars($reset['email']) . "</p>";
        
        // Check if it matches the email
        if ($reset['email'] === $email) {
            echo "<p style='color:green'>Email matches!</p>";
        } else {
            echo "<p style='color:red'>Email does not match! Token is for: " . htmlspecialchars($reset['email']) . "</p>";
        }
        
        // Check if it's expired
        $expires = new DateTime($reset['expires_at']);
        $now = new DateTime();
        
        echo "<p>Current time: " . $now->format('Y-m-d H:i:s') . "</p>";
        echo "<p>Expires at: " . $expires->format('Y-m-d H:i:s') . "</p>";
        
        if ($expires > $now) {
            echo "<p style='color:green'>Token is valid and not expired.</p>";
        } else {
            echo "<p style='color:red'>Token is expired.</p>";
        }
        
        echo "<h2>Full Token Details:</h2>";
        echo "<pre>";
        print_r($reset);
        echo "</pre>";
    } else {
        echo "<p style='color:red'>Token not found in database.</p>";
        
        // Show all tokens in the database
        $stmt = $db->query("SELECT * FROM password_resets ORDER BY created_at DESC LIMIT 5");
        $all_tokens = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (count($all_tokens) > 0) {
            echo "<h2>Recent tokens in database:</h2>";
            foreach ($all_tokens as $t) {
                echo "<p>Email: " . htmlspecialchars($t['email']) . "</p>";
                echo "<p>Token: " . htmlspecialchars(substr($t['token'], 0, 10)) . "...</p>";
                echo "<p>Created: " . $t['created_at'] . ", Expires: " . $t['expires_at'] . "</p>";
                echo "<hr>";
            }
        } else {
            echo "<p>No tokens found in the database.</p>";
        }
    }
    
} catch (Exception $e) {
    echo "<p style='color:red'>Error: " . htmlspecialchars($e->getMessage()) . "</p>";
}
?>
