<?php

namespace App\Models;

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

class Payslip extends Model
{
    protected $guarded = ['id'];

    protected $casts = [
        'snap_date_joined' => 'date',
        'basic_salary'     => 'decimal:2',
        'total_earning'    => 'decimal:2',
        'total_deductions' => 'decimal:2',
        'allowance_total'  => 'decimal:2',
        'nett_pay'         => 'decimal:2',
    ];

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

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

    public function deductionLines(): HasMany
    {
        return $this->hasMany(PayslipLine::class)->where('category', 'deduction');
    }

    public function allowanceLines(): HasMany
    {
        return $this->hasMany(PayslipLine::class)->where('category', 'allowance');
    }

    public function periodLabel(): string
    {
        return strtoupper(\Carbon\Carbon::create($this->period_year, $this->period_month, 1)->format('F Y'));
    }

    // Sum of the fixed statutory/loan deduction columns.
    public function fixedDeductions(): float
    {
        return (float) ($this->epf_employee + $this->socso_employee + $this->eis_employee
            + $this->income_tax_pcb + $this->income_tax_cp38 + $this->unpaid_leave
            + $this->advance + $this->loan);
    }

    // Recalculate totals from components + line items, then persist net.
    public function recalculate(): void
    {
        $this->allowance_total = round((float) $this->lines()->where('category', 'allowance')->sum('amount'), 2);

        $this->total_earning = round(
            $this->basic_salary + $this->ot_amount + $this->ph_amount
            + $this->al_amount + $this->allowance_total, 2
        );

        $lineDeductions = $this->lines()->where('category', 'deduction')->sum('amount');
        $this->total_deductions = round($this->fixedDeductions() + $lineDeductions, 2);
        $this->nett_pay = round($this->total_earning - $this->total_deductions, 2);
    }
}
