<?php
// ============================================================
// hash-passwords.php — place in web/ folder, run ONCE, DELETE after
// Converts plain text passwords → Yii2 bcrypt hashed passwords
// ============================================================

defined('YII_DEBUG') or define('YII_DEBUG', false);
defined('YII_ENV')   or define('YII_ENV', 'prod');

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';

$config = require __DIR__ . '/../config/web.php';
(new yii\web\Application($config));

$db = Yii::$app->db;

$totalUsers   = 0;
$totalHashed  = 0;
$totalSkipped = 0;
$errors       = [];

echo '<style>
    body { font-family: monospace; padding: 20px; background: #1a1a1a; color: #eee; }
    .success { color: #4ade80; }
    .error   { color: #f87171; }
    .info    { color: #60a5fa; }
    .warn    { color: #fbbf24; }
    h2       { color: #fff; border-bottom: 1px solid #444; padding-bottom: 8px; }
    .row     { padding: 4px 0; border-bottom: 1px solid #333; }
</style>';

echo '<h2>🔐 Password Hash Migration</h2>';

$users = $db->createCommand('SELECT id, username, password FROM user ORDER BY id ASC')->queryAll();
$totalUsers = count($users);

echo "<p class='info'>Found <strong>{$totalUsers}</strong> users. Checking passwords...</p>";
echo '<hr style="border-color:#444">';

foreach ($users as $user) {
    $id       = $user['id'];
    $username = $user['username'];
    $password = $user['password'];

    // ── Detect if already a bcrypt hash ───────────────────────
    // Yii2 bcrypt hashes start with $2y$ and are 60 chars long
    $isAlreadyHashed = (
        strlen($password) === 60 &&
        strpos($password, '$2y$') === 0
    );

    if ($isAlreadyHashed) {
        echo "<div class='row warn'>⏭ Skipped user ID={$id} ({$username}) — already hashed</div>";
        $totalSkipped++;
        continue;
    }

    try {
        // ── Hash the plain text password ──────────────────────
        $hashed  = Yii::$app->security->generatePasswordHash($password);
        $authKey = Yii::$app->security->generateRandomString();

        $db->createCommand()->update('user', [
            'password' => $hashed,
            'auth_key' => $authKey,
        ], ['id' => $id])->execute();

        $totalHashed++;
        echo "<div class='row success'>✅ Hashed user ID={$id} ({$username}) — was: <span style='color:#94a3b8'>{$password}</span></div>";

    } catch (\Exception $e) {
        $errors[] = "User ID={$id}: " . $e->getMessage();
        echo "<div class='row error'>❌ Failed user ID={$id} ({$username}): " . htmlspecialchars($e->getMessage()) . "</div>";
    }
}

// ── Summary ───────────────────────────────────────────────────
echo '<hr style="border-color:#444">';
echo '<h2>📊 Summary</h2>';
echo "<p class='info'>Total users: <strong>{$totalUsers}</strong></p>";
echo "<p class='success'>✅ Passwords hashed: <strong>{$totalHashed}</strong></p>";
echo "<p class='warn'>⏭ Already hashed (skipped): <strong>{$totalSkipped}</strong></p>";

if (!empty($errors)) {
    echo "<p class='error'>❌ Errors: <strong>" . count($errors) . "</strong></p>";
    echo "<ul class='error'>";
    foreach ($errors as $err) {
        echo "<li>" . htmlspecialchars($err) . "</li>";
    }
    echo "</ul>";
} else {
    echo "<p class='success'>No errors! 🎉</p>";
}

echo '<hr style="border-color:#444">';
echo '<p style="color:#f87171; font-size:1.2em;"><strong>⚠️ DELETE this file (web/hash-passwords.php) immediately!</strong></p>';
echo '<p style="color:#94a3b8;">Note: The plain text passwords shown above are now replaced with secure hashes. Users log in with their same password as before.</p>';
