<?php
/**
 * Migrate Admin from admin table to users table
 * Give them a username instead of email
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('includes/config.php');

echo "<h2>Admin Migration: Add Usernames</h2>";
echo "<style>
body { font-family: Arial; padding: 20px; }
.success { background: #d4edda; color: #155724; padding: 15px; border-left: 4px solid #28a745; margin: 10px 0; }
.info { background: #d1ecf1; color: #0c5460; padding: 15px; border-left: 4px solid #17a2b8; margin: 10px 0; }
table { border-collapse: collapse; width: 100%; margin: 10px 0; }
th, td { border: 1px solid #ddd; padding: 10px; }
th { background: #f8f9fa; }
</style>";

// Get admin from admin table
$admin_query = mysqli_query($con, "SELECT id, username, password FROM admin");

echo "<h3>Step 1: Admins from admin table:</h3>";
echo "<table><tr><th>ID</th><th>Username</th><th>Action</th></tr>";

$admins_to_migrate = [];

while ($admin = mysqli_fetch_assoc($admin_query)) {
    echo "<tr>";
    echo "<td>{$admin['id']}</td>";
    echo "<td>{$admin['username']}</td>";

    // Check if already exists in users
    $check = mysqli_query($con, "SELECT id FROM users WHERE username = '{$admin['username']}'");

    if (mysqli_num_rows($check) > 0) {
        echo "<td style='color: green;'>✅ Already migrated</td>";
    } else {
        echo "<td style='color: orange;'>⚠️ Needs migration</td>";
        $admins_to_migrate[] = $admin;
    }

    echo "</tr>";
}
echo "</table>";

if (count($admins_to_migrate) > 0) {
    echo "<h3>Step 2: Migrating admins to users table...</h3>";

    foreach ($admins_to_migrate as $admin) {
        $username = mysqli_real_escape_string($con, $admin['username']);
        $password = $admin['password'];

        $insert = "INSERT INTO users (username, password, role) VALUES ('$username', '$password', 'admin')";

        if (mysqli_query($con, $insert)) {
            $new_id = mysqli_insert_id($con);
            echo "<div class='success'>✅ Migrated admin: <strong>$username</strong> → users.id = $new_id</div>";
        } else {
            echo "<div class='error'>❌ Failed to migrate $username: " . mysqli_error($con) . "</div>";
        }
    }
} else {
    echo "<div class='info'>ℹ️ No new admins to migrate</div>";
}

// Update existing admin (email → username)
echo "<h3>Step 3: Converting email-based admins to username-based...</h3>";

$email_admins = mysqli_query($con, "SELECT id, email FROM users WHERE role = 'admin' AND email IS NOT NULL AND username IS NULL");

if (mysqli_num_rows($email_admins) > 0) {
    echo "<table><tr><th>ID</th><th>Current Email</th><th>New Username</th><th>Action</th></tr>";

    while ($admin = mysqli_fetch_assoc($email_admins)) {
        // Create username from email (part before @)
        $username = explode('@', $admin['email'])[0];

        // Check if username exists
        $check = mysqli_query($con, "SELECT id FROM users WHERE username = '$username'");
        if (mysqli_num_rows($check) > 0) {
            $username = $username . '_admin';
        }

        echo "<tr>";
        echo "<td>{$admin['id']}</td>";
        echo "<td>{$admin['email']}</td>";
        echo "<td><strong>$username</strong></td>";

        // Update
        $update = "UPDATE users SET username = '$username', email = NULL WHERE id = {$admin['id']}";

        if (mysqli_query($con, $update)) {
            echo "<td style='color: green;'>✅ Updated</td>";
        } else {
            echo "<td style='color: red;'>❌ Failed</td>";
        }

        echo "</tr>";
    }

    echo "</table>";
} else {
    echo "<div class='info'>ℹ️ All admins already have usernames</div>";
}

// Final verification
echo "<h3>Step 4: Final Verification</h3>";

$all_users = mysqli_query($con, "SELECT id, username, email, role FROM users");

echo "<table><tr><th>ID</th><th>Username</th><th>Email</th><th>Role</th><th>Login With</th></tr>";

while ($user = mysqli_fetch_assoc($all_users)) {
    echo "<tr>";
    echo "<td>{$user['id']}</td>";
    echo "<td>" . ($user['username'] ?: '-') . "</td>";
    echo "<td>" . ($user['email'] ?: '-') . "</td>";
    echo "<td>{$user['role']}</td>";

    if ($user['role'] == 'admin') {
        echo "<td><strong>Username: {$user['username']}</strong></td>";
    } else {
        echo "<td><strong>Email: {$user['email']}</strong></td>";
    }

    echo "</tr>";
}

echo "</table>";

echo "<div class='success'>";
echo "<h4>✅ Admin Migration Complete!</h4>";
echo "<p><strong>Admin Login Credentials:</strong></p>";

$admins = mysqli_query($con, "SELECT username FROM users WHERE role = 'admin'");
echo "<ul>";
while ($admin = mysqli_fetch_assoc($admins)) {
    echo "<li>Username: <strong>{$admin['username']}</strong> | Password: (your admin password)</li>";
}
echo "</ul>";
echo "</div>";

echo "<br>";
echo "<a href='login.php' style='padding: 10px 20px; background: #4caf50; color: white; text-decoration: none; border-radius: 5px;'>Go to Login</a>";

mysqli_close($con);
?>
