<?php

declare(strict_types=1);

namespace BotGuard\Core;

/**
 * Base controller providing response helpers shared by every controller.
 *
 * The container autowires View, Session, Csrf and Request into the constructor,
 * so subclasses can render templates and read the request without boilerplate.
 */
abstract class Controller
{
    public function __construct(
        protected View $view,
        protected Session $session,
        protected Csrf $csrf,
        protected Request $request,
    ) {
    }

    /**
     * Render a view into an HTML response.
     *
     * @param array<string, mixed> $data
     */
    protected function render(string $view, array $data = [], int $status = 200): Response
    {
        $this->view->share('csrf', $this->csrf);
        $this->view->share('session', $this->session);
        $this->view->share('auth', Container::getInstance()->make(Auth::class));

        $html = $this->view->render($view, $data);

        return (new Response($html, $status))
            ->withHeader('Content-Type', 'text/html; charset=utf-8');
    }

    /**
     * Build a JSON response.
     */
    protected function json(mixed $data, int $status = 200): Response
    {
        return Response::json($data, $status);
    }

    /**
     * Redirect to a URL, optionally flashing a message.
     */
    protected function redirect(string $url, ?string $flashKey = null, mixed $flashValue = null): Response
    {
        if ($flashKey !== null) {
            $this->session->flash($flashKey, $flashValue);
        }

        return Response::redirect($url);
    }

    /**
     * Convenience: build and run a validator against the current request.
     *
     * @param array<string, string> $rules
     */
    protected function validate(array $rules): Validator
    {
        return Validator::make($this->request->all(), $rules);
    }
}
