<?php

declare(strict_types=1);

namespace Kylin\Hr\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * 社保模型
 *
 * 管理员工社保缴纳信息，包括养老、医疗、工伤、失业、生育等。
 *
 * @property float $base_amount      社保基数
 * @property float $pension_personal 个人养老
 * @property float $pension_company  公司养老
 * @property float $medical_personal 个人医疗
 * @property float $medical_company  公司医疗
 */
class SocialInsurance extends Model
{
    protected $fillable = [
        'employee_id',
        'base_amount',
        'pension_personal',
        'pension_company',
        'medical_personal',
        'medical_company',
        'unemployment_personal',
        'unemployment_company',
        'injury_company',
        'maternity_company',
        'housing_personal',
        'housing_company',
        'effective_date',
    ];

    protected function casts(): array
    {
        return [
            'base_amount' => 'decimal:2',
            'pension_personal' => 'decimal:4',
            'pension_company' => 'decimal:4',
            'medical_personal' => 'decimal:4',
            'medical_company' => 'decimal:4',
            'unemployment_personal' => 'decimal:4',
            'unemployment_company' => 'decimal:4',
            'injury_company' => 'decimal:4',
            'maternity_company' => 'decimal:4',
            'housing_personal' => 'decimal:4',
            'housing_company' => 'decimal:4',
            'effective_date' => 'date',
        ];
    }

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

    /**
     * 计算个人部分合计
     */
    public function getPersonalTotalAttribute(): float
    {
        $base = $this->base_amount;
        return round(
            $base * $this->pension_personal
            + $base * $this->medical_personal
            + $base * $this->unemployment_personal
            + $base * $this->housing_personal,
            2
        );
    }

    /**
     * 计算企业部分合计
     */
    public function getCompanyTotalAttribute(): float
    {
        $base = $this->base_amount;
        return round(
            $base * $this->pension_company
            + $base * $this->medical_company
            + $base * $this->unemployment_company
            + $base * $this->injury_company
            + $base * $this->maternity_company
            + $base * $this->housing_company,
            2
        );
    }
}
