<?php

namespace App\Controllers;

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

use App\Core\Database;

class AuthController
{
    /*
    -----------------------------------------
    LOGIN
    -----------------------------------------
    */

    
public function login()
{
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }

    error_log("LOGIN METHOD STARTED");

    if (!empty($_GET['conference_id'])) {
        $_SESSION['submit_conference_id'] = (int)$_GET['conference_id'];
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {

        $email = trim($_POST['email'] ?? '');
        $pass  = $_POST['password'] ?? '';

        $db = Database::getInstance();

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

        if (
            !$user ||
            !password_verify($pass, $user['password_hash'])
        ) {
$_SESSION['login_error'] = 'Invalid email or password';

header('Location: /easychair/login');
exit;            
//die("Invalid login");
        }

        $_SESSION['user_id'] = (int)$user['id'];
        $_SESSION['user'] = $user;

        $globalRole = $user['global_role'] ?? '';

        $isSuperAdmin =
            $globalRole === 'superadmin'
            || (int)($user['role_id'] ?? 0) === 1;

        /*
        -----------------------------------------
        LOAD BOTH NEW + LEGACY CONFERENCE ROLES
        -----------------------------------------
        */

        $stmt = $db->prepare("
            SELECT
                conference_id,
                role,
                title,
                short_name,
		slug
            FROM (
                SELECT
                    cur.conference_id,
                    cur.role_code AS role,
                    c.title_en AS title,
                    c.short_name,
		c.slug,
                    cur.id AS sort_id
                FROM conference_user_roles cur
                LEFT JOIN conferences c
                    ON c.id = cur.conference_id
                WHERE cur.user_id = ?

                UNION

                SELECT
                    uc.conference_id,
                    r.code AS role,
                    c.title_en AS title,
                    c.short_name,
		c.slug,
                    uc.id AS sort_id
                FROM user_conferences uc
                LEFT JOIN roles r
                    ON r.id = uc.role_id
                LEFT JOIN conferences c
                    ON c.id = uc.conference_id
                WHERE uc.user_id = ?
            ) x
            ORDER BY sort_id ASC
        ");

        $stmt->execute([
            (int)$user['id'],
            (int)$user['id']
        ]);

        $roles = $stmt->fetchAll(\PDO::FETCH_ASSOC);


        if ($isSuperAdmin) {

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

            if (empty($roles)) {
                $stmt = $db->query("
                    SELECT
                        id AS conference_id,
                        'superadmin' AS role,
                        title_en AS title,
                        short_name,
                slug
                    FROM conferences
                    ORDER BY id
                ");
                $roles = $stmt->fetchAll(\PDO::FETCH_ASSOC);
/*
-----------------------------------------
AUTO SELECT FIRST CONFERENCE
-----------------------------------------
*/

if (
    !empty($roles)
    &&
    empty($_SESSION['conference_id'])
) {

    $_SESSION['conference_id']
        = (int)$roles[0]['conference_id'];

    $_SESSION['current_conference_id']
        = (int)$roles[0]['conference_id'];

    $_SESSION['conference_slug']
        = $roles[0]['slug']
        ?? '';

    $_SESSION['conference_short_name']
        = $roles[0]['short_name']
        ?? '';
}

            }

        }

        /*
        -----------------------------------------
        PRIORITIZE STRONGEST ROLE
        -----------------------------------------
        */

        if (!empty($roles)) {

           $priority = [

    /*
    -----------------------------------------
    TRUE SYSTEM ADMINS
    -----------------------------------------
    */

    'superadmin' => 1,

    /*
    -----------------------------------------
    CONFERENCE MANAGEMENT
    -----------------------------------------
    */

    'org_admin'        => 2,
    'conference_chair' => 3,
    'organizer'        => 4,
    'track_chair'      => 5,
    'section_editor'   => 6,

    /*
    -----------------------------------------
    REVIEW WORKFLOW
    -----------------------------------------
    */

    'reviewer' => 7,

    /*
    -----------------------------------------
    LEGACY / GENERIC ADMIN
    -----------------------------------------
    */

    'admin' => 8,

    /*
    -----------------------------------------
    AUTHOR
    -----------------------------------------
    */

    'author' => 9
];

if (!empty($roles)) {

   $priority = [

       'superadmin' => 1,
       'org_admin' => 2,
       'conference_chair' => 3,
       'organizer' => 4,
       'track_chair' => 5,
       'section_editor' => 6,
       'reviewer' => 7,
       'admin' => 8,
       'author' => 9
   ];

            
usort($roles, function ($a, $b) use ($priority) {
                $pa = $priority[$a['role'] ?? 'author'] ?? 999;
                $pb = $priority[$b['role'] ?? 'author'] ?? 999;
                return $pa <=> $pb;
            });
        }

          

/*
--------------------------------------------------
FINAL ROLE NORMALIZATION
--------------------------------------------------
*/

$normalizedRoles = [];

foreach ($roles as $r) {

    if (
        empty($r['conference_id'])
        ||
        empty($r['role'])
    ) {
        continue;
    }

    $key =
        $r['conference_id']
        . '_'
        . $r['role'];

    $normalizedRoles[$key] = $r;
}

/*
--------------------------------------------------
FORCE REVIEWER CONFERENCE MEMBERSHIPS
--------------------------------------------------
*/

try {

    $stmtReviewer =
        $db->prepare("
            SELECT
                cr.conference_id,
                'reviewer' AS role,
                c.title_en AS title,
                c.short_name,
		c.slug

            FROM conference_reviewers cr

            LEFT JOIN conferences c
                ON c.id = cr.conference_id

            WHERE cr.user_id = ?
        ");

    $stmtReviewer->execute([
        (int)$user['id']
    ]);

    while ($rr = $stmtReviewer->fetch(\PDO::FETCH_ASSOC)) {

        $key =
            $rr['conference_id']
            . '_reviewer';

        $normalizedRoles[$key] = $rr;
    }

} catch (\Throwable $e) {

    error_log(
        'FINAL REVIEWER MERGE ERROR: '
        . $e->getMessage()
    );
}

$roles =
    array_values($normalizedRoles);

$_SESSION['available_roles'] = $roles;
$_SESSION['all_roles'] = $roles;

error_log(
    'FINAL ROLES => '
    . print_r($roles, true)
);
            if ($isSuperAdmin) {
                $_SESSION['conference_role'] = 'superadmin';
                $_SESSION['role'] = 'superadmin';
                $_SESSION['user_role'] = 'superadmin';
            } else {
                $_SESSION['conference_role'] = $first['role'] ?? 'author';
                $_SESSION['role'] = $_SESSION['conference_role'];
                $_SESSION['user_role'] = $_SESSION['conference_role'];
            }
        } else {
            $_SESSION['conference_role'] = 'author';
            $_SESSION['role'] = 'author';
            $_SESSION['user_role'] = 'author';
        }

        $_SESSION['needs_role_selection'] = false;

        error_log(
            "SESSION AFTER LOGIN: " .
            json_encode($_SESSION)
        );

        /*
        -----------------------------------------
        RETURN TO CONFERENCE SUBMISSION
        -----------------------------------------
        */

        if (!empty($_SESSION['submit_conference_id'])) {

            $cid = (int)$_SESSION['submit_conference_id'];
            unset($_SESSION['submit_conference_id']);

            header("Location: /easychair/author/submit?id=" . $cid);
            exit;
        }

        /*
        -----------------------------------------
        DIRECT ROUTING
        -----------------------------------------
        */

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

if (
    in_array(
        $role,
        [
            'superadmin',
            'org_admin',
            'conference_chair',
            'organizer',
            'track_chair',
            'section_editor'
        ],
        true
    )
)        

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

        if ($role === 'reviewer') {
            header("Location: /easychair/reviewer/dashboard");
            exit;
        }

        header("Location: /easychair/author/dashboard");
        exit;
    }

    require BASE_PATH . '/app/views/auth/login.php';
}

    /*
    -----------------------------------------
    SELECT ROLE
    -----------------------------------------
    */

    public function selectRole()
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        /*
        -----------------------------------------
        AUTH CHECK
        -----------------------------------------
        */

        if (!isset($_SESSION['user_id'])) {

            header("Location: /easychair/login");
            exit;
        }

        /*
        -----------------------------------------
        SUPERADMIN CHECK
        -----------------------------------------
        */

        $isSuperAdmin =
            (
                ec_is_superadmin()
            )
            ||
            (
                ($_SESSION['user_role'] ?? '')
                === 'superadmin'
            )
            ||
            (
                ($_SESSION['conference_role'] ?? '')
                === 'superadmin'
            )
            ||
            (
                ($_SESSION['user']['role_id'] ?? 0)
                == 1
            );

        /*
        -----------------------------------------
        ROLE SELECTION POST
        -----------------------------------------
        */

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {

            $idx =
                (int)($_POST['idx'] ?? -1);

            if (
                !isset(
                    $_SESSION['all_roles'][$idx]
                )
            ) {

                die("Invalid role selection");
            }

            $r =
                $_SESSION['all_roles'][$idx];

            $_SESSION['conference_id']
                = (int)(
                    $r['conference_id']
                    ?? 0
                );

            $_SESSION['current_conference_id']
                = $_SESSION['conference_id'];

            /*
            DB
            */

            $db =
                Database::getInstance();

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

            $stmt->execute([
                $_SESSION['conference_id']
            ]);

            $conf =
                $stmt->fetch(\PDO::FETCH_ASSOC);

            /*
            ORG
            */

            $_SESSION['org_id']
                = (int)(
                    $conf['org_id']
                    ?? $_SESSION['user']['org_id']
                    ?? 1
                );

            /*
            ROLE
            */

            if ($isSuperAdmin) {

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

                $_SESSION['user_role']
                    = 'superadmin';

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

            } else {

                $_SESSION['role']
                    = (string)(
                        $r['role']
                        ?? 'author'
                    );

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

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

            /*
            SHORTNAME
            */

            $_SESSION['conference_short_name']
                = $conf['short_name']
                ?? '';

$_SESSION['conference_slug']
    = $selected['slug']
    ?? (
        $conf['slug']
        ?? ''
    );

$_SESSION['conference_slug'] =
    $first['slug']
    ?? '';
            /*
            EXIT ROLE SELECTION
            */

            unset(
                $_SESSION['needs_role_selection']
            );

            error_log(
                "ROLE SET FINAL: "
                . json_encode($_SESSION)
            );

            /*
            ROUTING
            */

            if ($isSuperAdmin) {

                header(
                    "Location: /easychair/admin/dashboard"
                );

                exit;
            }

            if (
                in_array(
                    $_SESSION['role'],
                    [
                        'admin',
                        'conference_chair',
                        'organizer',
                        'track_chair'
                    ]
                )
            ) {

                header(
                    "Location: /easychair/admin/dashboard"
                );

                exit;
            }

            if (
                $_SESSION['role']
                === 'reviewer'
            ) {

                header(
                    "Location: /easychair/reviewer/dashboard"
                );

                exit;
            }

            header(
                "Location: /easychair/author/dashboard"
            );

            exit;
        }

        /*
        -----------------------------------------
        LOAD ROLES
        -----------------------------------------
        */

        $roles =
            $_SESSION['all_roles']
            ?? [];

        /*
        -----------------------------------------
        NO ROLES
        -----------------------------------------
        */

        if (empty($roles)) {

            die(
                "No roles found. Please login again."
            );
        }

        /*
        -----------------------------------------
        RENDER VIEW
        -----------------------------------------
        */

        ob_start();

        require BASE_PATH
            . '/app/views/auth/select_role.php';

        $content =
            ob_get_clean();

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

/*
-----------------------------------------
REGISTER
-----------------------------------------
*/


public function register()
{
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }

    $db = Database::getInstance();

    /*
    --------------------------------------------------
    PRESERVE CONFERENCE CONTEXT
    --------------------------------------------------
    */

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

    if ($conferenceId > 0) {

        $_SESSION['submit_conference_id']
            = $conferenceId;
    }

    /*
    --------------------------------------------------
    REGISTER POST
    --------------------------------------------------
    */

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {

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

        $firstName =
            trim($_POST['first_name'] ?? '');

        $lastName =
            trim($_POST['last_name'] ?? '');

        $email =
            trim($_POST['email'] ?? '');

        $phone =
            trim($_POST['phone'] ?? '');

        $affiliation =
            trim($_POST['affiliation'] ?? '');

        $password =
            $_POST['password'] ?? '';

        $passwordConfirm =
            $_POST['password_confirm'] ?? '';

        /*
        --------------------------------------------------
        VALIDATION
        --------------------------------------------------
        */

        if (
            !$firstName
            || !$lastName
            || !$email
            || !$password
        ) {

            $_SESSION['error']
                = "All required fields are mandatory.";

            header("Location: " . $_SERVER['REQUEST_URI']);
            exit;
        }

        if ($password !== $passwordConfirm) {

            $_SESSION['error']
                = "Passwords do not match.";

            header("Location: " . $_SERVER['REQUEST_URI']);
            exit;
        }

        /*
        --------------------------------------------------
        EMAIL EXISTS
        --------------------------------------------------
        */

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

        $stmt->execute([$email]);

        if ($stmt->fetch()) {

            $_SESSION['error']
                = "Email already registered.";

            header("Location: " . $_SERVER['REQUEST_URI']);
            exit;
        }

        /*
        --------------------------------------------------
        ORGANIZATION ID
        --------------------------------------------------
        */

        $orgId = 1;

        if ($conferenceId > 0) {

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

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

            $orgId =
                (int)(
                    $stmt->fetchColumn()
                    ?: 1
                );
        }

        /*
        --------------------------------------------------
        CREATE USER
        --------------------------------------------------
        */

        $hash =
            password_hash(
                $password,
                PASSWORD_DEFAULT
            );

        $stmt = $db->prepare("
            INSERT INTO users
            (
                org_id,
                role_id,
                first_name,
                last_name,
                email,
                phone,
                password_hash,
                expertise,
                preferred_lang,
                is_active,
                created_at,
                updated_at
            )
            VALUES
            (
                ?, 5,
                ?, ?, ?, ?, ?,
                ?,
                'en',
                1,
                NOW(),
                NOW()
            )
        ");

        $stmt->execute([

            $orgId,
            $firstName,
            $lastName,
            $email,
            $phone,
            $hash,
            $affiliation

        ]);

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

        /*
        --------------------------------------------------
        ATTACH AUTHOR TO CONFERENCE
        --------------------------------------------------
        */

        if ($conferenceId > 0) {

            $stmt = $db->prepare("
                SELECT id
                FROM roles
                WHERE code='author'
                LIMIT 1
            ");

            $stmt->execute();

            $roleId =
                (int)(
                    $stmt->fetchColumn()
                    ?: 5
                );

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

            $stmt->execute([

                $userId,
                $conferenceId,
                $roleId

            ]);
        }

        /*
        --------------------------------------------------
        AUTO LOGIN
        --------------------------------------------------
        */

        $_SESSION['user_id']
            = $userId;

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

        $stmt->execute([$userId]);

        $_SESSION['user']
            = $stmt->fetch(\PDO::FETCH_ASSOC);

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

        $_SESSION['user_role']
            = 'author';

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

        $_SESSION['conference_id']
            = $conferenceId;

        $_SESSION['org_id']
            = $orgId;

        /*
        --------------------------------------------------
        REDIRECT TO SUBMISSION
        --------------------------------------------------
        */

        if ($conferenceId > 0) {

            header(
                "Location: /easychair/author/submit?id="
                . $conferenceId
            );

            exit;
        }

        /*
        --------------------------------------------------
        DEFAULT
        --------------------------------------------------
        */

        header(
            "Location: /easychair/author/dashboard"
        );

        exit;
    }

    /*
    --------------------------------------------------
    LOAD PRESELECTED CONFERENCE
    --------------------------------------------------
    */

    $preselectedConference = null;

    if ($conferenceId > 0) {

        $stmt = $db->prepare("
            SELECT
                c.*,
                o.name AS org_name
            FROM conferences c
            LEFT JOIN organizations o
                ON o.id = c.org_id
            WHERE c.id=?
            LIMIT 1
        ");

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

        $preselectedConference =
            $stmt->fetch(\PDO::FETCH_ASSOC);
    }

    /*
    --------------------------------------------------
    PUBLIC CONFERENCE LIST
    --------------------------------------------------
    */

    $conferences = $db->query("
        SELECT
            c.*,
            o.name AS org_name
        FROM conferences c
        LEFT JOIN organizations o
            ON o.id = c.org_id
        WHERE c.is_active = 1
        ORDER BY c.id DESC
    ")->fetchAll(\PDO::FETCH_ASSOC);

    /*
    --------------------------------------------------
    VIEW
    --------------------------------------------------
    */

    require BASE_PATH
        . '/app/views/auth/register.php';
}

    

/*
    -----------------------------------------
    LOGOUT
    -----------------------------------------
    */

    public function logout()
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        session_destroy();

        header("Location: /easychair/login");
        exit;
    }
}
