<?php

namespace App\Http\Middleware;

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

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // For mobile app requests, disable CSRF protection
        if ($this->isFromMobileApp($request)) {
            // Mark this request to skip CSRF verification
            $request->attributes->set('skip_csrf', true);
            
            // Store the original intended URL for later use
            if (app()->bound('session')) {
                app('session')->put('url.intended', $request->url());
            }
        }
        
        // Handle preflight OPTIONS requests
        if ($request->isMethod('OPTIONS')) {
            $response = response('', 200);
        } else {
            $response = $next($request);
        }
        
        // Set appropriate CORS headers
        if ($this->isFromMobileApp($request)) {
            // For mobile apps, allow any origin
            $response->headers->set('Access-Control-Allow-Origin', '*');
        } else {
            // For web browsers, be more restrictive if needed
            $response->headers->set('Access-Control-Allow-Origin', config('app.url'));
        }
        
        $response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
        $response->headers->set('Access-Control-Allow-Headers', 
            'X-Requested-With, Content-Type, X-Token-Auth, Authorization, X-CSRF-TOKEN, X-XSRF-TOKEN, X-Mobile-App, Accept');
        $response->headers->set('Access-Control-Allow-Credentials', 'true');
        $response->headers->set('Access-Control-Expose-Headers', 'X-CSRF-TOKEN, X-XSRF-TOKEN');
        
        return $response;
    }
    
    /**
     * Determine if the request is coming from the mobile app
     *
     * @param Request $request
     * @return bool
     */
    protected function isFromMobileApp(Request $request): bool
    {
        // Log request details for debugging
        \Log::debug('CORS - Mobile app detection check', [
            'user_agent' => $request->userAgent(),
            'x_mobile_app' => $request->header('X-Mobile-App'),
            'x_requested_with' => $request->header('X-Requested-With'),
            'path' => $request->path(),
            'method' => $request->method(),
        ]);
        
        // Check for mobile app specific headers
        if ($request->hasHeader('X-Mobile-App')) {
            \Log::debug('CORS - Mobile app detected via X-Mobile-App header');
            return true;
        }
        
        // Check for mobile app user agent
        if ($request->userAgent()) {
            // Check for common mobile app indicators
            $mobileIndicators = ['dart', 'flutter', 'okhttp', 'mypoliceapp', 'dio'];
            $userAgent = strtolower($request->userAgent());
            
            foreach ($mobileIndicators as $indicator) {
                if (str_contains($userAgent, $indicator)) {
                    \Log::debug('CORS - Mobile app detected via user agent: ' . $indicator);
                    return true;
                }
            }
        }
        
        // For auth endpoints, be more lenient
        $authEndpoints = ['login', 'api/login', 'sanctum/csrf-cookie'];
        $currentPath = trim($request->path(), '/');
        
        foreach ($authEndpoints as $endpoint) {
            if (str_contains($currentPath, trim($endpoint, '/'))) {
                if ($request->hasHeader('X-Requested-With') && 
                    $request->header('X-Requested-With') === 'XMLHttpRequest') {
                    \Log::debug('CORS - Mobile app detected via XMLHttpRequest on auth endpoint');
                    return true;
                }
                
                // Also accept any JSON request to auth endpoints
                if ($request->expectsJson() || $request->isJson() || $request->wantsJson()) {
                    \Log::debug('CORS - Mobile app detected via JSON request to auth endpoint');
                    return true;
                }
            }
        }
        
        // Not detected as a mobile app
        return false;
    }
}