<?php

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

$lat = 40.7128; // NY
$lng = -74.0060; // NY

// Pick a known LA ad
$ad = Ad::where('city', 'Los Angeles')->first();

if (!$ad) {
    echo "No LA ad found.\n";
    exit;
}

echo "Ad ID: {$ad->id}\n";
echo "Ad City: {$ad->city}\n";
echo "Ad Coords: {$ad->latitude}, {$ad->longitude}\n";

// Manual Haversine in PHP
$earthRadius = 6371;
$dLat = deg2rad($ad->latitude - $lat);
$dLon = deg2rad($ad->longitude - $lng);
$a = sin($dLat/2) * sin($dLat/2) +
     cos(deg2rad($lat)) * cos(deg2rad($ad->latitude)) *
     sin($dLon/2) * sin($dLon/2);
$c = 2 * atan2(sqrt($a), sqrt(1-$a));
$distPHP = $earthRadius * $c;

echo "PHP Distance: {$distPHP} km\n";

// SQL Haversine
$haversine = "(6371 * acos(cos(radians($lat)) * cos(radians(latitude)) * cos(radians(longitude) - radians($lng)) + sin(radians($lat)) * sin(radians(latitude))))";

$result = Ad::selectRaw("id, city, $haversine as distance")
            ->where('id', $ad->id)
            ->first();

echo "SQL Distance: {$result->distance} km\n";
