<?php
require __DIR__ . '/../config/bootstrap.php';
require_once BASE_PATH . '/app/helpers/conference_scope.php';

use App\Core\Database;

$db = Database::getInstance();

$emails = array_slice($argv, 1);
if (!$emails) {
    $emails = [
        'seed.orgadmin@easychair.test',
        'seed.chair@easychair.test',
        'seed.organizer@easychair.test',
        'seed.author@easychair.test',
        'seed.reviewer@easychair.test',
    ];
}

foreach ($emails as $email) {
    $_SESSION = [];

    $stmt = $db->prepare("SELECT * FROM users WHERE email=? LIMIT 1");
    $stmt->execute([$email]);
    $u = $stmt->fetch(PDO::FETCH_ASSOC);

    echo "\n====================\n$email\n";

    if (!$u) {
        echo "User not found\n";
        continue;
    }

    $_SESSION['user_id'] = (int)$u['id'];
    $_SESSION['email'] = $email;
    $_SESSION['org_id'] = (int)($u['org_id'] ?? 0);
    $_SESSION['role'] = (string)($u['role'] ?? '');

    if ($_SESSION['role'] === '') {
        if (str_contains($email, 'orgadmin')) $_SESSION['role'] = 'org_admin';
        elseif (str_contains($email, 'chair')) $_SESSION['role'] = 'conference_chair';
        elseif (str_contains($email, 'organizer')) $_SESSION['role'] = 'organizer';
        elseif (str_contains($email, 'reviewer')) $_SESSION['role'] = 'reviewer';
        elseif (str_contains($email, 'author')) $_SESSION['role'] = 'author';
    }

    $_SESSION['conference_role'] = $_SESSION['role'];

    echo "Before: role=" . ($_SESSION['conference_role'] ?? '') .
        " org=" . ($_SESSION['org_id'] ?? '') .
        " conf=" . ($_SESSION['conference_id'] ?? 'NONE') . "\n";

    $ok = ec_scope_auto_select_conference(true);

    echo "Auto selected: " . ($ok ? 'YES' : 'NO') . "\n";
    echo "After:  role=" . ($_SESSION['conference_role'] ?? '') .
        " org=" . ($_SESSION['org_id'] ?? '') .
        " conf=" . ($_SESSION['conference_id'] ?? 'NONE') .
        " short=" . ($_SESSION['conference_short_name'] ?? '') . "\n";

    echo "conference_list=" . implode(',', $_SESSION['conference_list'] ?? []) . "\n";
}
