<?php

namespace App\Models;

use App\Enums\IsPaid;
use App\Observers\PayrollObserver;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

#[ObservedBy([PayrollObserver::class])]
class Payroll extends Model
{
    /** @use HasFactory<\Database\Factories\PayrollFactory> */
    use HasFactory, SoftDeletes;

    protected $guarded = ['id'];

    protected function casts(): array
    {
        return [
            'is_paid' => IsPaid::class,
            'paid_at' => 'datetime',
            'base_salary' => 'integer',
            'bonus' => 'integer',
            'deduction' => 'integer',
            'total_salary' => 'integer',
        ];
    }

    #[Scope]
    protected function paid(Builder $query): void
    {
        $query->where('is_paid', IsPaid::PAID->value);
    }

    #[Scope]
    protected function notPaid(Builder $query): void
    {
        $query->where('is_paid', IsPaid::NOT_PAID->value);
    }

    protected function periodLabel(): Attribute
    {
        return Attribute::make(
            get: fn () => Carbon::parse($this->period_month)->translatedFormat('F Y'),
        );
    }

    protected function isPaidLabel(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->is_paid->value === IsPaid::PAID->value ? IsPaid::PAID->value : IsPaid::NOT_PAID->value,
        );
    }

    protected function baseSalaryFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => 'Rp '.number_format($this->base_salary, 0, ',', '.'),
        );
    }

    protected function bonusFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => 'Rp '.number_format($this->bonus, 0, ',', '.'),
        );
    }

    protected function deductionFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => 'Rp '.number_format($this->deduction, 0, ',', '.'),
        );
    }

    protected function totalSalaryFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => 'Rp '.number_format($this->total_salary, 0, ',', '.'),
        );
    }

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

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