<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Restaurant extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'name',
        'description',
        'address',
        'governorate', // إضافة جديدة
        'city', // إضافة جديدة
        'governorate_id', // معرف المحافظة
        'city_id', // معرف المدينة
        'latitude',
        'longitude',
        'phone',
        'email',
        'cuisine_type',
        'rating',
        'rating_count',
        'logo',
        'cover_image',
        'is_active',
        'is_open',
        'opening_time',
        'closing_time',
        'delivery_fee',
        'delivery_time_minutes',
        'minimum_order',
    ];

    protected $casts = [
        'user_id' => 'integer',
        'governorate_id' => 'integer',
        'city_id' => 'integer',
        'is_active' => 'boolean',
        'is_open' => 'boolean',
        'rating' => 'decimal:2',
        'delivery_fee' => 'decimal:2',
        'minimum_order' => 'decimal:2',
        'latitude' => 'decimal:8',
        'longitude' => 'decimal:8',
        'opening_time' => 'string',
        'closing_time' => 'string',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    public function menuItems()
    {
        return $this->hasMany(MenuItem::class);
    }

    public function foodOrders()
    {
        return $this->hasMany(FoodOrder::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function manager()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function governorate()
    {
        return $this->belongsTo(Governorate::class);
    }

    public function city()
    {
        return $this->belongsTo(City::class);
    }

    // Helper methods للمحافظة والمدينة
    public function getGovernorateAttribute($value)
    {
        return $value ?: $this->extractGovernorateFromAddress();
    }

    public function getCityAttribute($value)
    {
        return $value ?: $this->extractCityFromAddress();
    }

    // استخراج المحافظة من العنوان إذا لم تكن محددة
    private function extractGovernorateFromAddress()
    {
        if (!$this->address) {
            return null;
        }

        $governorates = [
            'بغداد', 'البصرة', 'النجف', 'كربلاء', 'الأنبار', 'نينوى', 
            'أربيل', 'السليمانية', 'دهوك', 'كركوك', 'صلاح الدين', 
            'ديالى', 'بابل', 'واسط', 'ذي قار', 'ميسان', 'المثنى', 'القادسية'
        ];

        foreach ($governorates as $governorate) {
            if (str_contains($this->address, $governorate)) {
                return $governorate;
            }
        }

        return null;
    }

    // استخراج المدينة من العنوان إذا لم تكن محددة
    private function extractCityFromAddress()
    {
        if (!$this->address) {
            return null;
        }

        // يمكن تحسين هذه الدالة حسب نمط العناوين في قاعدة البيانات
        $addressParts = explode(',', $this->address);
        if (count($addressParts) > 1) {
            return trim($addressParts[0]);
        }

        return null;
    }

    public function getManagerName()
    {
        return $this->user ? $this->user->name : 'غير محدد';
    }

    public function getManagerEmail()
    {
        return $this->user ? $this->user->email : 'غير محدد';
    }

    public function getManagerPhone()
    {
        return $this->user ? $this->user->phone : 'غير محدد';
    }

    public function getAverageRating()
    {
        return $this->rating ?? 0;
    }

    public function getTotalOrders()
    {
        return $this->foodOrders()->count();
    }

    public function isCurrentlyOpen()
    {
        if (!$this->is_open || !$this->is_active) {
            return false;
        }

        if (!$this->opening_time || !$this->closing_time) {
            return true;
        }

        $now = now()->format('H:i:s');
        $opening = $this->opening_time;
        $closing = $this->closing_time;

        return $now >= $opening && $now <= $closing;
    }

    public function getPopularItems()
    {
        return $this->menuItems()
            ->where('is_popular', true)
            ->where('is_available', true)
            ->orderBy('rating', 'desc')
            ->limit(5)
            ->get();
    }

    public function getAvailableItems()
    {
        return $this->menuItems()
            ->where('is_available', true)
            ->orderBy('category')
            ->orderBy('name')
            ->get();
    }

    public function getOpeningTimeFormatted()
    {
        if (!$this->opening_time) {
            return 'غير محدد';
        }
        
        if (strpos($this->opening_time, ':') !== false) {
            $time = explode(':', $this->opening_time);
            return $time[0] . ':' . $time[1];
        }
        
        return $this->opening_time;
    }

    public function getClosingTimeFormatted()
    {
        if (!$this->closing_time) {
            return 'غير محدد';
        }
        
        if (strpos($this->closing_time, ':') !== false) {
            $time = explode(':', $this->closing_time);
            return $time[0] . ':' . $time[1];
        }
        
        return $this->closing_time;
    }

    public function getWorkingHoursFormatted()
    {
        if (!$this->opening_time || !$this->closing_time) {
            return '24/7';
        }
        return $this->getOpeningTimeFormatted() . ' - ' . $this->getClosingTimeFormatted();
    }

    public function getDeliveryTimeFormatted()
    {
        return $this->delivery_time_minutes ? $this->delivery_time_minutes . ' دقيقة' : 'غير محدد';
    }

    public function getFormattedDeliveryFee()
    {
        return $this->delivery_fee ? number_format($this->delivery_fee, 0) . ' د.ع' : 'مجاني';
    }

    public function getFormattedMinimumOrder()
    {
        return $this->minimum_order ? number_format($this->minimum_order, 0) . ' د.ع' : 'غير محدد';
    }

    public function getStatusText()
    {
        if (!$this->is_active) {
            return 'غير نشط';
        }
        return $this->is_open ? 'مفتوح' : 'مغلق';
    }

    public function getStatusColor()
    {
        if (!$this->is_active) {
            return 'red';
        }
        return $this->is_open ? 'green' : 'orange';
    }

    public function getRatingStars()
    {
        $rating = $this->rating ?? 0;
        $stars = '';
        for ($i = 1; $i <= 5; $i++) {
            if ($i <= $rating) {
                $stars .= '★';
            } else {
                $stars .= '☆';
            }
        }
        return $stars;
    }

    public function getTotalMenuItems()
    {
        return $this->menuItems()->count();
    }

    public function getTotalPopularItems()
    {
        return $this->menuItems()->where('is_popular', true)->count();
    }

    public function getTotalAvailableItems()
    {
        return $this->menuItems()->where('is_available', true)->count();
    }

    public function getTotalRevenue()
    {
        return $this->foodOrders()->where('status', 'delivered')->sum('total');
    }

    public function getFormattedRevenue()
    {
        return number_format($this->getTotalRevenue(), 0) . ' د.ع';
    }

    public function getAverageOrderValue()
    {
        $totalOrders = $this->getTotalOrders();
        if ($totalOrders == 0) {
            return 0;
        }
        return $this->getTotalRevenue() / $totalOrders;
    }

    public function getFormattedAverageOrderValue()
    {
        return number_format($this->getAverageOrderValue(), 0) . ' د.ع';
    }

    // Scope methods للبحث
    public function scopeByGovernorate($query, $governorate)
    {
        return $query->where(function($q) use ($governorate) {
            $q->where('governorate', $governorate)
              ->orWhere('address', 'like', '%' . $governorate . '%');
        });
    }

    public function scopeByCity($query, $city)
    {
        return $query->where(function($q) use ($city) {
            $q->where('city', $city)
              ->orWhere('address', 'like', '%' . $city . '%');
        });
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeOpen($query)
    {
        return $query->where('is_open', true);
    }

    public function scopeByCuisineType($query, $cuisineType)
    {
        return $query->where('cuisine_type', $cuisineType);
    }

    public function scopeByRating($query, $minRating)
    {
        return $query->where('rating', '>=', $minRating);
    }

    public function scopeSearch($query, $search)
    {
        return $query->where('name', 'like', '%' . $search . '%');
    }

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