<?php
class App {
    protected $controller = 'HomeController';
    protected $method = 'index';
    protected $params = [];

    public function __construct() {
        $url = $this->parseUrl();

        // ✅ Check controller exists
        if (isset($url[0])) {
    $potentialController = ucfirst($url[0]);

    // Add "Controller" only if it's not already part of the name
    if (strpos($potentialController, 'Controller') === false) {
        $potentialController .= 'Controller';
    }

    if (file_exists('../app/controllers/' . $potentialController . '.php')) {
        $this->controller = $potentialController;
        unset($url[0]);
    }
}


        require_once '../app/controllers/' . $this->controller . '.php';
        $this->controller = new $this->controller;

        // ✅ Check method exists
        if (isset($url[1]) && method_exists($this->controller, $url[1])) {
            $this->method = $url[1];
            unset($url[1]);
        }

        $this->params = $url ? array_values($url) : [];

        call_user_func_array([$this->controller, $this->method], $this->params);
    }

    private function parseUrl() {
        if (isset($_GET['url'])) {
            return explode('/', filter_var(rtrim($_GET['url'], '/'), FILTER_SANITIZE_URL));
        }
        return [];
    }
}
