<?php
/**
 * Seed one demo INTERNAL login per role, so each role's portal view can be tested.
 * Every login uses the same password (change later in Users admin):
 *
 *     Password:  ChangeMe@2026
 *     Emails:    <role_code>@medmecs.local   (e.g. supervisor@medmecs.local)
 *
 * Idempotent — safe to re-run. Each demo login is given EXACTLY its one role.
 *
 *   php bin/seed-role-logins.php
 */
require __DIR__ . '/../includes/config.php';

$pdo      = db();
$password = 'ChangeMe@2026';
$hash     = password_hash($password, PASSWORD_BCRYPT);

/* Make sure the extra named roles + their permission maps exist (idempotent). */
$extra = __DIR__ . '/../sql/seed-additional-roles.sql';
if (is_file($extra)) {
    $sql = preg_replace('/^\s*USE\s+[^;]+;/mi', '', (string) file_get_contents($extra)); // DB already selected
    try { $pdo->exec($sql); } catch (Throwable $e) { fwrite(STDERR, "warn: could not apply seed-additional-roles.sql: ".$e->getMessage()."\n"); }
}

/* role code => display name. sysadmin is intentionally omitted (admin@medmecs.local already exists). */
$roles = [
    'developer'         => 'Developer (demo)',
    'vertical_manager'  => 'Vertical Manager (demo)',
    'client_manager'    => 'Client Manager (demo)',
    'process_lead'      => 'Process Lead (demo)',
    'analyst'           => 'Analyst (demo)',
    'auditor'           => 'Auditor (demo)',
    'report_controller' => 'Report Controller (demo)',
    'manager'           => 'Manager (demo)',
    'supervisor'        => 'Supervisor (demo)',
    'user'              => 'User (demo)',
];

$insUser = $pdo->prepare(
    "INSERT INTO users (name,email,password,user_type,status,must_change_password,password_changed_at,created_at,updated_at)
     VALUES (?,?,?,'internal','active',0,NOW(),NOW(),NOW())
     ON DUPLICATE KEY UPDATE name=VALUES(name), status='active', password=VALUES(password), must_change_password=0, updated_at=NOW()"
);
$findUser  = $pdo->prepare("SELECT id FROM users WHERE email=?");
$findRole  = $pdo->prepare("SELECT id FROM roles WHERE code=?");
$clearRole = $pdo->prepare("DELETE FROM user_roles WHERE user_id=?");
$assign    = $pdo->prepare("INSERT IGNORE INTO user_roles (user_id, role_id) VALUES (?,?)");

printf("%-20s %-34s %s\n", 'ROLE', 'EMAIL', 'PASSWORD');
printf("%s\n", str_repeat('-', 74));
$made = 0;
foreach ($roles as $code => $name) {
    $email = $code . '@medmecs.local';
    $findRole->execute([$code]);
    $rid = (int) $findRole->fetchColumn();
    if (!$rid) { fwrite(STDERR, "  ! role '$code' not found — skipped\n"); continue; }
    $insUser->execute([$name, $email, $hash]);
    $findUser->execute([$email]);
    $uid = (int) $findUser->fetchColumn();
    $clearRole->execute([$uid]);          // demo login carries exactly its one role
    $assign->execute([$uid, $rid]);
    printf("%-20s %-34s %s\n", $code, $email, $password);
    $made++;
}
echo "\n$made demo logins ready. Sign in at /login.php with any email above.\n";
echo "Tip: change name/email/password later in admin/users.php.\n";
