<?php

namespace App\Core;

/**
 * ITSWEBER CMS – Base Controller
 */
abstract class Controller
{
    protected App $app;

    public function __construct(App $app)
    {
        $this->app = $app;
    }

    /**
     * Render a theme template and send it as HTML response.
     */
    protected function render(string $template, array $data = []): void
    {
        $view = $this->app->service('view');
        $content = $view->render($template, $data);
        Response::html($content);
    }

    /**
     * Render an admin view and send it as HTML response.
     */
    protected function renderAdmin(string $view, array $data = []): void
    {
        $viewEngine = $this->app->service('view');
        $content = $viewEngine->renderAdmin($view, $data);
        Response::html($content);
    }

    /**
     * Redirect to a URL.
     */
    protected function redirect(string $url): void
    {
        Response::redirect($url);
    }

    /**
     * Get the database instance.
     */
    protected function db(): Database
    {
        return $this->app->db();
    }

    /**
     * Get the session instance.
     */
    protected function session(): Session
    {
        return $this->app->service('session');
    }

    /**
     * Get the auth instance.
     */
    protected function auth(): Auth
    {
        return $this->app->service('auth');
    }

    /**
     * Get the CSRF instance.
     */
    protected function csrf(): Csrf
    {
        return $this->app->service('csrf');
    }

    /**
     * Validate CSRF token from POST request.
     */
    protected function validateCsrf(): void
    {
        $this->csrf()->check();
    }
}
