<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array<int, string>
     */
    protected $except = [
        // Add API routes that should always be excluded from CSRF
        'api/*',
        'sanctum/csrf-cookie',
    ];

    /**
     * Determine if the request has a URI that should pass through CSRF verification.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function inExceptArray($request)
    {
        // Check if this request was marked to skip CSRF by the CORS middleware
        if ($request->attributes->get('skip_csrf', false)) {
            \Log::debug('CSRF - Skipping CSRF verification for mobile app request', [
                'path' => $request->path(),
                'user_agent' => $request->userAgent(),
                'x_mobile_app' => $request->header('X-Mobile-App'),
            ]);
            return true;
        }

        // Check if this is a mobile app request directly
        if ($this->isFromMobileApp($request)) {
            \Log::debug('CSRF - Skipping CSRF verification for detected mobile app request', [
                'path' => $request->path(),
                'user_agent' => $request->userAgent(),
                'x_mobile_app' => $request->header('X-Mobile-App'),
            ]);
            return true;
        }

        return parent::inExceptArray($request);
    }

    /**
     * Determine if the request is coming from the mobile app
     *
     * @param \Illuminate\Http\Request $request
     * @return bool
     */
    protected function isFromMobileApp($request): bool
    {
        // Check for mobile app specific headers
        if ($request->hasHeader('X-Mobile-App')) {
            return true;
        }

        // Check for mobile app user agent
        if ($request->userAgent()) {
            $mobileIndicators = ['dart', 'flutter', 'okhttp', 'mypoliceapp', 'dio'];
            $userAgent = strtolower($request->userAgent());
            
            foreach ($mobileIndicators as $indicator) {
                if (str_contains($userAgent, $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') {
                    return true;
                }
                
                // Also accept any JSON request to auth endpoints
                if ($request->expectsJson() || $request->isJson() || $request->wantsJson()) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Get the CSRF token from the request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string
     */
    protected function getTokenFromRequest($request)
    {
        $token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN');

        if (!$token && $header = $request->header('X-XSRF-TOKEN')) {
            try {
                $token = $this->decryptCookie($header);
            } catch (\Exception $e) {
                \Log::debug('CSRF - Failed to decrypt XSRF token', [
                    'error' => $e->getMessage(),
                    'header' => $header
                ]);
            }
        }

        \Log::debug('CSRF - Token extraction', [
            'token_found' => !empty($token),
            'token_length' => $token ? strlen($token) : 0,
            'path' => $request->path(),
            'method' => $request->method(),
        ]);

        return $token;
    }
}