<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class Voucher extends Model
{
    use HasFactory;
    use LogsActivity;

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

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

    protected $fillable = [
        'number',
        'nominal',
        'calculation_type',
        'description',
        'customer_id',
        'expired_at',
        'voucher_event_id',
        'affiliator_id',
        'reference_issued_id',
        'item_reference_id',
        'reference_issued_type',
        'reference_used_id',
        'reference_used_type',
        'used_at',
        'max_nominal',
        'percent',
        'min_sales'
    ];

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

    public function customer() {
        return $this->belongsTo(Customer::class, 'customer_id', 'id');
    }

    public function event(){
        return $this->belongsTo(VoucherEvent::class,"voucher_event_id");
    }

    public function location(){
        return $this->belongsTo(Location::class,"location_id");
    }

    public function affiliator(){
        return $this->belongsTo(Affiliator::class);
    }

    public function referenceIssued(){
        return $this->morphTo();
    }

    public function referenceUsed(){
        return $this->morphTo();
    }

    public function item()
    {
        return $this->belongsTo(ItemReference::class, 'item_reference_id', 'id');
    }
}
