<?php
namespace App\Core;

class Controller {
    
    protected $request;
    protected $response;
    
    public function __construct() {
        $this->request = new Request();
        $this->response = new Response();
    }
    
    protected function render($view, $data = []) {
        extract($data);
        
        $viewFile = APP_PATH . '/views/' . str_replace('.', '/', $view) . '.php';
        
        if (file_exists($viewFile)) {
            ob_start();
            include $viewFile;
            $content = ob_get_clean();
            
            // Include layout
            include APP_PATH . '/views/layouts/main.php';
        } else {
            die("View not found: " . $view);
        }
    }
    
    protected function json($data, $statusCode = 200) {
        $this->response->json($data, $statusCode);
    }
    
    protected function redirect($url) {
        $this->response->redirect($url);
    }
    
    protected function isAuthenticated() {
        return isset($_SESSION['user_id']);
    }
    
    protected function requireAuth() {
        if (!$this->isAuthenticated()) {
            $this->redirect('/login');
        }
    }
    
    protected function csrf_token() {
        return \Security::generateCSRFToken();
    }
    
    protected function csrf_field() {
        return '<input type="hidden" name="csrf_token" value="' . $this->csrf_token() . '">';
    }
    
    protected function getUserRole() {
    return $_SESSION['user_role'] ?? $_SESSION['role'] ?? null;
}
    
    protected function getUserId() {
        return $_SESSION['user_id'] ?? null;
    }
}