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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    echo "<h1>Password Reset Database Test</h1>";
    
    // Check if table exists
    $stmt = $db->query("SHOW TABLES LIKE 'password_resets'");
    if ($stmt->rowCount() == 0) {
        echo "<p style='color:red'>ERROR: The password_resets table does not exist!</p>";
        
        // Create the table
        echo "<p>Attempting to create the table...</p>";
        $sql = "
        CREATE TABLE `password_resets` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `email` varchar(255) NOT NULL,
          `token` varchar(255) NOT NULL,
          `code` varchar(10) NOT NULL,
          `created_at` datetime NOT NULL,
          `expires_at` datetime NOT NULL,
          PRIMARY KEY (`id`),
          KEY `email_index` (`email`),
          KEY `token_index` (`token`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
        ";
        
        try {
            $db->exec($sql);
            echo "<p style='color:green'>Table created successfully!</p>";
        } catch (PDOException $e) {
            echo "<p style='color:red'>Failed to create table: " . $e->getMessage() . "</p>";
        }
    } else {
        echo "<p style='color:green'>The password_resets table exists.</p>";
    }
    
    // Check table structure
    echo "<h2>Table Structure:</h2>";
    $stmt = $db->query("DESCRIBE password_resets");
    echo "<table border='1'><tr><th>Field</th><th>Type</th><th>Null</th><th>Key</th><th>Default</th><th>Extra</th></tr>";
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo "<tr>";
        foreach ($row as $key => $value) {
            echo "<td>" . htmlspecialchars($value ?? 'NULL') . "</td>";
        }
        echo "</tr>";
    }
    echo "</table>";
    
    // Check existing records
    echo "<h2>Existing Records:</h2>";
    $stmt = $db->query("SELECT * FROM password_resets ORDER BY created_at DESC LIMIT 10");
    if ($stmt->rowCount() == 0) {
        echo "<p>No records found.</p>";
    } else {
        echo "<table border='1'><tr><th>ID</th><th>Email</th><th>Token (first 10 chars)</th><th>Code</th><th>Created At</th><th>Expires At</th><th>Status</th></tr>";
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo "<tr>";
            echo "<td>" . htmlspecialchars($row['id']) . "</td>";
            echo "<td>" . htmlspecialchars($row['email']) . "</td>";
            echo "<td>" . htmlspecialchars(substr($row['token'], 0, 10)) . "...</td>";
            echo "<td>" . htmlspecialchars($row['code']) . "</td>";
            echo "<td>" . htmlspecialchars($row['created_at']) . "</td>";
            echo "<td>" . htmlspecialchars($row['expires_at']) . "</td>";
            
            // Check if token is expired
            $expires = new DateTime($row['expires_at']);
            $now = new DateTime();
            if ($expires > $now) {
                echo "<td style='color:green'>Valid</td>";
            } else {
                echo "<td style='color:red'>Expired</td>";
            }
            
            echo "</tr>";
        }
        echo "</table>";
    }
    
    // Create a test token
    echo "<h2>Create Test Token:</h2>";
    $email = 'mbkoncepts@gmail.com'; // Replace with your email
    $token = bin2hex(random_bytes(32));
    $code = '123456';
    $now = new DateTime();
    $expires = (new DateTime())->add(new DateInterval('PT1H')); // 1 hour expiry
    
    // Delete any existing reset requests for this email
    $stmt = $db->prepare("DELETE FROM password_resets WHERE email = ?");
    $stmt->execute([$email]);
    
    // Create new reset request
    $stmt = $db->prepare("INSERT INTO password_resets (email, token, code, created_at, expires_at) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([
        $email,
        $token,
        $code,
        $now->format('Y-m-d H:i:s'),
        $expires->format('Y-m-d H:i:s')
    ]);
    
    echo "<p>Test token created for $email</p>";
    echo "<p>Token: $token</p>";
    echo "<p>Code: $code</p>";
    
    // Generate test links
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'];
    
    $resetLink1 = "$protocol://$host/forgot-password.php?email=" . urlencode($email) . "&token=" . $token;
    $resetLink2 = "$protocol://$host/forgot-password.php?email=" . urlencode($email) . "&token=" . urlencode($token);
    
    echo "<h2>Test Links:</h2>";
    echo "<p>Link 1 (without URL encoding token): <a href='$resetLink1' target='_blank'>$resetLink1</a></p>";
    echo "<p>Link 2 (with URL encoding token): <a href='$resetLink2' target='_blank'>$resetLink2</a></p>";
    
} catch (PDOException $e) {
    echo "<h1>Database Error</h1>";
    echo "<p style='color:red'>Error: " . $e->getMessage() . "</p>";
}
?>
