<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class DemoModeMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Check if demo mode is enabled
        if (!$this->isDemoModeEnabled()) {
            return $next($request);
        }

        // Skip demo mode for installation routes
        if ($request->routeIs('install.*')) {
            return $next($request);
        }

        // Skip demo mode for login and authentication routes
        if ($request->routeIs('login', 'logout', 'password.*', 'verification.*', 'register', 'auth.*') || 
            $request->is('login', 'logout', 'register', 'forgot-password', 'reset-password*', 'verify-email*', 'confirm-password') ||
            $request->path() === 'login' || $request->path() === 'logout' || $request->path() === 'register') {
            return $next($request);
        }

        // Skip demo mode for AJAX requests that are read-only
        if ($request->ajax() && $this->isReadOnlyAjaxRequest($request)) {
            return $next($request);
        }

        // Block destructive HTTP methods (but allow login POST)
        if ($this->isDestructiveMethod($request->method()) && !$this->isLoginPost($request)) {
            return $this->handleDemoModeBlock($request);
        }

        // Block destructive form submissions
        if ($request->isMethod('POST') && $this->isDestructiveAction($request)) {
            return $this->handleDemoModeBlock($request);
        }

        return $next($request);
    }

    /**
     * Check if demo mode is enabled
     */
    private function isDemoModeEnabled(): bool
    {
        return env('DEMO', '0') === '1';
    }

    /**
     * Check if the HTTP method is destructive
     */
    private function isDestructiveMethod(string $method): bool
    {
        return in_array(strtoupper($method), ['POST', 'PUT', 'PATCH', 'DELETE']);
    }

    /**
     * Check if this is a login POST request
     */
    private function isLoginPost(Request $request): bool
    {
        return $request->isMethod('POST') && 
               ($request->path() === 'login' || $request->routeIs('login'));
    }

    /**
     * Check if the request is a destructive action
     */
    private function isDestructiveAction(Request $request): bool
    {
        $path = $request->path();
        $action = $request->input('_method', $request->method());

        // List of destructive actions
        $destructiveActions = [
            'create', 'store', 'edit', 'update', 'destroy', 'delete',
            'activate', 'deactivate', 'approve', 'reject', 'ban', 'unban',
            'import', 'export', 'backup', 'restore', 'migrate', 'seed',
            'install', 'uninstall', 'enable', 'disable', 'toggle'
        ];

        // Check if the action is destructive
        foreach ($destructiveActions as $actionName) {
            if (str_contains($path, $actionName) || str_contains($action, $actionName)) {
                return true;
            }
        }

        // Check for specific destructive routes
        $destructiveRoutes = [
            'admin/users/*/delete',
            'admin/settings/update',
            'admin/email-templates/*/update',
            'admin/license/*/update',
            'admin/products/*/update',
            'admin/categories/*/update',
            'admin/orders/*/update',
            'admin/customers/*/update',
        ];

        foreach ($destructiveRoutes as $route) {
            if ($request->is($route)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if AJAX request is read-only
     */
    private function isReadOnlyAjaxRequest(Request $request): bool
    {
        $path = $request->path();
        
        // Allow read-only AJAX requests
        $readOnlyActions = [
            'search', 'filter', 'sort', 'paginate', 'load', 'fetch',
            'get', 'show', 'view', 'index', 'list', 'data'
        ];

        foreach ($readOnlyActions as $action) {
            if (str_contains($path, $action)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Handle demo mode blocking
     */
    private function handleDemoModeBlock(Request $request): Response
    {
        if ($request->ajax() || $request->wantsJson()) {
            return response()->json([
                'success' => false,
                'message' => 'Demo Mode: This action is not allowed in demo mode. You can only view and browse the system.',
                'demo_mode' => true
            ], 403);
        }

        return redirect()->back()
            ->with('error', 'Demo Mode: This action is not allowed in demo mode. You can only view and browse the system.')
            ->with('demo_mode', true);
    }
}
