<?php

namespace App\Models;

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

class SalaryTemplate extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'school_id',
        'template_name',
        'description',
        'is_active',
    ];

    protected $casts = [
        'is_active' => 'boolean',
    ];

    // Relationships
    public function school()
    {
        return $this->belongsTo(School::class);
    }

    public function details()
    {
        return $this->hasMany(SalaryTemplateDetail::class, 'salary_template_id');
    }

    public function staffSalaryStructures()
    {
        return $this->hasMany(StaffSalaryStructure::class, 'salary_template_id');
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    // Accessors
    public function getTotalAllowancesAttribute()
    {
        return $this->details()
                    ->where('component_type', 'allowance')
                    ->sum('amount');
    }

    public function getTotalDeductionsAttribute()
    {
        return $this->details()
                    ->where('component_type', 'deduction')
                    ->sum('amount');
    }
}
