<?php

namespace App\Models;

use App\Scopes\ZoneScope;
use App\Scopes\StoreScope;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Casts\Attribute;

use function PHPUnit\Framework\returnSelf;

class Item extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'category_id', 'category_ids', 'veg', 'price', 'discount', 'discount_type', 'description', 'available_time_starts', 'available_time_ends', 'opening_times', 'unit_id', 'image', 'images', 'store_id', 'module_id', 'stock', 'add_ons', 'attributes', 'choice_options', 'variations', 'is_approved', 'data_to_update', 'vendor_product_id'];

    protected $casts = [
        'tax' => 'float',
        'price' => 'float',
        'status' => 'integer',
        'discount' => 'float',
        'avg_rating' => 'float',
        'set_menu' => 'integer',
        'category_id' => 'integer',
        'store_id' => 'integer',
        'reviews_count' => 'integer',
        'recommended' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'veg'=>'integer',
        'images'=>'array',
        'module_id'=>'integer',
        'stock'=>'integer',
        "min_price" => 'float',
        "max_price" => 'float',
        //'opening_times' => 'array',
    ];

    protected $appends = ['unit_type', 'item_schedules'];

    protected function itemSchedules(): Attribute
    {
        return Attribute::get(function () {
            // 1) تأكّد إنه opening_times مصفوفة فعلية
            $opening = $this->opening_times;

            if (is_string($opening)) {
                // لو كان مخزن كسطر JSON، حاول تفكّه
                $decoded = json_decode($opening, true);
                if (json_last_error() === JSON_ERROR_NONE) {
                    $opening = $decoded;
                }
            }

            if (is_array($opening) && count($opening) > 0) {
                return collect($opening)
                    ->map(function ($time) {
                        $start = isset($time['start']) ? substr((string)$time['start'], 0, 5) : null;
                        $end   = isset($time['end'])   ? substr((string)$time['end'], 0, 5)   : null;
                        // تجاهل الفترات غير الصالحة
                        if (empty($start) || empty($end)) return null;
                        return ['start' => $start, 'end' => $end];
                    })
                    ->filter() // يزيل القيم null الناتجة عن فترات غير صالحة
                    ->values()
                    ->all();
            }

            // 2) fallback على available_time_starts / available_time_ends
            $startRaw = $this->available_time_starts ?? null;
            $endRaw   = $this->available_time_ends ?? null;

            // نلغي الافتراضات إذا الاثنين غير موجودين
            if (empty($startRaw) && empty($endRaw)) {
                return []; // نرجع مصفوفة فارغة بدل null
            }

            $start = $startRaw ? substr((string)$startRaw, 0, 5) : null;
            $end   = $endRaw ? substr((string)$endRaw, 0, 5) : null;

            if (empty($start) || empty($end)) {
                return []; // لو واحدة ناقصة، نخليها فارغة بدل ترجيع بيانات غير صحيحة
            }

            return [['start' => $start, 'end' => $end]];
        });
    }

    public function scopeRecommended($query)
    {
        return $query->where('recommended',1);
    }

    public function translations()
    {
        return $this->morphMany(Translation::class, 'translationable');
    }

    public function scopeModule($query, $module_id)
    {
        return $query->where('module_id', $module_id);
    }

    public function scopeActive($query)
    {
        return $query->where('status', 1)->where(function ($query){
            return $query->where('is_approved', 1)->orWhere(function ($q){
                return $q->where('is_approved', 0)->where('data_to_update', '!=', NULL);
            });
        })->whereHas('store', function($query){
            return $query->where('status', 1);
        });
    }

    public function scopeNotApproved($query)
    {
        return $query->where('is_approved', 0);
    }

    public function scopePopular($query)
    {
        return $query->orderBy('order_count', 'desc');
    }

    public function scopeHasDiscount($query)
    {
        return $query->where('discount', '>', 0);
    }

    public function reviews()
    {
        return $this->hasMany(Review::class)->latest();
    }

    public function whislists()
    {
        return $this->hasMany(Wishlist::class);
    }

    public function unit()
    {
        return $this->belongsTo(Unit::class,'unit_id');
    }

    public function module()
    {
        return $this->belongsTo(Module::class,'module_id');
    }

    public function getUnitTypeAttribute()
    {
        return $this->unit?$this->unit->unit:null;
    }

    public function store()
    {
        return $this->belongsTo(Store::class);
    }

    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id');
    }

    public function orders()
    {
        return $this->hasMany(OrderDetail::class);
    }

    protected static function booted()
    {
        if(auth('vendor')->check() || auth('vendor_employee')->check())
        {
            static::addGlobalScope(new StoreScope);
        }

        static::addGlobalScope(new ZoneScope);

        static::addGlobalScope('translate', function (Builder $builder) {
            $builder->with(['translations' => function($query){
                return $query->where('locale', app()->getLocale());
            }]);
        });
    }


    public function scopeType($query, $type)
    {
        if($type == 'veg')
        {
            return $query->where('veg', true);
        }
        else if($type == 'non_veg')
        {
            return $query->where('veg', false);
        }

        return $query;
    }

    public function tags()
    {
        return $this->belongsToMany(Tag::class);
    }

    protected static function boot()
    {
        parent::boot();
        static::created(function ($item) {
            $item->slug = $item->generateSlug($item->name);
            $item->save();
        });
    }
    private function generateSlug($name)
    {
        $slug = Str::slug($name);
        if ($max_slug = static::where('slug', 'like',"{$slug}%")->latest('id')->value('slug')) {

            if($max_slug == $slug) return "{$slug}-2";

            $max_slug = explode('-',$max_slug);
            $count = array_pop($max_slug);
            if (isset($count) && is_numeric($count)) {
                $max_slug[]= ++$count;
                return implode('-', $max_slug);
            }
        }
        return $slug;
    }

}
