<?php

use App\Core\Database;

/*
-----------------------------------------
Current Organization
-----------------------------------------
*/

function ec_current_org_id(): int
{
    if (!empty($_SESSION['org_id'])) {
        return (int)$_SESSION['org_id'];
    }

    return 0;
}

/*
-----------------------------------------
Current Conference
-----------------------------------------
*/

function ec_current_conference_id(): int
{
    if (!empty($_SESSION['conference_id'])) {
        return (int)$_SESSION['conference_id'];
    }

    $db =
        Database::getInstance();

    $orgId =
        ec_current_org_id();

    if (!$orgId) {
        return 0;
    }

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

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

    $conferenceId =
        (int)$stmt->fetchColumn();

    if ($conferenceId) {

        $_SESSION['conference_id'] =
            $conferenceId;

    }

    return $conferenceId;
}

/*
-----------------------------------------
Conference Guard
-----------------------------------------
*/

function ec_require_conference(): void
{
    if (!ec_current_conference_id()) {

        http_response_code(403);

        die(
            "Conference context missing."
        );

    }
}
