<?php
declare(strict_types=1);

/**
 * OnePanel B3: action handler group: auth
 * Generated from legacy action.php blocks for maintainability.
 */

function op_handle_auth(string $actionKey): void {
  switch ($actionKey) {
    case 'login':
      $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
        if (!rate_limit_ok('login:' . $ip, 10, 600)) {
          $_SESSION['error'] = 'Too many login attempts. Please wait a few minutes and try again.';
          header('Location: index.php');
          exit;
        }
      
      	if (login($_POST['username'], $_POST['password'])) {
      		session_regenerate_id(true);
      		$_SESSION[$authVar] = $_POST['username'];
      		header("Location: index.php");
      		exit;
      	} else {
      		$_SESSION['error'] = "Unrecognised username and password combination";
      		header("Location: index.php");
      		exit;
      	}
      }
      if (!isset($_SESSION[$authVar])) {
      	exit;
      return;
    default:
      http_response_code(400);
      echo 'Unknown action';
      return;
  }
}

// ---- B3.2 normalized wrappers ----

function handle_auth_login(array $post): void {
  // Keep existing login pipeline (rate-limit + session regen) by delegating if present.
  $_POST = $post;
  if (function_exists('op_handle_auth')) { op_handle_auth('login'); return; }
  throw new RuntimeException('Login handler missing');
}

function handle_auth_logout(array $post): void {
  $_SESSION = [];
  if (ini_get('session.use_cookies')) {
    $p = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
      $p['path'] ?? '/',
      $p['domain'] ?? '',
      (bool)($p['secure'] ?? false),
      (bool)($p['httponly'] ?? true)
    );
  }
  session_destroy();
  header('Location: index.php');
  exit;
}
