<?php

declare(strict_types=1);

namespace Core;

use Cartalyst\Sentinel\Native\Facades\Sentinel;

abstract class Controller
{
    protected function view(string $view, array $data = []): Response
    {
        return View::render($view, $data);
    }

    protected function fragment(string $view, array $data = [], int $status = 200, array $headers = []): Response
    {
        return View::fragment($view, $data, $status, $headers);
    }

    protected function redirect(string $url): Response
    {
        return Response::redirect($url);
    }

    protected function json(array $data): Response
    {
        return Response::json($data);
    }

    protected function requirePost(Request $request): void
    {
        if ($request->method() !== 'POST') {
            throw new \Exception('This action requires POST.');
        }
    }

    protected function requireAuth(): ?Response
    {
        if (!Sentinel::check()) {
            return $this->redirect('/login');
        }
        return null;
    }

    protected function fileResponse(string $content, string $filename, string $mimeType = 'application/octet-stream'): Response
    {
        return new Response($content, 200, [
            'Content-Type'        => $mimeType,
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
            'Content-Length'      => (string) strlen($content),
        ]);
    }
}
