<?php

use App\Core\Database;

if (!function_exists('ec_admin_start_session')) {

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

}

if (!function_exists('ec_admin_db')) {

    function ec_admin_db()
    {
        return Database::getInstance();
    }

}

if (!function_exists('ec_admin_role')) {

    function ec_admin_role(): string
    {
        ec_admin_start_session();

        return (string)(
            $_SESSION['role']
            ??
            $_SESSION['user_role']
            ??
            $_SESSION['conference_role']
            ??
            ''
        );
    }

}

if (!function_exists('ec_admin_conference_id')) {

    function ec_admin_conference_id(): int
    {
        ec_admin_start_session();

        return (int)(
            $_SESSION['conference_id']
            ??
            $_SESSION['current_conference_id']
            ??
            0
        );
    }

}

if (!function_exists('ec_admin_org_id')) {

    function ec_admin_org_id(): int
    {
        ec_admin_start_session();

        return (int)(
            $_SESSION['org_id']
            ??
            0
        );
    }

}

if (!function_exists('ec_admin_require')) {

    function ec_admin_require(): void
    {
        ec_admin_start_session();

        if (empty($_SESSION['user_id'])) {

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

            exit;

        }

    }

}

if (!function_exists('ec_admin_json')) {

    function ec_admin_json($data): void
    {
        if (ob_get_length()) {
            ob_end_clean();
        }

        header('Content-Type: application/json');

        echo json_encode(
            $data,
            JSON_UNESCAPED_UNICODE
            |
            JSON_PRETTY_PRINT
        );

        exit;
    }

}

if (!function_exists('ec_admin_redirect')) {

    function ec_admin_redirect(string $url): void
    {
        header("Location: ".$url);

        exit;
    }

}

if (!function_exists('ec_admin_flash')) {

    function ec_admin_flash(
        string $type,
        string $message
    ): void
    {
        ec_admin_start_session();

        $_SESSION['flash'] = [

            'type' => $type,

            'message' => $message

        ];
    }

}
