<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class Sales extends Model
{
    use HasFactory, SoftDeletes, Sluggable;
    use LogsActivity;

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults();
   }

    protected $table = 'sales';
    protected $primaryKey = 'id';

    protected $fillable = [
        'id',
        'number',
        'name',
        'phone',
        'email',
        'address',
        'country',
        'province_id',
        'city_id',
        'district_id',
        'village_id',
        'postal_code',
        'customer_group_id',
        'location_id',
    ];

    public function sluggable(): array
    {
        return [
            'number' => [
                'source' => 'number'
            ]
        ];
    }

    public function scopeFilter(Builder $query, array $filters)
    {
        $query->when($filters['search'] ?? false, function ($query, $search) {
            return $query
                ->where('name', 'iLIKE', '%' . $search . '%')
                ->orWhere('phone', 'LIKE', '%' . $search . '%');
        });
    }

    public function locations()
    {
        return $this->belongsTo(Location::class, 'location_id', 'id');
    }

    public function customerGroup()
    {
        return $this->belongsTo(CustomerGroup::class, 'customer_group_id', 'id');
    }
}
