<?php

namespace App\Models;

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

class Payroll extends Model
{
    use HasFactory;

    protected $fillable = [
        'employee_id',
        'period_month',
        'basic_salary',
        'total_allowances',
        'total_deductions',
        'net_salary',
        'status',
        'payment_date',
        'treasury_id',
    ];

    protected $casts = [
        'basic_salary' => 'decimal:2',
        'total_allowances' => 'decimal:2',
        'total_deductions' => 'decimal:2',
        'net_salary' => 'decimal:2',
        'payment_date' => 'date',
    ];

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

    public function treasury()
    {
        return $this->belongsTo(Treasury::class);
    }

    public function items()
    {
        return $this->hasMany(PayrollItem::class);
    }

    /**
     * Calculate net salary from basic + allowances - deductions.
     */
    public function calculateNetSalary()
    {
        $allowances = $this->items()->where('type', 'allowance')->orWhere('type', 'bonus')->sum('amount');
        $deductions = $this->items()->where('type', 'deduction')->orWhere('type', 'penalty')->sum('amount');

        $this->total_allowances = $allowances;
        $this->total_deductions = $deductions;
        $this->net_salary = $this->basic_salary + $allowances - $deductions;
        return $this;
    }
}
