<?php

namespace App\Models;

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

class PayrollSummary extends Model
{
    use HasFactory;

    protected $fillable = [
        'payroll_id',
        'reference_no',
        'payroll_date',
        'cut_off',
        'company_id',
        'dealership_id',
        'department_id',
        'employee_id',
        'salary_rate',
        'basic_pay',
        'cola',
        'leave_pay',
        'absent_amount',
        'late_amount',
        'tardiness_amount',
        'undertime_amount',
        'overtime_total',
        'night_diff_total',
        'holiday_total',
        'restday_total',
        'gross_pay',
        'gross_pay_for_sss',
        'sss_employee_share',
        'sss_employer_share',
        'philhealth_contribution',
        'pagibig_contribution',
        'pagibig_contribution_employer',
        'taxable_amount',
        'withholding_tax',
        'income_after_tax',
        'benefits_total',
        'adjustments_total',
        'loans_total',
        'payment_contributions_total',
        'other_deductions',
        'total_additions',
        'total_deductions',
        'details',
        'net_pay',

    ];

    // Set up event listener to encode 'details' before saving
    protected static function boot()
    {
        parent::boot();

        static::saving(function ($model) {
            if (is_array($model->details)) {
                $model->details = json_encode($model->details);
            }
        });
    }

    // Accessor to decode JSON when accessing 'details'
    public function getDetailsAttribute($value)
    {
        if(!is_array($value)) {
            return json_decode($value, true); // Decode as associative array
        } else {
            return $value;
        }
    }

    public function payroll()
    {
        return $this->belongsTo(Payroll::class, 'payroll_id', 'id');
    }

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

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

    public function dealership() {
        return $this->belongsTo(Dealership::class,'dealership_id');
    }
}
