<?php
declare(strict_types=1);

require_once __DIR__ . '/session_config.php';
require_once __DIR__ . '/DataBase.php';

function bdr_logout_redirect(string $logoutPath = '../logout.php'): void
{
    if (!headers_sent()) {
        header('Location: ' . $logoutPath);
    }
    exit();
}

function bdr_database(): PDO
{
    static $conn = null;

    if ($conn instanceof PDO) {
        return $conn;
    }

    $dataBase = new DataBase();
    $conn = $dataBase->getConnection();

    return $conn;
}

function bdr_current_user_id(string $logoutPath = '../logout.php'): int
{
    bdr_start_session();

    if (ob_get_level() === 0) {
        ob_start();
    }

    if (!isset($_SESSION['user_id'])) {
        bdr_logout_redirect($logoutPath);
    }

    return (int) $_SESSION['user_id'];
}

function bdr_user_has_privilege(PDO $conn, int $userId, $elementIds): bool
{
    $ids = is_array($elementIds) ? $elementIds : array($elementIds);
    $ids = array_values(array_unique(array_filter(array_map('intval', $ids), static function ($id) {
        return $id > 0;
    })));

    if (count($ids) === 0) {
        return true;
    }

    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $sql = "SELECT user_id FROM privileges WHERE user_id = ? AND element_id IN ($placeholders) AND yes_no = 1 LIMIT 1";
    $query = $conn->prepare($sql);
    $query->execute(array_merge(array($userId), $ids));

    return $query->rowCount() > 0;
}

function bdr_require_privilege($elementIds, string $logoutPath = '../logout.php', ?string $deniedPath = null): array
{
    $userId = bdr_current_user_id($logoutPath);
    $conn = bdr_database();

    if (!bdr_user_has_privilege($conn, $userId, $elementIds)) {
        bdr_logout_redirect($deniedPath ?? $logoutPath);
    }

    return array(
        'conn' => $conn,
        'user_id' => $userId,
        'user' => $userId,
        'branch' => $_SESSION['branch'] ?? null,
        'realName' => $_SESSION['realName'] ?? null,
    );
}
