<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class GasOffice extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'description',
        'address',
        'latitude',
        'longitude',
        'phone',
        'email',
        'owner_id',
        'logo',
        'cover_image',
        'is_active',
        'is_open',
        'opening_time',
        'closing_time',
        'delivery_fee',
        'delivery_time_minutes',
        'minimum_order',
        'service_areas',
        'rating',
        'rating_count',
    ];

    protected $casts = [
        'latitude' => 'decimal:8',
        'longitude' => 'decimal:8',
        'is_active' => 'boolean',
        'is_open' => 'boolean',
        'opening_time' => 'string',
        'closing_time' => 'string',
        'delivery_fee' => 'decimal:2',
        'minimum_order' => 'decimal:2',
        'rating' => 'decimal:2',
        'service_areas' => 'array',
    ];

    /**
     * صاحب مكتب الغاز
     */
    public function owner(): BelongsTo
    {
        return $this->belongsTo(User::class, 'owner_id');
    }

    /**
     * قناني الغاز المتوفرة في هذا المكتب
     */
    public function gasCylinders(): HasMany
    {
        return $this->hasMany(GasCylinder::class);
    }

    /**
     * طلبات الغاز من هذا المكتب
     */
    public function gasOrders(): HasMany
    {
        return $this->hasMany(GasOrder::class);
    }

    /**
     * التحقق من أن المكتب مفتوح الآن
     */
    public function isCurrentlyOpen(): bool
    {
        if (!$this->is_open) {
            return false;
        }

        $now = now();
        $currentTime = $now->format('H:i:s');

        if ($this->opening_time && $this->closing_time) {
            // opening_time و closing_time هما strings (H:i:s format)
            $openingTime = is_string($this->opening_time) ? $this->opening_time : $this->opening_time->format('H:i:s');
            $closingTime = is_string($this->closing_time) ? $this->closing_time : $this->closing_time->format('H:i:s');
            
            return $currentTime >= $openingTime && $currentTime <= $closingTime;
        }

        return true;
    }

    /**
     * حساب المسافة من نقطة معينة
     */
    public function distanceFrom($latitude, $longitude): float
    {
        if (!$this->latitude || !$this->longitude) {
            return 999999; // مسافة كبيرة جداً إذا لم يكن هناك موقع
        }

        $lat1 = deg2rad($this->latitude);
        $lon1 = deg2rad($this->longitude);
        $lat2 = deg2rad($latitude);
        $lon2 = deg2rad($longitude);

        $deltaLat = $lat2 - $lat1;
        $deltaLon = $lon2 - $lon1;

        $a = sin($deltaLat / 2) * sin($deltaLat / 2) +
             cos($lat1) * cos($lat2) *
             sin($deltaLon / 2) * sin($deltaLon / 2);

        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));

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

    /**
     * البحث عن مكاتب قريبة
     */
    public static function nearby($latitude, $longitude, $radius = 10)
    {
        return static::where('is_active', true)
            ->where('is_open', true)
            ->get()
            ->filter(function ($office) use ($latitude, $longitude, $radius) {
                return $office->distanceFrom($latitude, $longitude) <= $radius;
            })
            ->sortBy(function ($office) use ($latitude, $longitude) {
                return $office->distanceFrom($latitude, $longitude);
            });
    }

    /**
     * Get platform fees for this gas office.
     */
    public function platformFees()
    {
        return $this->hasMany(PlatformFee::class, 'service_provider_id')
                    ->where('service_provider_type', 'gas_office');
    }
}
