<?php
namespace App\Controllers;

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

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

use App\Core\Database;

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

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

    private function role(): string
    {
        return (string)($_SESSION['role'] ?? $_SESSION['user_role'] ?? '');
    }

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

  error_log(
        'ADMIN USERS ROLE=' .
        (
            $_SESSION['role']
            ?? $_SESSION['user_role']
            ?? 'NULL'
        )
    );

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

if (!in_array(strtolower($this->role()), [

    'superadmin',
'superadmin',
    'super admin',
    'org_admin',
    'org admin',
    'admin',
    'organizer',
    'conference_chair',
    'conference chair',
    'track_chair',
    'track chair'

], true)) {        
    http_response_code(403);
            exit("Access denied.");
        }
    }

    private function orgId(): int
    {
        return (int)($_SESSION['org_id'] ?? 0);
    }

    private function conferenceId(): int
    {
        return (int)($_SESSION['conference_id'] ?? $_SESSION['current_conference_id'] ?? 0);
    }

    private function canManageRole(string $targetRole): bool
    {
        $role = $this->role();

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

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

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

        return in_array($targetRole, [
            'reviewer',
            'author'
        ], true);
    }

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

        $db = $this->db();
        $role = $this->role();
        $orgId = $this->orgId();
        $conferenceId = $this->conferenceId();

        $params = [];
        $where = " WHERE u.is_active IN (0,1) ";

        if ($role === 'superadmin') {
            // all users
        } elseif ($role === 'org_admin') {
            $where .= " AND u.org_id = ? ";
            $params[] = $orgId;
        } else {
            if ($conferenceId <= 0) {
                header("Location: /easychair/select-conference");
                exit;
            }

            $where .= "
                AND u.org_id = ?
                AND EXISTS (
                    SELECT 1
                    FROM user_conferences ucx
                    WHERE ucx.user_id = u.id
                      AND ucx.conference_id = ?
                )
            ";
            $params[] = $orgId;
            $params[] = $conferenceId;
        }

        $stmt = $db->prepare("
            SELECT
                u.id,
                u.org_id,
                u.first_name,
                u.last_name,
                u.email,
                u.mobile,
                u.job_title,
                u.is_active,
                u.role_id,
                r.code AS global_role,
                r.name AS global_role_name,
                GROUP_CONCAT(DISTINCT CONCAT(c.short_name, ':', cr.code) ORDER BY c.id SEPARATOR ', ') AS conference_roles
            FROM users u
            LEFT JOIN roles r ON r.id = u.role_id
            LEFT JOIN user_conferences uc ON uc.user_id = u.id
            LEFT JOIN conferences c ON c.id = uc.conference_id
            LEFT JOIN roles cr ON cr.id = uc.role_id
            {$where}
            GROUP BY
                u.id, u.org_id, u.first_name, u.last_name, u.email, u.mobile,
                u.job_title, u.is_active, u.role_id, r.code, r.name
            ORDER BY u.org_id ASC, u.id DESC
        ");

        $stmt->execute($params);
        $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $roles = $db->query("
            SELECT id, name, code
            FROM roles
            ORDER BY id
        ")->fetchAll(\PDO::FETCH_ASSOC);

        $conferences = [];

        if ($role === 'superadmin') {
            $conferences = $db->query("
                SELECT id, org_id, short_name, title_ar, title_en
                FROM conferences
                ORDER BY org_id, id
            ")->fetchAll(\PDO::FETCH_ASSOC);
        } elseif ($role === 'org_admin') {
            $stmt = $db->prepare("
                SELECT id, org_id, short_name, title_ar, title_en
                FROM conferences
                WHERE org_id = ?
                ORDER BY id
            ");
            $stmt->execute([$orgId]);
            $conferences = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        } else {
            $stmt = $db->prepare("
                SELECT id, org_id, short_name, title_ar, title_en
                FROM conferences
                WHERE id = ?
                  AND org_id = ?
                ORDER BY id
            ");
            $stmt->execute([$conferenceId, $orgId]);
            $conferences = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        }

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

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

    public function store()
    {
$this->requireAdmin();

        $db = $this->db();

        $first = trim($_POST['first_name'] ?? '');
        $last = trim($_POST['last_name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $password = (string)($_POST['password'] ?? '');
        $roleId = (int)($_POST['role_id'] ?? 5);
        $conferenceId = (int)($_POST['conference_id'] ?? $this->conferenceId());

        if (!$first || !$last || !$email || !$password || !$roleId) {
            exit("Missing required fields.");
        }

        $stmt = $db->prepare("SELECT code FROM roles WHERE id = ? LIMIT 1");
        $stmt->execute([$roleId]);
        $targetRole = (string)$stmt->fetchColumn();

        if (!$targetRole || !$this->canManageRole($targetRole)) {
            http_response_code(403);
            exit("You cannot assign this role.");
        }

        $orgId = $this->orgId();

        if (ec_is_superadmin()) {
            if ($conferenceId > 0) {
                $stmt = $db->prepare("SELECT org_id FROM conferences WHERE id = ? LIMIT 1");
                $stmt->execute([$conferenceId]);
                $orgId = (int)$stmt->fetchColumn();
            } else {
                $orgId = (int)($_POST['org_id'] ?? 0);
            }
        }

        if ($orgId <= 0) {
            exit("Organization context missing.");
        }

        $stmt = $db->prepare("
            INSERT INTO users
            (org_id, role_id, first_name, last_name, email, password_hash, mobile, job_title, is_active, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, NOW())
        ");

        $stmt->execute([
            $orgId,
            $roleId,
            $first,
            $last,
            $email,
            password_hash($password, PASSWORD_BCRYPT),
            trim($_POST['mobile'] ?? ''),
            trim($_POST['job_title'] ?? '')
        ]);

        $userId = (int)$db->lastInsertId();

        if ($conferenceId > 0) {
            $stmt = $db->prepare("
                INSERT INTO user_conferences (user_id, conference_id, role_id)
                VALUES (?, ?, ?)
            ");
            $stmt->execute([$userId, $conferenceId, $roleId]);
        }

        header("Location: /easychair/admin/users");
        exit;
    }

    public function update()
{
    $this->requireAdmin();

    $db = $this->db();

    $id = (int)($_POST['id'] ?? 0);
    $roleId = (int)($_POST['role_id'] ?? 0);
    $conferenceId = (int)($_POST['conference_id'] ?? $this->conferenceId());

    if (!$id || !$roleId) {
        exit("Missing data.");
    }

    $stmt = $db->prepare("
        SELECT code 
        FROM roles 
        WHERE id = ? 
        LIMIT 1
    ");
    $stmt->execute([$roleId]);

    $targetRole = (string)$stmt->fetchColumn();

    if (!$targetRole || !$this->canManageRole($targetRole)) {
        http_response_code(403);
        exit("You cannot assign this role.");
    }

    if (!ec_is_superadmin()) {

        $stmt = $db->prepare("
            SELECT id
            FROM users
            WHERE id = ?
              AND org_id = ?
            LIMIT 1
        ");

        $stmt->execute([
            $id,
            $this->orgId()
        ]);

        if (!$stmt->fetchColumn()) {
            http_response_code(403);
            exit("User is outside your organization.");
        }
    }

    /*
    |--------------------------------------------------------------------------
    | Update Main User Role
    |--------------------------------------------------------------------------
    */
    $stmt = $db->prepare("
        UPDATE users
        SET role_id = ?
        WHERE id = ?
    ");

    $stmt->execute([
        $roleId,
        $id
    ]);

    /*
    |--------------------------------------------------------------------------
    | Conference Role Mapping
    |--------------------------------------------------------------------------
    */
    if ($conferenceId > 0) {

        if (!ec_is_superadmin()) {

            $stmt = $db->prepare("
                SELECT id
                FROM conferences
                WHERE id = ?
                  AND org_id = ?
                LIMIT 1
            ");

            $stmt->execute([
                $conferenceId,
                $this->orgId()
            ]);

            if (!$stmt->fetchColumn()) {
                http_response_code(403);
                exit("Conference is outside your organization.");
            }
        }

        /*
        |--------------------------------------------------------------------------
        | Check Existing Mapping
        |--------------------------------------------------------------------------
        */
        $stmt = $db->prepare("
            SELECT id
            FROM user_conferences
            WHERE user_id = ?
              AND conference_id = ?
            LIMIT 1
        ");

        $stmt->execute([
            $id,
            $conferenceId
        ]);

        $exists = $stmt->fetchColumn();

        /*
        |--------------------------------------------------------------------------
        | Insert New Mapping
        |--------------------------------------------------------------------------
        */
        if (!$exists) {

            $stmt = $db->prepare("
                INSERT INTO user_conferences
                (
                    user_id,
                    conference_id,
                    role_id
                )
                VALUES (?, ?, ?)
            ");

            $stmt->execute([
                $id,
                $conferenceId,
                $roleId
            ]);

        } else {

            /*
            |--------------------------------------------------------------------------
            | Update Existing Mapping
            |--------------------------------------------------------------------------
            */
            $stmt = $db->prepare("
                UPDATE user_conferences
                SET role_id = ?
                WHERE user_id = ?
                  AND conference_id = ?
            ");

            $stmt->execute([
                $roleId,
                $id,
                $conferenceId
            ]);
        }
    }

    header("Location: /easychair/admin/users");
    exit;
}

    public function removeRole()
    {
        $this->requireAdmin();

        $db = $this->db();

        $userId =
            (int)($_GET['user_id'] ?? 0);

        $conferenceId =
            (int)($_GET['conference_id'] ?? 0);

        $roleId =
            (int)($_GET['role_id'] ?? 0);

        if (
            !$userId
            || !$conferenceId
            || !$roleId
        ) {

            exit('Missing data.');
        }

        $stmt = $db->prepare("

            DELETE FROM user_conferences

            WHERE user_id = ?
            AND conference_id = ?
            AND role_id = ?

            LIMIT 1

        ");

        $stmt->execute([

            $userId,
            $conferenceId,
            $roleId

        ]);

        header(
            'Location: /easychair/admin/users'
        );

        exit;
    }

}



