<?php

namespace App\Controllers;

use App\Middleware\AuthMiddleware;

class BaseController
{
    protected $authMiddleware;

    public function __construct()
    {
        $this->authMiddleware = new AuthMiddleware();
    }

    /**
     * Requerir autenticación
     */
    protected function requireAuth()
    {
        $this->authMiddleware->requireAuth('/login');
    }

    /**
     * Requerir rol específico
     */
    protected function requireRole(array $allowedRoles)
    {
        $this->requireAuth(); // Primero verificar autenticación
        
        $user = $_SESSION['user'] ?? null;
        if (!$user || !in_array($user['role_name'] ?? '', $allowedRoles)) {
            header('Location: /dashboard');
            exit;
        }
    }

    /**
     * Requerir permisos de administrador
     */
    protected function requireAdmin()
    {
        $this->authMiddleware->requireAdmin('/dashboard');
    }

    /**
     * Renderizar vista
     */
    protected function render(string $view, array $data = [])
    {
        // Agregar datos comunes a todas las vistas
        $data['csrf_token'] = csrf_token();
        $data['current_user'] = $_SESSION['user'] ?? null;
        $data['showSidebar'] = $data['showSidebar'] ?? true; // Mostrar sidebar por defecto
        
        extract($data);
        $viewPath = __DIR__ . '/../../views/' . $view . '.php';
        if (!file_exists($viewPath)) {
            throw new \Exception("Vista no encontrada: $view");
        }
        require $viewPath;
    }

    /**
     * Validar token CSRF
     */
    protected function validateCsrfToken(string $token): bool
    {
        return $token === ($_SESSION['csrf_token'] ?? '');
    }

    /**
     * Redireccionar
     */
    protected function redirect(string $path, int $code = 302)
    {
        http_response_code($code);
        header("Location: $path");
        exit;
    }

    /**
     * Renderizar JSON
     */
    protected function json(array $data, int $code = 200)
    {
        http_response_code($code);
        header('Content-Type: application/json');
        echo json_encode($data);
        exit;
    }
}