<?php

namespace App\Models;

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

class Employee extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'designation_id',
        'employee_code',
        'name',
        'phone',
        'email',
        'photo',
        'father_name',
        'mother_name',
        'nid_no',
        'present_address',
        'permanent_address',
        'joining_date',
        'employee_type',
        'overtime_eligible',
        'overtime_rate',
        'opening_balance',
        'status',
        'note',
    ];

    protected $casts = [
        'joining_date'      => 'date',
        'overtime_eligible' => 'boolean',
        'overtime_rate'     => 'decimal:2',
        'opening_balance'   => 'decimal:2',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function designation()
    {
        return $this->belongsTo(Designation::class);
    }

    public function salaryStructures()
    {
        return $this->hasMany(EmployeeSalaryStructure::class);
    }

    public function currentSalaryStructure()
    {
        return $this->hasOne(EmployeeSalaryStructure::class)->where('is_current', true);
    }

    public function salaryHistories()
    {
        return $this->hasMany(EmployeeSalaryHistory::class);
    }

    public function attendances()
    {
        return $this->hasMany(EmployeeAttendance::class);
    }

    public function payrollItems()
    {
        return $this->hasMany(PayrollItem::class);
    }

    public function advances()
    {
        return $this->hasMany(EmployeeAdvance::class);
    }

    public function payrollPayments()
    {
        return $this->hasMany(PayrollPayment::class);
    }

    public function ledgers()
    {
        return $this->hasMany(EmployeeLedger::class);
    }

    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    public function scopeMonthly($query)
    {
        return $query->where('employee_type', 'monthly');
    }

    public function scopeDailyRoz($query)
    {
        return $query->where('employee_type', 'daily_roz');
    }

    public function activeAdvances()
    {
        return $this->hasMany(EmployeeAdvance::class)
            ->whereIn('status', ['active', 'partial_adjusted']);
    }

    public function bonuses()
    {
        return $this->hasMany(EmployeeBonus::class);
    }
}
