<?php
function au_h($v) {
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
}

$rows = $rows ?? [];
$roles = $roles ?? [];
$conferences = $conferences ?? [];
$currentRole = $_SESSION['role'] ?? '';
$currentConference = $_SESSION['conference_id'] ?? null;

function role_allowed_for_current_admin($roleCode) {
    $current = $_SESSION['role'] ?? '';

    if ($current === 'superadmin') {
        return true;
    }

    if ($roleCode === 'superadmin') {
        return false;
    }

    if ($current === 'org_admin') {
        return in_array($roleCode, [
            'org_admin',
            'admin',
            'organizer',
            'conference_chair',
            'track_chair',
            'reviewer',
            'author'
        ], true);
    }

    return in_array($roleCode, ['reviewer', 'author'], true);
}
?>

<div class="container-fluid py-3">

    <div class="card border-0 shadow-sm mb-4" style="border-radius:22px;">
        <div class="card-body d-flex justify-content-between align-items-center flex-wrap gap-3">
            <div>
                <h3 class="fw-bold mb-1"><i class="fa fa-users"></i> إدارة المستخدمين</h3>
                <div class="text-muted">عرض المستخدمين حسب صلاحيات المؤسسة والمؤتمر الحالي</div>
            </div>
            <a class="btn btn-outline-primary" href="/easychair/select-conference">تغيير المؤتمر</a>
        </div>
    </div>

    <div class="card border-0 shadow-sm mb-4" style="border-radius:22px;">
        <div class="card-body">
            <h5 class="fw-bold mb-3">إضافة مستخدم تجريبي / فعلي</h5>

            <form method="post" action="/easychair/admin/users/store" class="row g-2">
                <div class="col-md-2">
                    <input name="first_name" class="form-control" placeholder="الاسم" required>
                </div>
                <div class="col-md-2">
                    <input name="last_name" class="form-control" placeholder="اللقب" required>
                </div>
                <div class="col-md-3">
                    <input name="email" type="email" class="form-control" placeholder="Email" required>
                </div>
                <div class="col-md-2">
                    <input name="password" type="password" class="form-control" placeholder="Password" required>
                </div>
                <div class="col-md-3">
                    <input name="job_title" class="form-control" placeholder="Job title">
                </div>

                <div class="col-md-3">
                    <select name="role_id" class="form-select" required>
                        <?php foreach ($roles as $role): ?>
                            <?php if (!role_allowed_for_current_admin($role['code'])) continue; ?>
                            <option value="<?= (int)$role['id'] ?>">
                                <?= au_h($role['code']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-4">
                    <select name="conference_id" class="form-select">
                        <?php foreach ($conferences as $conf): ?>
                            <option value="<?= (int)$conf['id'] ?>" <?= ((int)$currentConference === (int)$conf['id']) ? 'selected' : '' ?>>
                                <?= au_h(($conf['short_name'] ?? '') . ' - ' . (($conf['title_ar'] ?? '') ?: ($conf['title_en'] ?? ''))) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-2">
                    <button class="btn btn-success w-100">
                        <i class="fa fa-plus"></i> إضافة
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div class="card border-0 shadow-sm" style="border-radius:22px;">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover align-middle">
                    <thead class="table-dark">
                    <tr>
                        <th>ID</th>
                        <th>Org</th>
                        <th>الاسم</th>
                        <th>Email</th>
                        <th>Global Role</th>
                        <th>Conference Roles</th>
                        <th>الحالة</th>
                        <th>تحديث</th>
                    </tr>
                    </thead>
                    <tbody>

                    <?php foreach($rows as $r): ?>
                        <tr>
                            <td><?= (int)$r['id'] ?></td>
                            <td><?= (int)($r['org_id'] ?? 0) ?></td>
                            <td class="fw-bold"><?= au_h(($r['first_name'] ?? '') . ' ' . ($r['last_name'] ?? '')) ?></td>
                            <td><?= au_h($r['email'] ?? '') ?></td>
                            <td>
                                <span class="badge bg-secondary"><?= au_h($r['global_role'] ?? '') ?></span>
                            </td>
                            <td>
                                <span class="text-muted small"><?php
$rolesList =
    explode(
        ',',
        $r['conference_roles'] ?? ''
    );
?>

<div class="d-flex flex-wrap gap-1">

<?php foreach ($rolesList as $roleName): ?>

    <?php
    $roleName = trim($roleName);

    if (!$roleName) {
        continue;
    }
    ?>

    <span class="badge bg-primary">

        <?= au_h($roleName) ?>

    </span>

<?php endforeach; ?>

</div></span>
                            </td>
                            <td>
                                <?php if (!empty($r['is_active'])): ?>
                                    <span class="badge bg-success">active</span>
                                <?php else: ?>
                                    <span class="badge bg-danger">inactive</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <form method="post" action="/easychair/admin/users/update" class="d-flex gap-2">
                                    <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">

                                    <select name="role_id" class="form-select form-select-sm">
                                        <?php foreach ($roles as $role): ?>
                                            <?php if (!role_allowed_for_current_admin($role['code'])) continue; ?>
                                            <option value="<?= (int)$role['id'] ?>" <?= ((int)$r['role_id'] === (int)$role['id']) ? 'selected' : '' ?>>
                                                <?= au_h($role['code']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>

                                    <select name="conference_id" class="form-select form-select-sm">
                                        <?php foreach ($conferences as $conf): ?>
                                            <option value="<?= (int)$conf['id'] ?>" <?= ((int)$currentConference === (int)$conf['id']) ? 'selected' : '' ?>>
                                                <?= au_h($conf['short_name'] ?? ('#'.$conf['id'])) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>

                                    <button class="btn btn-primary btn-sm">
                                        <i class="fa fa-save"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>

                    <?php if (empty($rows)): ?>
                        <tr>
                            <td colspan="8" class="text-center text-muted py-4">
                                لا يوجد مستخدمون ضمن هذا النطاق.
                            </td>
                        </tr>
                    <?php endif; ?>

                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div>
