<?php

namespace App\Core;

class Controller
{
    protected function render(string $view, array $data = [])
    {
        /*
        -----------------------------------------
        Extract variables
        -----------------------------------------
        */
        if (!empty($data)) {
            extract($data, EXTR_SKIP);
        }

        /*
        -----------------------------------------
        Resolve view path
        -----------------------------------------
        */
        $viewFile = BASE_PATH . '/app/views/' . $view . '.php';

        if (!file_exists($viewFile)) {
            die("View not found: " . htmlspecialchars($viewFile));
        }

        /*
        -----------------------------------------
        Render view into buffer
        -----------------------------------------
        */
        ob_start();
        require $viewFile;
        $content = ob_get_clean();

/*
-----------------------------------------
Role-aware layout selection
-----------------------------------------
*/

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

if ($role === 'author') {

    $layoutFile =
        BASE_PATH .
        '/app/views/layouts/author_layout.php';

}
elseif ($role === 'reviewer') {

    $layoutFile =
        BASE_PATH .
        '/app/views/layouts/reviewer_layout.php';

}
else {

    $layoutFile =
        BASE_PATH .
        '/app/views/layouts/admin_layout.php';

}

if (!file_exists($layoutFile)) {

    die(
        "Layout not found: "
        .
        htmlspecialchars($layoutFile)
    );

}

require $layoutFile;
    }


protected function orgId(): int
{
    $orgId = (int)($_SESSION['org_id'] ?? 0);

    if (
        $orgId <= 0 &&
        (
            ($_SESSION['role'] ?? '') === 'superadmin'
            || ($_SESSION['user_role'] ?? '') === 'superadmin'
            || ($_SESSION['conference_role'] ?? '') === 'superadmin'
        )
    ) {

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

        $_SESSION['org_id'] = $orgId;
    }

    return $orgId;
}

protected function conferenceId(): int
{
    return \App\Core\TenantContext::conferenceId();
}

}
