<?php

namespace App\Models;

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

class StaffSalaryStructure extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'staff_id',
        'salary_template_id',
        'basic_salary',
        'gross_salary',
        'net_salary',
        'total_allowances',
        'total_deductions',
        'effective_from',
        'effective_to',
        'is_active',
        'remarks',
    ];

    protected $casts = [
        'basic_salary' => 'decimal:2',
        'gross_salary' => 'decimal:2',
        'net_salary' => 'decimal:2',
        'total_allowances' => 'decimal:2',
        'total_deductions' => 'decimal:2',
        'effective_from' => 'date',
        'effective_to' => 'date',
        'is_active' => 'boolean',
    ];

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

    public function salaryTemplate()
    {
        return $this->belongsTo(SalaryTemplate::class);
    }

    public function allowances()
    {
        return $this->belongsToMany(SalaryHead::class, 'staff_salary_components')
                    ->wherePivot('component_type', 'allowance')
                    ->withPivot('amount', 'is_percentage', 'percentage_value')
                    ->withTimestamps();
    }

    public function deductions()
    {
        return $this->belongsToMany(SalaryHead::class, 'staff_salary_components')
                    ->wherePivot('component_type', 'deduction')
                    ->withPivot('amount', 'is_percentage', 'percentage_value')
                    ->withTimestamps();
    }

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

    public function scopeForStaff($query, $staffId)
    {
        return $query->where('staff_id', $staffId);
    }

    public function scopeEffectiveOn($query, $date)
    {
        return $query->where('effective_from', '<=', $date)
                     ->where(function($q) use ($date) {
                         $q->whereNull('effective_to')
                           ->orWhere('effective_to', '>=', $date);
                     });
    }

    // Accessors
    public function getAnnualSalaryAttribute()
    {
        return $this->gross_salary * 12;
    }
}
