<?php

namespace App\Models;

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

class EmployeeEarning extends Model
{
    use HasFactory;

    protected $fillable = [
        'employee_id',
        'earning_type_id',
        'amount',
        'currency',
        'effective_date',
        'end_date',
        'is_recurring',
        'frequency',
        'notes',
        'is_active',
        'created_by',
        'updated_by'
    ];

    protected $casts = [
        'amount' => 'decimal:2',
        'effective_date' => 'date',
        'end_date' => 'date',
        'is_recurring' => 'boolean',
        'is_active' => 'boolean'
    ];

    public function employee()
    {
        return $this->belongsTo(Employee::class, 'employee_id');
    }

    public function earningType()
    {
        return $this->belongsTo(EarningType::class, 'earning_type_id');
    }

    public function getFrequencyLabelAttribute()
    {
        $labels = [
            'monthly' => 'Monthly',
            'quarterly' => 'Quarterly',
            'annually' => 'Annually',
            'one-time' => 'One Time'
        ];

        return $labels[$this->frequency] ?? ucfirst($this->frequency);
    }

    public function getRecurringBadgeAttribute()
    {
        if ($this->is_recurring) {
            return '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-blue-100 text-blue-800">Recurring</span>';
        }
        return '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-yellow-100 text-yellow-800">One-time</span>';
    }

    public function getStatusBadgeAttribute()
    {
        if ($this->is_active) {
            return '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">Active</span>';
        }
        return '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-gray-100 text-gray-800">Inactive</span>';
    }

    public function isCurrent()
    {
        $today = now()->toDateString();
        
        if ($this->end_date && $today > $this->end_date) {
            return false;
        }
        
        return $today >= $this->effective_date;
    }

    public function getMonthlyAmount()
    {
        if (!$this->isCurrent()) {
            return 0;
        }

        switch ($this->frequency) {
            case 'monthly':
                return $this->amount;
            case 'quarterly':
                return $this->amount / 3;
            case 'annually':
                return $this->amount / 12;
            case 'one-time':
                return $this->is_recurring ? 0 : $this->amount; // One-time payments are handled specially
            default:
                return $this->amount;
        }
    }
}