<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Tax extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'type',
        'rate',
        'components',
        'is_active',
    ];

    protected function casts(): array
    {
        return [
            'rate' => 'decimal:2',
            'components' => 'array',
            'is_active' => 'boolean',
        ];
    }

    public function products()
    {
        return $this->hasMany(Product::class);
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Calculate total rate from components
     */
    public function calculateTotalRate(): float
    {
        if ($this->type === 'single') {
            return $this->rate;
        }

        if (empty($this->components) || !is_array($this->components)) {
            return 0;
        }

        return array_sum(array_column($this->components, 'rate'));
    }
}
