<?php
require __DIR__ . '/../vendor/autoload.php';

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/..');
$dotenv->safeLoad();

use App\Database;

$pdo = Database::getConnection();

$roles = ['admin','manager','user'];

$pdo->beginTransaction();
try {
    $stmt = $pdo->prepare('INSERT IGNORE INTO roles (name) VALUES (:name)');
    foreach ($roles as $r) {
        $stmt->execute([':name' => $r]);
    }

    $roleStmt = $pdo->query('SELECT id,name FROM roles');
    $roleMap = [];
    foreach ($roleStmt->fetchAll() as $row) {
        $roleMap[$row['name']] = $row['id'];
    }

    $users = [
        ['Admin User','admin@example.com','password','admin'],
        ['Manager User','manager@example.com','password','manager'],
        ['Regular User','user@example.com','password','user']
    ];

    $ins = $pdo->prepare('INSERT IGNORE INTO users (name,full_name,username,email,password,password_hash,role_id,status) VALUES (:name,:full_name,:username,:email,:password,:password_hash,:role_id,:status)');
    foreach ($users as $u) {
        $username = explode('@', $u[1])[0];
        $ins->execute([
            ':name' => $u[0],
            ':full_name' => $u[0],
            ':username' => $username,
            ':email' => $u[1],
            ':password' => password_hash($u[2], PASSWORD_DEFAULT),
            ':password_hash' => password_hash($u[2], PASSWORD_DEFAULT),
            ':role_id' => $roleMap[$u[3]] ?? 3,
            ':status' => 'active',
        ]);
    }

    $pdo->commit();
    echo "Seed complete.\n";
} catch (Exception $e) {
    $pdo->rollBack();
    echo "Seed failed: " . $e->getMessage() . "\n";
}
