<?php
/**
 * Create Dummy Users Directly via PHP
 */

// Database configuration
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);
        putenv(sprintf('%s=%s', trim($name), trim($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";

$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error . "\n");
}

echo "Connected to database: {$database}\n\n";

// Define dummy users
$dummyUsers = [
    [
        'name' => 'Super Admin',
        'email' => 'superadmin@flex.com',
        'mobile' => '9999999999',
        'password' => 'Super@123',
        'address' => 'Super Admin Office, Main Street',
        'pin_code' => '110001',
        'user_type' => 'buyer',
        'role' => 'super_admin',
        'reliability_score' => 100
    ],
    [
        'name' => 'Admin User',
        'email' => 'admin@flex.com',
        'mobile' => '9888888888',
        'password' => 'Admin@123',
        'address' => 'Admin Office, Central Avenue',
        'pin_code' => '110002',
        'user_type' => 'buyer',
        'role' => 'admin',
        'reliability_score' => 80
    ],
    [
        'name' => 'Test Seller',
        'email' => 'seller@flex.com',
        'mobile' => '9777777777',
        'password' => 'Seller@123',
        'address' => 'Seller Shop, Market Road',
        'pin_code' => '110003',
        'user_type' => 'seller',
        'role' => 'seller',
        'reliability_score' => 60
    ],
    [
        'name' => 'Delivery Person',
        'email' => 'delivery@flex.com',
        'mobile' => '9666666666',
        'password' => 'Delivery@123',
        'address' => 'Delivery Hub, Station Road',
        'pin_code' => '110004',
        'user_type' => 'buyer',
        'role' => 'delivery',
        'reliability_score' => 70
    ],
    [
        'name' => 'Test Buyer',
        'email' => 'buyer@flex.com',
        'mobile' => '9555555555',
        'password' => 'Buyer@123',
        'address' => '123 Buyer Street, City Center',
        'pin_code' => '110005',
        'user_type' => 'buyer',
        'role' => 'buyer',
        'reliability_score' => 50
    ]
];

// Delete existing dummy users
echo "Cleaning up existing dummy users...\n";
$emails = array_map(function($u) { return $u['email']; }, $dummyUsers);
$emailsStr = "'" . implode("','", $emails) . "'";
$conn->query("DELETE FROM users WHERE email IN ({$emailsStr})");
echo "Deleted " . $conn->affected_rows . " existing dummy user(s)\n\n";

// Insert new users
echo "Creating dummy users:\n";
$stmt = $conn->prepare("
    INSERT INTO users 
    (name, email, mobile, password, address, pin_code, user_type, role, reliability_score, is_blocked, is_verified, created_at, updated_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 1, NOW(), NOW())
");

foreach ($dummyUsers as $user) {
    $passwordHash = password_hash($user['password'], PASSWORD_DEFAULT);
    
    $stmt->bind_param(
        "ssssssssi",
        $user['name'],
        $user['email'],
        $user['mobile'],
        $passwordHash,
        $user['address'],
        $user['pin_code'],
        $user['user_type'],
        $user['role'],
        $user['reliability_score']
    );
    
    if ($stmt->execute()) {
        echo "✓ Created: {$user['name']} ({$user['email']}) - Password: {$user['password']}\n";
        
        // Verify password works
        $userId = $stmt->insert_id;
        $checkStmt = $conn->prepare("SELECT password FROM users WHERE id = ?");
        $checkStmt->bind_param("i", $userId);
        $checkStmt->execute();
        $result = $checkStmt->get_result();
        $row = $result->fetch_assoc();
        
        if (password_verify($user['password'], $row['password'])) {
            echo "  ✓ Password verification: PASS\n";
        } else {
            echo "  ✗ Password verification: FAIL\n";
        }
    } else {
        echo "✗ Failed to create: {$user['email']} - Error: {$stmt->error}\n";
    }
}

$stmt->close();

// Verify all users
echo "\n=== VERIFICATION ===\n";
$result = $conn->query("
    SELECT id, name, email, role, user_type, is_verified, reliability_score 
    FROM users 
    WHERE email LIKE '%@flex.com' 
    ORDER BY FIELD(role, 'super_admin', 'admin', 'seller', 'delivery', 'buyer')
");

if ($result && $result->num_rows > 0) {
    echo "Found {$result->num_rows} dummy user(s):\n\n";
    echo str_pad("ID", 5) . str_pad("Name", 20) . str_pad("Email", 30) . str_pad("Role", 15) . "Verified\n";
    echo str_repeat("-", 90) . "\n";
    
    while ($row = $result->fetch_assoc()) {
        $verified = $row['is_verified'] ? '✓' : '✗';
        echo str_pad($row['id'], 5) . 
             str_pad($row['name'], 20) . 
             str_pad($row['email'], 30) . 
             str_pad($row['role'], 15) . 
             $verified . "\n";
    }
} else {
    echo "No dummy users found.\n";
}

$conn->close();

echo "\n=== ALL DONE! ===\n";
echo "\nLogin URL: http://localhost:8080/login\n";
echo "\n=== TEST CREDENTIALS ===\n";
echo "Super Admin: superadmin@flex.com / Super@123\n";
echo "Admin:       admin@flex.com / Admin@123\n";
echo "Seller:      seller@flex.com / Seller@123\n";
echo "Delivery:    delivery@flex.com / Delivery@123\n";
echo "Buyer:       buyer@flex.com / Buyer@123\n";
echo "\nFor more details, see DUMMY_USERS.md\n";
