<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\WorkingArea;
use App\Models\User;
use App\Models\TripRequest;
use App\Models\Trip;

class ServicePoint extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'name_ar',
        'type',
        'latitude',
        'longitude',
        'address',
        'working_area_id',
        'description',
        'is_active',
    ];

    protected $casts = [
        'latitude' => 'decimal:8',
        'longitude' => 'decimal:8',
        'is_active' => 'boolean',
    ];

    /**
     * Get the working area that owns the service point.
     */
    public function workingArea()
    {
        return $this->belongsTo(WorkingArea::class);
    }

    /**
     * Scope to get only active service points.
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope to get service points by type.
     */
    public function scopeOfType($query, $type)
    {
        return $query->where('type', $type);
    }

    /**
     * Get the distance from a given point.
     */
    public function getDistanceFrom($lat, $lng)
    {
        $lat1 = deg2rad($this->latitude);
        $lng1 = deg2rad($this->longitude);
        $lat2 = deg2rad($lat);
        $lng2 = deg2rad($lng);

        $dlat = $lat2 - $lat1;
        $dlng = $lng2 - $lng1;

        $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2);
        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));

        return 6371 * $c; // المسافة بالكيلومترات
    }
}
