<?php

namespace App\Observers;

use App\Enums\SalaryAdjustmentType;
use App\Models\PayrollAdjustment;

class PayrollAdjustmentObserver
{
    public function saved(PayrollAdjustment $adjustment): void
    {
        $this->updatePayroll($adjustment);
    }

    public function deleted(PayrollAdjustment $adjustment): void
    {
        $this->updatePayroll($adjustment);
    }

    public function restored(PayrollAdjustment $adjustment): void
    {
        $this->updatePayroll($adjustment);
    }

    protected function updatePayroll(PayrollAdjustment $adjustment): void
    {
        $payroll = $adjustment->payroll;
        if (! $payroll) {
            return;
        }

        $bonus = $payroll->adjustments()->where('type', SalaryAdjustmentType::BONUS)->sum('amount');
        $deduction = $payroll->adjustments()->where('type', SalaryAdjustmentType::DEDUCTION)->sum('amount');

        $payroll->update([
            'bonus' => $bonus,
            'deduction' => $deduction,
        ]);
    }
}
