<?php
require_once "../../../controllers/routing/default_values.php";
require_once SERVER_AUTH."db_con_live_static.php";
require_once SERVER_CORE."utilities/temp_function.php";





echo "<h2>Password Migration: AES to SHA-256</h2>";
echo "<p>Starting migration process...</p>";

// Get all users and their encrypted passwords
$sql = "SELECT user_id, password FROM user_activity_management";
$result = $conn->query($sql);

if($result) {
    $total_users = $result->num_rows;
    $migrated = 0;
    $failed = 0;
    
    echo "<p>Found $total_users users to process.</p>";
    
    while($row = $result->fetch_assoc()) {
        $user_id = $row["user_id"];
        $aes_password = $row["password"];
        
        try {
            // Decode the password using AES method (function from temp_function.php)
            $plaintext_password = url_decode($aes_password);
            
            if($plaintext_password === false || $plaintext_password === '') {
                echo "Warning: Failed to decode password for user_id: $user_id<br>";
                $failed++;
                continue;
            }
            
            // Re-encode using SHA-256
            $new_password = auth_encode_sha256($plaintext_password);
            
            // Update the user table
            $update_sql = "UPDATE user_activity_management SET password='$new_password' WHERE user_id='$user_id'";
            $update_result = $conn->query($update_sql);
            
            if($update_result) {
                // Also update password_logs table if needed
                // $log_sql = "INSERT INTO password_logs SET user_id='$user_id', password='$new_password', entry_at='".date('Y-m-d H:i:s')."', entry_by='$user_id'";
                // $conn->query($log_sql);
                
                $migrated++;
                echo "Successfully migrated password for user ID: $user_id<br>";
            } else {
                echo "Failed to update password for user ID: $user_id - " . $conn->error . "<br>";
                $failed++;
            }
        } catch(Exception $e) {
            echo "Error processing user ID: $user_id - " . $e->getMessage() . "<br>";
            $failed++;
        }
    }
    
    echo "<h3>Migration Summary</h3>";
    echo "<p>Total users: $total_users</p>";
    echo "<p>Successfully migrated: $migrated</p>";
    echo "<p>Failed: $failed</p>";
    
    if($migrated == $total_users) {
        echo "<p style='color:green;'>All passwords successfully migrated to SHA-256!</p>";
    } else {
        echo "<p style='color:orange;'>Some passwords could not be migrated. Please check the errors above.</p>";
    }
} else {
    echo "Error: " . $conn->error;
}

echo "<p><a href='index.php'>Return to main page</a></p>";
?>