<?php
require_once __DIR__ . '/../api/config.php';
require_once __DIR__ . '/../includes/Database.php';

header('Content-Type: text/plain');

echo "--- Quicky Quicky Demo Data Setup ---\n\n";

// 1. Check Database Connection
echo "1. Checking database connection...\n";
try {
    $db = new Database();
    echo "   Database connection successful!\n\n";
} catch (PDOException $e) {
    echo "   Database connection FAILED: " . $e->getMessage() . "\n";
    echo "   Please ensure your database is running and 'api/config.php' has correct credentials.\n";
    exit;
}

// 2. Define Demo Users
echo "2. Managing demo users...\n";
$demoUsers = [
    [
        'email' => 'admin@mabanga.com',
        'name' => 'Admin User',
        'role' => 'admin',
        'password' => '123456'
    ],
    [
        'email' => 'customer@mabanga.com',
        'name' => 'Customer User',
        'role' => 'customer',
        'password' => '123456'
    ],
    [
        'email' => 'shop@mabanga.com',
        'name' => 'Shop Owner',
        'role' => 'shop_owner',
        'password' => '123456'
    ],
    [
        'email' => 'rider@mabanga.com',
        'name' => 'Rider User',
        'role' => 'rider',
        'password' => '123456'
    ],
];

foreach ($demoUsers as $userData) {
    $email = $userData['email'];
    $name = $userData['name'];
    $role = $userData['role'];
    $plainPassword = $userData['password'];
    $hashedPassword = password_hash($plainPassword, PASSWORD_DEFAULT);

    echo "   Processing user: {$email} ({$role})\n";

    // Check if user exists
    $stmt = $db->query("SELECT id, password FROM users WHERE email = ?", [$email]);
    $existingUser = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($existingUser) {
        // User exists, check password
        if (!password_verify($plainPassword, $existingUser['password'])) {
            // Password needs update
            $db->query("UPDATE users SET password = ? WHERE id = ?", [$hashedPassword, $existingUser['id']]);
            echo "      - Password updated for existing user.\n";
        } else {
            echo "      - User exists with correct password. No changes needed.\n";
        }
    } else {
        // User does not exist, create new user
        $db->query(
            "INSERT INTO users (email, password, name, role) VALUES (?, ?, ?, ?)",
            [$email, $hashedPassword, $name, $role]
        );
        echo "      - New user created successfully.\n";
    }
}

echo "\n--- Demo Data Setup Complete ---\n";
echo "You can now log in with the following credentials:\n";
foreach ($demoUsers as $userData) {
    echo "- Email: {$userData['email']}, Password: {$userData['password']}\n";
}

?>