<?php
/**
 * FIX PASSWORDS - RUN THIS IMMEDIATELY
 * This will generate proper bcrypt hashes for all users
 * DELETE THIS FILE AFTER RUNNING!
 */

require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/config/database.php';

echo "<h1>🔧 Fixing User Passwords</h1>";
echo "<p>Generating proper bcrypt hashes for all users...</p>";

try {
    $pdo = get_db_connection();
    
    // Default password for all test users
    $password = 'Admin@123';
    
    // Generate a REAL bcrypt hash
    $hash = password_hash($password, PASSWORD_DEFAULT, ['cost' => 12]);
    
    echo "<p>Generated hash for '<strong>$password</strong>':</p>";
    echo "<pre style='background: #f4f4f4; padding: 10px; border-radius: 5px;'>$hash</pre>";
    
    // Update all users with this hash
    $stmt = $pdo->prepare("UPDATE users SET password_hash = ?");
    $result = $stmt->execute([$hash]);
    
    if ($result) {
        $count = $stmt->rowCount();
        echo "<p style='color: green; font-weight: bold;'>✅ SUCCESS! Updated $count users with password: <strong>$password</strong></p>";
    } else {
        echo "<p style='color: red;'>❌ Failed to update users</p>";
    }
    
    // Verify the update
    $check = $pdo->query("SELECT username, password_hash FROM users LIMIT 5");
    $users = $check->fetchAll(PDO::FETCH_ASSOC);
    
    echo "<h3>Verification (first 5 users):</h3>";
    echo "<table border='1' cellpadding='8' style='border-collapse: collapse;'>";
    echo "<tr><th>Username</th><th>Hash Preview</th><th>Verifies with 'Admin@123'?</th></tr>";
    
    foreach ($users as $user) {
        $verifies = password_verify($password, $user['password_hash']) ? '✅ YES' : '❌ NO';
        $hash_preview = substr($user['password_hash'], 0, 30) . '...';
        
        echo "<tr>";
        echo "<td>" . htmlspecialchars($user['username']) . "</td>";
        echo "<td><code>" . htmlspecialchars($hash_preview) . "</code></td>";
        echo "<td style='color: " . ($verifies == '✅ YES' ? 'green' : 'red') . ";'>$verifies</td>";
        echo "</tr>";
    }
    echo "</table>";
    
    echo "<hr>";
    echo "<h3>✅ Passwords fixed! You can now login with:</h3>";
    echo "<ul>";
    echo "<li><strong>Username:</strong> admin</li>";
    echo "<li><strong>Password:</strong> Admin@123</li>";
    echo "</ul>";
    echo "<p><a href='login.php' style='display: inline-block; padding: 10px 20px; background: #28a745; color: white; text-decoration: none; border-radius: 5px;'>Go to Login Page</a></p>";
    echo "<p style='color: red;'><strong>⚠️ IMPORTANT: Delete this file after logging in!</strong></p>";
    
} catch (Exception $e) {
    echo "<p style='color: red;'>Error: " . $e->getMessage() . "</p>";
}