<?php

namespace App\Http\Middleware;

use App\Models\Setting;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckFeatureEnabled
{
    /**
     * Feature flag mapping to human-readable names.
     */
    protected array $featureNames = [
        'feature_client_portal' => 'Portal del Cliente',
        'feature_progress_photos' => 'Fotos de Progreso',
        'feature_wallet' => 'Wallet/Saldo',
        'feature_referrals' => 'Sistema de Referidos',
        'feature_pdf_export' => 'Exportación PDF',
        'feature_chat' => 'Sistema de Chat',
        'feature_compliance_tracking' => 'Seguimiento de Cumplimiento',
        'feature_analytics' => 'Análisis y Estadísticas',
        'feature_custom_foods' => 'Alimentos Personalizados',
    ];

    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, string $feature): Response
    {
        // Check if feature is enabled
        if (!$this->isFeatureEnabled($feature)) {
            $featureName = $this->featureNames[$feature] ?? $feature;
            
            // For API/AJAX requests
            if ($request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'error' => 'Funcionalidad no disponible',
                    'message' => "La funcionalidad '{$featureName}' está deshabilitada por el administrador.",
                ], 403);
            }
            
            // For web requests, redirect with error message
            return redirect()->back()->with('error', "La funcionalidad '{$featureName}' está deshabilitada por el administrador.");
        }

        return $next($request);
    }

    /**
     * Check if a feature is enabled.
     */
    protected function isFeatureEnabled(string $feature): bool
    {
        // Admin users bypass feature checks
        if (auth()->check() && auth()->user()->isAdmin()) {
            return true;
        }

        return (bool) Setting::get($feature, true);
    }

    /**
     * Static method to check feature status (for use in views/controllers).
     */
    public static function isEnabled(string $feature): bool
    {
        // Admin users bypass feature checks
        if (auth()->check() && auth()->user()->isAdmin()) {
            return true;
        }

        return (bool) Setting::get($feature, true);
    }

    /**
     * Get all feature statuses.
     */
    public static function getAllFeatures(): array
    {
        $features = Setting::getGroup('features');
        
        return [
            'feature_client_portal' => $features['feature_client_portal'] ?? true,
            'feature_progress_photos' => $features['feature_progress_photos'] ?? true,
            'feature_wallet' => $features['feature_wallet'] ?? true,
            'feature_referrals' => $features['feature_referrals'] ?? true,
            'feature_pdf_export' => $features['feature_pdf_export'] ?? true,
            'feature_chat' => $features['feature_chat'] ?? true,
            'feature_compliance_tracking' => $features['feature_compliance_tracking'] ?? true,
            'feature_analytics' => $features['feature_analytics'] ?? true,
            'feature_custom_foods' => $features['feature_custom_foods'] ?? true,
        ];
    }
}
