<?php

namespace App\Models;

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

class InsuranceProduct extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'code',
        'description',
        'type',
        'max_coverage_amount',
        'min_coverage_amount',
        'max_term_months',
        'min_term_months',
        'premium_calculation_type',
        'premium_rate',
        'fixed_premium_amount',
        'tiered_rates',
        'application_fee',
        'processing_fee',
        'claim_fee',
        'is_active',
        'requires_medical_check',
        'allows_multiple_claims',
        'max_claims_per_year',
        'created_by',
    ];

    protected $casts = [
        'max_coverage_amount' => 'decimal:2',
        'min_coverage_amount' => 'decimal:2',
        'premium_rate' => 'decimal:2',
        'fixed_premium_amount' => 'decimal:2',
        'tiered_rates' => 'array',
        'application_fee' => 'decimal:2',
        'processing_fee' => 'decimal:2',
        'claim_fee' => 'decimal:2',
        'is_active' => 'boolean',
        'requires_medical_check' => 'boolean',
        'allows_multiple_claims' => 'boolean',
    ];

    // Relationships
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function policies()
    {
        return $this->hasMany(InsurancePolicy::class);
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeByType($query, $type)
    {
        return $query->where('type', $type);
    }

    // Accessors
    public function getDisplayNameAttribute()
    {
        return $this->name . ' (' . $this->code . ')';
    }

    public function getFormattedPremiumRateAttribute()
    {
        if ($this->premium_calculation_type === 'percentage') {
            return number_format((float) $this->premium_rate, 2) . '%';
        } elseif ($this->premium_calculation_type === 'fixed') {
            return '$' . number_format((float) $this->fixed_premium_amount, 2);
        }
        return 'Tiered';
    }

    // Methods
    public function isActive()
    {
        return $this->is_active;
    }

    public function calculatePremium($coverageAmount, $termMonths = null)
    {
        switch ($this->premium_calculation_type) {
            case 'fixed':
                return $this->fixed_premium_amount ?? 0;

            case 'percentage':
                $annualPremium = ($coverageAmount * $this->premium_rate) / 100;
                return $this->adjustPremiumForFrequency($annualPremium);

            case 'tiered':
                return $this->calculateTieredPremium($coverageAmount);

            default:
                return 0;
        }
    }

    private function adjustPremiumForFrequency($annualPremium)
    {
        // Assuming monthly frequency for simplicity
        // In a real implementation, you'd adjust based on premium_frequency
        return $annualPremium / 12;
    }

    private function calculateTieredPremium($coverageAmount)
    {
        if (!$this->tiered_rates) {
            return 0;
        }

        $tiers = $this->tiered_rates;
        $premium = 0;

        foreach ($tiers as $tier) {
            if ($coverageAmount <= $tier['max_amount']) {
                $premium = ($coverageAmount * $tier['rate']) / 100;
                break;
            }
        }

        return $this->adjustPremiumForFrequency($premium);
    }

    public function getTotalFees()
    {
        return $this->application_fee + $this->processing_fee + $this->claim_fee;
    }

    public function allowsMultipleClaims()
    {
        return $this->allows_multiple_claims;
    }

    public function requiresMedicalCheck()
    {
        return $this->requires_medical_check;
    }
}
