<?php

namespace App\Models;

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

class PayrollEntry extends Model
{
    use HasFactory;

    protected $fillable = [
        'payroll_run_id',
        'payroll_period_id',
        'company_id',
        'employee_id',
        'period_start_date',
        'period_end_date',
        'entry_date',
        'earning_type',
        'earning_amount',
        'subjecttopaye',
        'subjecttonapsa',
        'subjecttonhima',
        'calculated_by',
        'calculation_status',
        // NEW SUMMARY COLUMNS
        'gross_earnings',
        'totalpaye',
        'total_employee_napsa',
        'total_employer_napsa',
        'total_employee_nhima',
        'total_employer_nhima',
        'total_net_pay',
        'approved_by',
        'approved_at',
        'paid_by',
        'paid_at'
    ];

    protected $casts = [
        'period_start_date' => 'date',
        'period_end_date' => 'date',
        'entry_date' => 'date',
        'earning_amount' => 'decimal:2',
        'gross_earnings' => 'decimal:2',
        'totalpaye' => 'decimal:2',
        'total_employee_napsa' => 'decimal:2',
        'total_employer_napsa' => 'decimal:2',
        'total_employee_nhima' => 'decimal:2',
        'total_employer_nhima' => 'decimal:2',
        'total_net_pay' => 'decimal:2',
        'approved_at' => 'datetime',
        'paid_at' => 'datetime'
    ];

    // Relationships
    public function payrollPeriod()
    {
        return $this->belongsTo(PayrollPeriod::class, 'payroll_period_id');
    }

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

    public function employee()
    {
        return $this->belongsTo(Employee::class, 'employee_id');
    }

    public function payrollRun()
    {
        return $this->belongsTo(PayrollRun::class, 'payroll_run_id');
    }

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

    // Helper methods for your Zambia-specific UI
    public function isTaxable()
    {
        return $this->subjecttopaye === 'Yes';
    }

    public function isNapsaApplicable()
    {
        return $this->subjecttonapsa === 'Yes';
    }
}