<?php

use App\Models\Ad;
use Illuminate\Support\Facades\DB;

// Simulate Request Parameters for "Delhi"
$lat = 28.6139;
$lng = 77.2090;
$radius = 50; // 50km radius

echo "--- Simulating Request for Delhi ($lat, $lng) with Radius {$radius}km ---\n";

$query = Ad::where('status', 'Active')->where('is_active', true);

// 1. Apply Radius Filter
// Haversine
$haversine = "(6371 * acos(cos(radians($lat)) * cos(radians(ads.latitude)) * cos(radians(ads.longitude) - radians($lng)) + sin(radians($lat)) * sin(radians(ads.latitude))))";

$query->whereRaw("$haversine <= ?", [$radius])
      ->whereNotNull(['ads.latitude', 'ads.longitude']);

$count = $query->count();
echo "Strict Radius Filter Found: $count Ads\n";

if ($count > 0) {
    $ads = $query->select('title', 'city', 'location_city', 'latitude', 'longitude')->get();
    foreach ($ads as $ad) {
        echo " - Found: {$ad->title} in {$ad->city} ({$ad->latitude}, {$ad->longitude})\n";
    }
} else {
    echo "NO ADS FOUND in Radius. Fallback would trigger.\n";
    
    // Fallback Logic Simulation
    echo "\n--- Simulating Fallback ---\n";
    $fallbackAds = Ad::where('status', 'Active')
        ->where('is_active', true)
        ->orderBy('created_at', 'desc')
        ->limit(5)
        ->get();
        
    foreach ($fallbackAds as $ad) {
        echo " - Fallback Ad: {$ad->title} in {$ad->city}\n";
    }
}
