<?php

namespace App\Models;

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

class Property extends Model
{
    use HasFactory;

    protected $fillable = [
        'property_name','slug', 'category_name', 'banner_img', 'price', 'security_deposit',
        'youtube_url', 'description', 'meta_title', 'meta_description',
    ];

    //Slug Code Start
    protected static function booted()
    {
        static::creating(function ($property) {
            $property->slug = static::generateUniqueSlug($property->property_name);
        });

        static::updating(function ($property) {
            // Only update slug if the name has changed
            if ($property->isDirty('property_name')) {
                $property->slug = static::generateUniqueSlug($property->property_name, $property->id);
            }
        });
    }

    protected static function generateUniqueSlug($name, $ignoreId = null)
    {
        $slug = Str::slug($name);
        $originalSlug = $slug;
        $count = 2;

        while (
            static::where('slug', $slug)
            ->when($ignoreId, fn($query) => $query->where('id', '!=', $ignoreId))
            ->exists()
        ) {
            $slug = $originalSlug . '-' . $count;
            $count++;
        }

        return $slug;
    }
    //Slug Code END

    protected $hidden = ['created_at', 'updated_at'];

    public function address()
    {
        return $this->hasOne(Address::class);
    }

    public function amenities()
    {
        return $this->hasOne(Amenity::class);
    }

    public function detail()
    {
        return $this->hasOne(Detail::class);
    }
    
    public function floorPlans()
    {
        return $this->hasMany(FloorPlan::class);
    }


    public function galleryImages()
    {
        //return $this->hasMany(GalleryImage::class);
        return $this->hasMany(GalleryImage::class, 'property_id');
    }

}
