<?php

namespace Modules\SystemCore\App\Models;

use App\Traits\UserActionsTrait;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class CoreTaxConfiguration extends Model
{
    use SoftDeletes, UserActionsTrait;

    protected $table = 'core_tax_configurations';

    protected $fillable = [
        'name',
        'code',
        'rate',
        'type',
        'tax_authority',
        'is_default',
        'description',
        'is_active',
        'created_by_id',
        'updated_by_id',
    ];

    protected function casts(): array
    {
        return [
            'rate' => 'decimal:4',
            'is_active' => 'boolean',
            'is_default' => 'boolean',
        ];
    }

    /**
     * Get products using this tax
     */
    public function products(): HasMany
    {
        return $this->hasMany(CoreProduct::class, 'tax_id');
    }

    /**
     * Scope for active taxes
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Get the default tax configuration.
     */
    public static function getDefault(): ?self
    {
        return static::where('is_default', true)->where('is_active', true)->first();
    }

    /**
     * Get active tax configurations.
     */
    public static function getActive(): Collection
    {
        return static::where('is_active', true)->orderBy('name')->get();
    }

    /**
     * Set this tax configuration as default (and unset others).
     */
    public function setAsDefault(): void
    {
        // Remove default from all other tax configurations
        static::where('is_default', true)->update(['is_default' => false]);

        // Set this one as default
        $this->update(['is_default' => true]);
    }

    /**
     * Format the rate based on type.
     */
    public function getFormattedRateAttribute(): string
    {
        if ($this->type === 'percentage') {
            return number_format($this->rate, 2).'%';
        }

        return number_format($this->rate, 2);
    }

    /**
     * Check if this tax configuration is in use
     */
    public function isInUse(): bool
    {
        return $this->products()->exists();
    }

    /**
     * Calculate tax amount for a given base amount
     */
    public function calculateTax(float $amount): float
    {
        if ($this->type === 'percentage') {
            return ($amount * $this->rate) / 100;
        }

        return (float) $this->rate;
    }
}
