<?php

namespace App\Models;

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

class PayrollPeriod extends Model
{
    public const STATUSES = ['draft', 'approved', 'rejected', 'paid'];

    protected $fillable = [
        'period_number', 'business_id', 'branch_id', 'name', 'start_date', 'end_date', 'pay_date', 'status',
        'total_gross', 'total_deductions', 'total_net', 'created_by', 'approved_by', 'approved_at',
        'rejected_by', 'rejected_at', 'decision_comments', 'paid_from_account_id', 'paid_by', 'paid_at',
    ];

    protected function casts(): array
    {
        return [
            'start_date' => 'date', 'end_date' => 'date', 'pay_date' => 'date', 'approved_at' => 'datetime',
            'rejected_at' => 'datetime', 'paid_at' => 'datetime', 'total_gross' => 'decimal:2',
            'total_deductions' => 'decimal:2', 'total_net' => 'decimal:2',
        ];
    }

    public function business(): BelongsTo { return $this->belongsTo(Business::class); }
    public function branch(): BelongsTo { return $this->belongsTo(Branch::class); }
    public function entries(): HasMany { return $this->hasMany(PayrollEntry::class)->orderBy('employee_name_snapshot'); }
    public function creator(): BelongsTo { return $this->belongsTo(User::class, 'created_by'); }
    public function approver(): BelongsTo { return $this->belongsTo(User::class, 'approved_by'); }
    public function rejecter(): BelongsTo { return $this->belongsTo(User::class, 'rejected_by'); }
    public function payer(): BelongsTo { return $this->belongsTo(User::class, 'paid_by'); }
    public function paidFromAccount(): BelongsTo { return $this->belongsTo(FinancialAccount::class, 'paid_from_account_id'); }
}
