<?php
namespace App\Controllers;

use App\Core\Database;

require_once BASE_PATH . '/app/helpers/conference_scope.php';

class UserScopeAuditController
{
    protected function db()
    {
        return Database::getInstance();
    }

    private function startSession(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }
    }

    private function requireSuperAdmin(): void
    {
        $this->startSession();

        if (empty($_SESSION['user_id'])) {
            header("Location: /easychair/login");
            exit;
        }

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

        if ($role !== 'super_admin') {
            http_response_code(403);
            exit('Only super admin can access User Scope Audit.');
        }
    }

    public function index()
    {
        $this->requireSuperAdmin();

        $q = trim((string)($_GET['q'] ?? ''));

        if ($q !== '') {
            $stmt = $this->db()->prepare("
                SELECT *
                FROM users
                WHERE email LIKE ? OR first_name LIKE ? OR last_name LIKE ? OR name LIKE ?
                ORDER BY id DESC
                LIMIT 80
            ");
            $like = '%' . $q . '%';
            $stmt->execute([$like, $like, $like, $like]);
        } else {
            $stmt = $this->db()->query("
                SELECT *
                FROM users
                ORDER BY id DESC
                LIMIT 80
            ");
        }

        $users = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        $rows = [];

        foreach ($users as $u) {
            $_SESSION['_scope_audit_old'] = $_SESSION;

            $_SESSION['user_id'] = (int)$u['id'];
            $_SESSION['email'] = (string)($u['email'] ?? '');
            $_SESSION['org_id'] = (int)($u['org_id'] ?? 0);
            $rawRole = (string)($u['role'] ?? $u['role_code'] ?? $u['user_role'] ?? '');
            $resolvedRole = function_exists('ec_scope_normalize_role') ? ec_scope_normalize_role($rawRole, (string)($u['email'] ?? '')) : $rawRole;
            $_SESSION['role'] = $resolvedRole;
            $_SESSION['user_role'] = $resolvedRole;
            $_SESSION['conference_role'] = $resolvedRole;

            $available = ec_scope_available_conferences();
            $selected = null;

            if (ec_scope_role() !== 'super_admin') {
                // ec_scope_auto_select_conference(true);
                $selected = [
                    'conference_id' => $_SESSION['conference_id'] ?? null,
                    'short_name' => $_SESSION['conference_short_name'] ?? '',
                    'org_id' => $_SESSION['org_id'] ?? null,
                    'role' => $_SESSION['conference_role'] ?? '',
                    'landing' => ec_scope_landing_url(),
                ];
            } else {
                $selected = [
                    'conference_id' => null,
                    'short_name' => 'Superadmin selector',
                    'org_id' => $_SESSION['org_id'] ?? null,
                    'role' => 'super_admin',
                    'landing' => ec_scope_landing_url('super_admin'),
                ];
            }

            $rows[] = [
                'user' => $u,
                'available' => $available,
                'selected' => $selected,
            ];

            $_SESSION = $_SESSION['_scope_audit_old'];
            unset($_SESSION['_scope_audit_old']);
        }

        ob_start();
        require BASE_PATH . '/app/views/admin/user_scope_audit/index.php';
        $content = ob_get_clean();

        require BASE_PATH . '/app/views/layouts/admin_layout.php';
    }
}
