<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Dummy extends Model
{
    public static function addDummyTrack($data)
    {
        $id = DB::table("t_dummy_tracks")->insertGetId($data);
        return $id;
    }

    public static function getByGpsId($gps_id)
    {
        return DB::select("SELECT * FROM t_dummy_tracks WHERE gps_id = ?;", [$gps_id]);
    }

    public static function updateDummyTrack($data)
    {
        return DB::table("t_dummy_tracks")
            ->where("id", $data["id"])
            ->update($data);
    }

    public static function deleteDummyTrack($data)
    {
        return DB::table("t_dummy_tracks")
            ->where("id", $data["id"])
            ->delete();
    }

    // ------------------------------------------------------------------------------------------------------------------------------------------------------------------

    public static function addDummyHub($data)
    {
        $id = DB::table("t_dummy_hubs")->insertGetId($data);
        return $id;
    }

    /**
     * https://stackoverflow.com/questions/574691/mysql-great-circle-distance-haversine-formula
     * miles: 3958.756 || 3959
     * km: 6371
     * meters: 6371000
     * more accurate using km/meters than miles i think ~
     */
    public static function nearestHubInCircle($lat, $lng)
    {
        $query = "SELECT id,name, ( 6371000 * acos( cos( radians( :lat1 ) ) * cos( radians( lat ) )
        * cos( radians( lng ) - radians( :lng ) ) + sin( radians( :lat2 ) ) * sin(radians( lat )) ) ) AS distance
        FROM t_dummy_hubs
        HAVING distance <= 800
        ORDER BY distance;";
        $params = [
            "lat1" => $lat,
            "lat2" => $lat,
            "lng" => $lng,
        ];
        return DB::select($query, $params);
    }
}
