<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class ServiceType extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'value',
    ];

    protected $appends = [
        'quantity',
        'amount',
        'sales_percentage',
        'average_price',
    ];

    public function getQuantityAttribute($created_at = null, $created_until = null): int
    {
        return $this->productServices()
            ->when($created_at, fn ($query) => $query->whereDate('created_at', '>=', $created_at))
            ->when($created_until, fn ($query) => $query->whereDate('created_at', '<=', $created_until))
            ->sum('amount');
    }

    public function getAmountAttribute($created_at = null, $created_until = null): float
    {
        return $this->productServices()
            ->when($created_at, fn ($query) => $query->whereDate('created_at', '>=', $created_at))
            ->when($created_until, fn ($query) => $query->whereDate('created_at', '<=', $created_until))
            ->sum('amount_price');
    }

    public function getSalesPercentageAttribute($created_at = null, $created_until = null): float
    {
        $query = ProductService::query()
            ->when($created_at, fn ($query) => $query->whereDate('created_at', '>=', $created_at))
            ->when($created_until, fn ($query) => $query->whereDate('created_at', '<=', $created_until));

        $total = $query->count();

        $part = $query->where('service_type_id', $this->id)->count();

        if ($total == 0) {
            return 0.0;
        }

        return round(($part / $total) * 100, 1);
    }

    public function getAveragePriceAttribute($created_at = null, $created_until = null): string
    {
        $quantity = $this->getQuantityAttribute($created_at, $created_until);
        $amount   = $this->getAmountAttribute($created_at, $created_until);

        if ($quantity == 0) {
            return '0.0';
        }

        try {
            return number_format($quantity / $amount, 2);
        } catch (\Exception $exception) {
            dd($quantity, $amount, $exception);
        }
    }

    public function productServices(): HasMany
    {
        return $this->hasMany(ProductService::class);
    }
}
