<?php

namespace App\Core;

abstract class Controller
{
    /**
     * Render sebuah view dengan data.
     * Nama view menggunakan format "folder/nama-file" relatif terhadap app/Views.
     */
    protected function view(string $view, array $data = []): void
    {
        extract($data);
        $viewPath = BASE_PATH . '/app/Views/' . $view . '.php';

        if (!file_exists($viewPath)) {
            http_response_code(500);
            die("View tidak ditemukan: {$view}");
        }

        require $viewPath;
    }

    protected function redirect(string $path): void
    {
        header('Location: ' . APP_URL . '/' . ltrim($path, '/'));
        exit;
    }

    protected function isPost(): bool
    {
        return $_SERVER['REQUEST_METHOD'] === 'POST';
    }

    protected function setFlash(string $type, string $message): void
    {
        $_SESSION['flash'] = ['type' => $type, 'message' => $message];
    }

    protected function verifyCsrf(): void
    {
        if (!\App\Core\Csrf::verify($_POST['_csrf'] ?? null)) {
            http_response_code(419);
            die('Sesi form kedaluwarsa atau tidak valid. Silakan kembali dan coba lagi.');
        }
    }
}
