<?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\BelongsToMany;

class Location extends Model
{
    use HasFactory;

    const STATUS_INACTIVE = 0;

    const STATUS_ACTIVE = 1;

    protected $guarded = [];

    protected $fillable = [
        'name',
        'slug',
        'address_id',
        'description',
        'status',
    ];

    protected $casts = [
        'status' => 'integer',
    ];

    public function getRouteKeyName()
    {
        return 'slug';
    }

    public function products(): BelongsToMany
    {
        return $this->belongsToMany(Product::class, 'location_product')
            ->withPivot(['quantity'])
            ->withTimestamps();
    }

    public function address(): BelongsTo
    {
        return $this->belongsTo(Address::class, 'address_id');
    }

    // Accessor for status text
    public function getStatusTextAttribute()
    {
        return $this->status === self::STATUS_ACTIVE ? 'Actif' : 'Inactif';
    }

    // Accessor for status badge
    public function getStatusBadgeAttribute()
    {
        if ($this->status === self::STATUS_ACTIVE) {
            return '<span class="inline-block px-3 py-1 border border-green-500 bg-green-100 text-xs font-medium rounded text-green-700">Actif</span>';
        }

        return '<span class="inline-block px-3 py-1 border border-red-500 bg-red-100 text-xs font-medium rounded text-red-700">Inactif</span>';
    }
}
