<?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;
use Illuminate\Notifications\Notifiable;

class Customer extends Model
{
    use HasFactory, SoftDeletes, Sluggable, Notifiable;
    use LogsActivity;

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

    protected $table = 'customers';
    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',
        'referal',
        'is_active',
        'verified_at',
        'user_id',
        'organization',
        'prefix',
        'channel',
        'creator_id',
        'gender',
        'date_of_birth',
        'profilling_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');
    }

    // public function proffiling()
    // {
    //     return $this->hasMany(FittingOrderCustomer::class);
    // }

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

    // public function chat()
    // {
    //     return $this->hasMany(Chat::class);
    // }

    // public function profillings()
    // {
    //     return $this->hasMany(Profilling::class);
    // }
    
    // public function clubMembers()
    // {
    //     return $this->hasMany(ClubMember::class, 'customer_id', 'id');
    // }

    public function getPointAttribute()
    {
        return $this->hasMany(CustomerPoint::class)->sum("point");
    }
    
    public function routeNotificationForEmail()
    {
        $email = $this->email;
        return $email;
    }
}
