<?php

namespace App\Domain\Payroll\Models;

use App\Domain\HR\Models\Employee;
use App\Support\Concerns\HasUuid;
use App\Support\Money\Money;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * One employee's pay for one period (§54).
 *
 * The lines snapshot the component names, so renaming a component next year
 * does not rewrite what a payslip said at the time.
 */
class Payslip extends Model
{
    use HasUuid;

    protected $guarded = ['id', 'uuid'];

    protected function casts(): array
    {
        return [
            'basic_salary' => 'integer',
            'gross_earnings' => 'integer',
            'total_deductions' => 'integer',
            'employer_contributions' => 'integer',
            'net_pay' => 'integer',
            'days_worked' => 'integer',
            'days_absent' => 'integer',
            'overtime_hours' => 'integer',
            'paid_on' => 'date',
        ];
    }

    public function run(): BelongsTo
    {
        return $this->belongsTo(PayrollRun::class, 'payroll_run_id');
    }

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

    public function lines(): HasMany
    {
        return $this->hasMany(PayslipLine::class)->orderBy('sort_order')->orderBy('id');
    }

    public function net(): Money
    {
        return Money::of((int) $this->net_pay, $this->currency);
    }
}
