<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class PayrollRun extends Model
{
    use HasFactory;

    protected $fillable = [
        'company_id',
        'payroll_period_id',
        'run_date',
        'status', // draft, processing, calculated, approved, paid, reversed
        'total_gross_salary',
        'approved_by',
        'approved_at',
        'reversed_by',
        'reversed_at',
        'notes',
        'created_by',
        'updated_by'
    ];

    protected $casts = [
        'run_date' => 'date',
        'approved_at' => 'datetime',
        'reversed_at' => 'datetime',
        'total_gross_salary' => 'decimal:2',
    ];

    /**
     * Relationships
     */

    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    public function payrollPeriod()
    {
        return $this->belongsTo(PayrollPeriod::class);
    }

    public function payrollEntries()
    {
        return $this->hasMany(PayrollEntry::class, 'payroll_run_id');
    }

    public function approvedBy()
    {
        return $this->belongsTo(User::class, 'approved_by');
    }

    public function reversedBy()
    {
        return $this->belongsTo(User::class, 'reversed_by');
    }

    public function createdBy()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function updatedBy()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    /**
     * Logic Helpers
     */

    public function canApprove()
    {
        return $this->status === 'calculated';
    }

    public function canReverse()
    {
        return in_array($this->status, ['approved', 'paid']);
    }
}