<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Branch extends Model
{
    protected $guarded = [];

    public function products(): BelongsToMany
    {
        return $this->belongsToMany(Product::class);
    }

    /**
     * Menghitung jarak dari Cabang ke Lokasi Pelanggan (dalam Kilometer)
     * Menggunakan Rumus Haversine.
     */
    public function calculateDistanceTo($customerLat, $customerLon)
    {
        // Jika kordinat cabang belum diisi di admin, kembalikan 0 atau tangani errornya
        if (!$this->latitude || !$this->longitude) {
            return 0; 
        }

        $earthRadius = 6371; // Radius bumi dalam satuan Kilometer

        $latFrom = deg2rad($this->latitude);
        $lonFrom = deg2rad($this->longitude);
        $latTo = deg2rad($customerLat);
        $lonTo = deg2rad($customerLon);

        $latDelta = $latTo - $latFrom;
        $lonDelta = $lonTo - $lonFrom;

        $angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
          cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));

        // Kembalikan hasil dalam KM, dibulatkan 2 angka di belakang koma (contoh: 15.42 KM)
        return round($angle * $earthRadius, 2); 
    }
}