<?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\EmployeeAdvanceFactory;

class EmployeeAdvance extends Model
{
    use HasFactory, HasEmployee;

    /**
     * The attributes that are mass assignable.
     */
    protected $fillable = [
        'employee_id',
        'voucher_id',
        'advance_no',
        'advance_amount',
        'remaining_amount',
        'installment_months',
        'monthly_deduction',
        'paid_installments',
        'issue_date',
        'start_deduction_date',
        'approved_by',
        'approved_at',
        'remarks',
        'status',
    ];


    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('advance_no', '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(): EmployeeAdvanceFactory
    // {
    //     // return EmployeeAdvanceFactory::new();
    // }
}
