<?php
namespace App\Core;

class Controller
{
    protected function view(string $template, array $data = []): void
    {
        $view = new View();
        $view->render($template, $data);
    }

    protected function redirect(string $path): void
    {
        // Utilise le helper base_url() pour gérer sous-répertoires / domaine dynamiquement.
        // $path peut être absolu (http...) ou relatif (/login ou login)
        if (preg_match('~^https?://~i', $path)) {
            $url = $path;
        } else {
            $base = rtrim(\base_url(), '/');
            $normalized = '/' . ltrim($path, '/');
            $url = $base . $normalized;
        }
        header('Location: ' . $url, true, 302);
        exit;
    }

    protected function renderViewToString(string $template, array $data = [], string $layout = 'none'): string
    {
        $view = new View();
        ob_start();
        $view->render($template, array_merge($data, ['_layout' => $layout]));
        return (string)ob_get_clean();
    }
}
