<?php

namespace Modules\Payroll\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Modules\Employee\Models\Traits\HasEmployee;

// use Modules\Payroll\Database\Factories\EmployeeLoanFactory;

class EmployeeLoan extends Model
{
    use HasFactory, HasEmployee;

    /**
     * The attributes that are mass assignable.
     */
    protected $fillable = [
        'employee_id',
        'loan_no',
        'loan_type',
        'principal_amount',
        'interest_rate',
        'installment_months',
        'interest_amount',
        'total_payable',
        'remaining_amount',
        'monthly_installment',
        'paid_installments',
        'issue_date',
        'start_deduction_date',
        'status',
        'remarks',
        'approved_by',
        'approved_at',
    ];


    public function scopeSearch($query, ?string $search)
    {
        if (blank($search)) {
            return $query;
        }

        $search = '%' . trim($search) . '%';

        return $query->when($search, function ($q, $search) {

            $q->where(function ($q) use ($search) {
                $q->where('loan_no', 'LIKE', $search)
                    ->orWhere('loan_type', 'LIKE', $search)
                    ->orWhereHas('employee', function ($q) use ($search) {
                        $q->where('name', 'LIKE', $search)
                            ->orWhere('emp_number', 'LIKE', $search);
                    });
            });
        });
    }

    public function scopeFilterByStatus($query, ?string $status)
    {
        return $query->when($status, fn($q, $status) => $q->where('status', $status));
    }

    public function scopeDateRange($query, ?string $from, ?string $to)
    {
        return $query->when($from, fn($q, $from) => $q->whereDate('issue_date', '>=', $from))->when($to, fn($q, $to) => $q->whereDate('issue_date', '<=', $to));
    }


    // protected static function newFactory(): EmployeeLoanFactory
    // {
    //     // return EmployeeLoanFactory::new();
    // }
}
