<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ContributionPenalty extends Model
{
    use HasFactory, SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'membership_category_id',
        'name',
        'description',
        'type',
        'amount',
        'percentage',
        'grace_period_days',
        'is_active',
        'apply_recurring',
        'max_penalty_days',
        'created_by',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'amount' => 'decimal:2',
        'percentage' => 'decimal:2',
        'grace_period_days' => 'integer',
        'is_active' => 'boolean',
        'apply_recurring' => 'boolean',
        'max_penalty_days' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

    /**
     * Get the membership category for the penalty.
     */
    public function membershipCategory(): BelongsTo
    {
        return $this->belongsTo(MembershipCategory::class);
    }

    /**
     * Get the user who created the penalty.
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Scope a query to only include active penalties.
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Calculate penalty amount for a given contribution amount.
     */
    public function calculatePenalty(float $contributionAmount, int $daysOverdue): float
    {
        // Check if within grace period
        if ($daysOverdue <= $this->grace_period_days) {
            return 0;
        }

        $effectiveDays = $daysOverdue - $this->grace_period_days;

        // Apply max penalty days limit
        if ($this->max_penalty_days && $effectiveDays > $this->max_penalty_days) {
            $effectiveDays = $this->max_penalty_days;
        }

        if ($this->type === 'fixed') {
            if ($this->apply_recurring) {
                return $this->amount * $effectiveDays;
            }
            return $this->amount;
        }

        // Percentage-based penalty
        $penaltyRate = $this->percentage / 100;
        if ($this->apply_recurring) {
            return ($contributionAmount * $penaltyRate) * $effectiveDays;
        }
        return $contributionAmount * $penaltyRate;
    }

    /**
     * Get penalty type display name.
     */
    public function getTypeDisplayAttribute(): string
    {
        return match($this->type) {
            'fixed' => 'Fixed Amount',
            'percentage' => 'Percentage',
            default => ucfirst($this->type),
        };
    }
}
