<?php

namespace App\Http\Middleware;

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

class VerifySmsApiRequest
{
    public function handle(Request $request, Closure $next)
    {
        $apiKey    = (string) $request->header('X-API-Key', '');
        $timestamp = (string) $request->header('X-Request-Timestamp', '');

        if ($apiKey === '') {
            return response()->json(['status' => 403, 'message' => 'Forbidden'], 403);
        }

        if ($timestamp === '' || !ctype_digit($timestamp)) {
            return response()->json(['status' => 400, 'message' => 'Bad Request'], 400);
        }

        $ttl = (int) config('sms.timestamp_ttl', 300);
        $diff = abs(time() - (int) $timestamp);
        if ($diff > $ttl) {
            return response()->json(['status' => 400, 'message' => 'Bad Request'], 400);
        }
\Log::info('Client IP debug', [
  'ip' => request()->ip(),
  'remote_addr' => $_SERVER['REMOTE_ADDR'] ?? null,
  'xff' => request()->header('X-Forwarded-For'),
  'cf_connecting_ip' => request()->header('CF-Connecting-IP'),
]);

        $allowedIps = (array) config('sms.allowed_ips', []);
        if (!empty($allowedIps)) {
            $clientIp = $request->ip();
            if (!in_array($clientIp, $allowedIps, true)) {
                return response()->json(['status' => 403, 'message' => 'Forbidden'], 403);
            }
        }

        $expected = (string) config('sms.api_key', '');
        if ($expected === '' || !hash_equals($expected, $apiKey)) {
            return response()->json(['status' => 403, 'message' => 'Forbidden'], 403);
        }

        return $next($request);
    }
}
