<?php

namespace Korkz\Demirteknoloji\traits;
trait AuthControl
{
    use ENVConfig;

    protected string $host;
    protected array $openPaths = ['/login'];

    public function __construct()
    {
        $env = $this->env();
        $hostNames = $env['HOST_NAMES_SERVER'];
        $this->host = $_SERVER['HTTP_HOST'] === 'localhost' ? "/$hostNames" : "";
    }

    public function checkAccess(array|string $paths, string $prefix): void
    {
        $host = $this->host . $prefix;
        $paths = is_array($paths) ? $paths : [$paths];
        if (!isset($_SESSION['userCode'])) {
            foreach ($paths as $path) {
                if (!in_array($path, $this->openPaths, true)) {
                    $url = "Location:$host/login";
                    $url .= '?redirect=' . urlencode($_SERVER['REQUEST_URI']);
                    header($url);
                    exit;
                }
            }
        } else {
            foreach ($paths as $path) {
                if (in_array($path, $this->openPaths, true)) {
                    header("Location:$host");
                    exit;
                }
            }
        }
    }
}
