<?php
/**
 * @copyright (c) Kufer Software GmbH, Oderstraße 7, D-84453 Mühldorf
 */

namespace Kufer\Web\KuferTools\Utils\Oeffentlich;

use Kufer\Web\KuferTools\Basis\Controller\Controller;
use Kufer\Web\KuferTools\Oeffentlich\DoLogin\DoLoginResponse;
use Kufer\Web\KuferTools\Utils\Dozent\KursBearbeitenPlanungUtils;

class OeffentlichUtils
{
  private function __construct()
  {
  }

  private static function forwardTo(\Benutzer $user, int $forwardToTool, string $forwardToId): bool
  {
    
    $toolId = \DBWorkTools::getDefaultInstance()->getToolIdByMarketingId($user->getIdentifier(), $forwardToTool);
    switch ($toolId) {
      case 1: 
        if ($forwardToId !== '') {
          header('Location: index.php?tool_id=1&action=kursdetails&knr=' . urlencode($forwardToId));
        } else {
          header('Location: index.php?tool_id=1');
        }

        die();
      case 3: 
        if ($forwardToId !== '') {
          $action = 'kursbearbeiten';
          $toolSettings = \ToolSettingsAPI::getToolSettings($toolId);
          if (count(KursBearbeitenPlanungUtils::getSettingStatus($toolSettings->kursstatusKursInPlanung)) > 0) {
            $dbwKurse = \DBWorkKurse::getDefaultInstance();
            $kurs = $dbwKurse->getKurs($forwardToId);
            if (KursBearbeitenPlanungUtils::isKursInPlanung($toolSettings->kursstatusKursInPlanung, $kurs)) {
              $action = 'kursbearbeitenplanung';
            }
          }

          header('Location: index.php?tool_id=3&action=' . $action . '&knr=' . urlencode($forwardToId));
        } else {
          header('Location: index.php?tool_id=3');
        }

        die();
    }

    return false;
  }

  
  public static function getAfterLoginController(?\Benutzer $user = null, ?DoLoginResponse $response = null): ?Controller
  {
    $dbwtools = new \DBWorkTools();
    $user = $user ?? \SessionOperations::getCurrentWebToolsUser();
    $location = '';

    if (!is_null($response) && !is_null($response->forward_to_tool ?? null)) {
      if (static::forwardTo($user, $response->forward_to_tool, $response->forward_to_id)) {
        return null;
      }
    }

    $tool0Settings = \ToolSettingsAPI::getToolSettings(0);
    $toolNachLoginAry = explode(',', $tool0Settings->toolNachLogin);

    foreach ($toolNachLoginAry as $toolId) {
      $trimmedToolId = trim($toolId);
      if (is_numeric($trimmedToolId) && $dbwtools->isToolAllowed($user->getIdentifier(), trim($trimmedToolId))) {
        $location = 'index.php?tool_id=' . trim($trimmedToolId) . '&einstieg=1';
        break;
      }
    }

    if ($location == '') {
      $location = 'index.php?tool_id=-4&action=willkommen';
    }

    
    header("Location: $location");

    return null;
  }
}