<?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
    {
        // 1. Proceed normally if we are NOT in demo mode.
        if (config('app.env') !== 'demo') {
            return $next($request);
        }

        // 2. Define the HTTP methods that modify data
        // If it's a read-only request (GET, HEAD, OPTIONS), let it pass immediately
        if ($request->isMethod('GET') || $request->isMethod('HEAD') || $request->isMethod('OPTIONS')) {
            return $next($request);
        }

        $path = $request->path();
        $user = $request->user();

        // 3. Exclude specific routes that should always be allowed (e.g., login/logout)
        // Also exclude the common AJAX state-fetching route as it is read-only but uses POST
        $excludedPaths = [
            'login',
            'logout',
            'register',
            'ch-admin/login',
            'ch-admin/logout',
            'ch-admin/ajax',
            'password/*',
        ];

        foreach ($excludedPaths as $excludedPath) {
            if ($request->is($excludedPath)) {
                return $next($request);
            }
        }

        // 4. Admin logic: Block all modifying actions in the admin area
        $isAdminAction = str_contains($path, 'ch-admin');

        // 5. Frontend logic: Protect the specific demo customer accounts AND admin accounts
        $adminEmails = [
            'admin@admin.com'
        ];

        // Add the emails of the demo accounts you want to lock down
        $protectedDemoEmails = [
            'customer@demo.com',
            'pro@demo.com'
        ];

        // Check user types
        $isAdminUser = $user && in_array($user->email, $adminEmails);
        $isProtectedDemoUser = $user && in_array($user->email, $protectedDemoEmails);

        // Path for updating account details on the frontend
        $isAccountAction = $request->is('account/edit-details') || $request->is('account/billing-details');

        // 6. Determine if we should block the request and set the appropriate message
        $message = null;

        if ($isAdminAction) {
            $message = 'This is the ChargePanda demonstration website. Admin actions are not functional on this platform. It is intended solely to showcase the core concept.';
        } elseif ($isAccountAction && ($isAdminUser || $isProtectedDemoUser)) {
            $message = 'Modifications to the default demo accounts are disabled. Please create a new account to test full functionality.';
        }

        if ($message) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => $message,
                ], 403);
            }

            return response($message, 403);
        }

        return $next($request);
    }
}
