<?php

declare(strict_types=1);

namespace App\Lib;

use Exception;
use App\Util\Helper;

class Controller
{
    /**
     * Loads a model class.
     *
     * @param string $model The name of the model.
     * @return object The instantiated model object.
     * @throws Exception If the model file does not exist.
     */
    public function model(string $model): object
    {
        $modelPath = APPROOT . '/Models/' . $model . '.php';
        if (!Helper::isFileExists($modelPath)) {
            throw new Exception("Model file does not exist: $modelPath");
        }
        return new (require $modelPath);
    }

    /**
     * Renders a view.
     *
     * @param string $view The name of the view.
     * @param array $data The data to be passed to the view.
     * @return void
     */
    public function view(string $view, array $data = []): void
    {
        $viewPath = APPROOT . '/View/' . $view . '.php';
        if (!Helper::isFileExists($viewPath)) {
            http_response_code(404);
            die("View does not exist.");
        }

        if (CONFIG['minify_html']) {
            ob_start('minifyHTML');
        }

        extract($data, EXTR_PREFIX_ALL, 'view');
        require_once $viewPath;

        if (CONFIG['minify_html']) {
            ob_end_flush();
        }
    }
}