<?php

namespace Modules\Billing\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Modules\Accounts\Models\Traits\HasVatTransactions;
use Modules\Billing\Models\Traits\HasBillingItems;
use Modules\Billing\Models\Traits\HasServiceDepartment;
use Modules\Billing\Models\Traits\ServiceRelationshipTrait;
use Modules\Core\Enums\AmountTypeEnum;
use Modules\Core\Traits\HasStatus;

class ServiceOffering extends Model
{
    use HasStatus,
        HasBillingItems,
        HasServiceDepartment,
        ServiceRelationshipTrait,
        HasVatTransactions;

    /**
     * The attributes that are mass assignable.
     */
    protected $fillable = [
        'name',
        'service_code',
        'service_department_id',
        'service_type',
        'sales_account_id',
        'base_fee',
        'vat_price_type',
        'vat_type',
        'vat_rate',
        'subsidy_type',
        'subsidy_value',
        'status',
    ];

    public function getSellingPriceAttribute(): float
    {
        $price = (float) $this->base_fee;

        if ($this->subsidy_value <= 0) {
            return $price;
        }

        return match ($this->subsidy_type) {
            AmountTypeEnum::FIXED->value => max(0,
                $price - $this->subsidy_value
            ),
            AmountTypeEnum::PERCENTAGE->value => max(0,
                $price - (($price * $this->subsidy_value) / 100)
            ),

            default => $price,
        };
    }

    public function scopeSearch(Builder $query, ?string $term): Builder
    {
        if (blank($term)) {
            return $query;
        }

        $term = '%' . trim($term) . '%';

        return $query->where(function ($q) use ($term) {
            $q->where('name', 'LIKE', $term)
                ->orWhere('service_code', 'LIKE', $term);
        });
    }

    public function scopeByType(Builder $query, ?string $type): Builder
    {
        return $type ? $query->where('service_type', $type) : $query;
    }
}
