<?php

namespace App\Core;

class Controller
{
    protected function view($path, $data = [])
    {
        extract($data);
        $viewFile = __DIR__ . '/../../views/' . str_replace('.', '/', $path) . '.php';
        
        if (file_exists($viewFile)) {
            require $viewFile;
        } else {
            die("View não encontrada: $viewFile");
        }
    }

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

    protected function checkPermission($requiredPerm = null)
    {
        if (empty($_SESSION['admin_logged_in'])) {
            // For AJAX requests, we might want to return JSON, but for now redirect is fine or let caller handle
            if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
                http_response_code(401);
                echo json_encode(['error' => 'Unauthorized']);
                exit;
            }
            $this->redirect('/login');
        }
        
        $role = $_SESSION['user_role'] ?? '';
        $perms = $_SESSION['user_permissions'] ?? [];

        if ($role === 'admin') return true;

        if ($requiredPerm) {
            if (in_array($requiredPerm, $perms)) return true;
            // Access denied
            $this->redirect('/admin');
        }
        
        return true;
    }

    protected function checkAdmin()
    {
        if (empty($_SESSION['admin_logged_in']) || ($_SESSION['user_role'] ?? '') !== 'admin') {
            $this->redirect('/admin');
        }
    }
}
