<?php
/**
 * Import SQL file to create dummy users
 */

// Database configuration from .env
if (file_exists(__DIR__ . '/.env')) {
    $lines = file(__DIR__ . '/.env', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) continue;
        if (strpos($line, '=') === false) continue;
        list($name, $value) = explode('=', $line, 2);
        $name = trim($name);
        $value = trim($value);
        if (!array_key_exists($name, $_SERVER) && !array_key_exists($name, $_ENV)) {
            putenv(sprintf('%s=%s', $name, $value));
            $_ENV[$name] = $value;
            $_SERVER[$name] = $value;
        }
    }
}

$host = getenv('database.default.hostname') ?: 'localhost';
$database = getenv('database.default.database') ?: 'flex_market';
$username = getenv('database.default.username') ?: 'root';
$password = getenv('database.default.password') ?: '';

echo "=== CREATING DUMMY USERS ===\n\n";
echo "Connecting to database: {$database}\n";

// Connect to database
$conn = new mysqli($host, $username, $password, $database);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error . "\n");
}

echo "Connected successfully!\n\n";

// Read and execute SQL file
$sqlFile = __DIR__ . '/create_dummy_users.sql';
if (!file_exists($sqlFile)) {
    die("Error: create_dummy_users.sql not found!\n");
}

$sql = file_get_contents($sqlFile);

// Split SQL into individual queries
$queries = array_filter(array_map('trim', explode(';', $sql)));

$successCount = 0;
$errorCount = 0;

foreach ($queries as $query) {
    // Skip empty queries and comments
    if (empty($query) || strpos($query, '--') === 0) {
        continue;
    }
    
    // Execute query
    if ($conn->query($query)) {
        $successCount++;
        
        // Show affected rows for important queries
        if (stripos($query, 'INSERT') !== false) {
            echo "✓ Inserted user (ID: {$conn->insert_id})\n";
        } elseif (stripos($query, 'DELETE') !== false && $conn->affected_rows > 0) {
            echo "✓ Deleted {$conn->affected_rows} existing dummy user(s)\n";
        } elseif (stripos($query, 'SELECT') !== false) {
            $result = $conn->query($query);
            if ($result && $result->num_rows > 0) {
                echo "\n";
                while ($row = $result->fetch_assoc()) {
                    if (isset($row['INFO'])) {
                        // Display credentials table
                        echo implode("\t", $row) . "\n";
                    } elseif (isset($row['email'])) {
                        // Display user info
                        echo "User: {$row['name']} ({$row['email']}) - Role: {$row['role']}\n";
                    }
                }
                echo "\n";
            }
        }
    } else {
        // Only show errors for important queries
        if (stripos($query, 'INSERT') !== false || stripos($query, 'DELETE') !== false) {
            echo "✗ Error: " . $conn->error . "\n";
            $errorCount++;
        }
    }
}

echo "\n=== SUMMARY ===\n";
echo "Successful operations: {$successCount}\n";
if ($errorCount > 0) {
    echo "Errors: {$errorCount}\n";
}

// Verify users were created
echo "\n=== VERIFICATION ===\n";
$result = $conn->query("SELECT id, name, email, role, is_verified FROM users WHERE email LIKE '%@flex.com' ORDER BY id");

if ($result && $result->num_rows > 0) {
    echo "Found {$result->num_rows} dummy user(s):\n\n";
    while ($row = $result->fetch_assoc()) {
        $verified = $row['is_verified'] ? '✓' : '✗';
        echo "{$verified} ID:{$row['id']} - {$row['name']} ({$row['email']}) - Role: {$row['role']}\n";
    }
} else {
    echo "No dummy users found. There may have been an error.\n";
}

$conn->close();

echo "\n=== DONE ===\n";
echo "You can now test login at: http://localhost:8080/login\n";
echo "Use credentials from DUMMY_USERS.md\n";
