<?php
namespace App\Models;

use Core\Model;

class Responder extends Model
{
    protected static string $table = 'responders';
    protected static string $primaryKey = 'id';
    
    // Log when responder details or availability changes
    protected static bool $auditable = true;

    /**
     * Find the nearest available responders to a specific GPS coordinate based on category.
     * Uses the Haversine formula directly in SQL to calculate straight-line distance in Kilometers.
     */
    public static function getNearest(float $lat, float $lng, int $categoryId, int $limit = 5): array
    {
        $sql = "
            SELECT 
                r.*, 
                u.full_name, 
                u.phone_number,
                (
                    6371 * acos (
                        cos ( radians(?) )
                        * cos( radians( base_latitude ) )
                        * cos( radians( base_longitude ) - radians(?) )
                        + sin ( radians(?) )
                        * sin( radians( base_latitude ) )
                    )
                ) AS distance
            FROM 
                responders r
            JOIN 
                users u ON r.user_id = u.id
            WHERE 
                r.category_id = ? 
                AND r.is_available = 1
            ORDER BY 
                distance ASC
            LIMIT ?
        ";

        // Bind parameters: victim_lat, victim_lng, victim_lat, category_id, limit
        return self::fetchAll($sql, [$lat, $lng, $lat, $categoryId, $limit]);
    }
}