<?php
namespace App\Core;

abstract class Controller
{
    /**
     * Get the base URL of the application (including subdirectory)
     */
    protected function baseUrl($path = '')
    {
        $scriptName = $_SERVER['SCRIPT_NAME']; // e.g., /malsat/public/index.php
        $basePath = rtrim(dirname($scriptName), '/\\');
        if ($basePath === '/' || $basePath === '\\') {
            $basePath = '';
        }
        return $basePath . '/' . ltrim($path, '/');
    }

    protected function redirect($url)
    {
        // If $url starts with '/', treat as relative to base
        if (strpos($url, '/') === 0) {
            $url = $this->baseUrl($url);
        }
        header("Location: {$url}");
        exit;
    }

    protected function render($view, $data = [])
    {
        extract($data);
        $viewPath = __DIR__ . '/../views/' . str_replace('.', '/', $view) . '.php';
        if (file_exists($viewPath)) {
            require $viewPath;
        } else {
            throw new \Exception("View {$view} not found at {$viewPath}");
        }
    }

    protected function isAuthenticated()
    {
        return isset($_SESSION['user_id']);
    }

    protected function requireAuth()
    {
        if (!$this->isAuthenticated()) {
            $this->redirect('/login');
        }
    }

    protected function json($data)
    {
        header('Content-Type: application/json');
        echo json_encode($data);
        exit;
    }
}