<?php

namespace App\Models;

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

class CreditDeductable extends Model
{
    use HasFactory;

    protected $table = 'credits_deductables';

    protected $primaryKey = 'id';
    
    public $incrementing = true;

    protected $fillable = [
        'client_id',
        'request_date',
        'requested_amount',
        'purpose',
        'status',
        'disbursement_date',
        'repayment_term',
        'interest_rate',
        'guarantee_type',
        'comments',
        'service_charges',
        'mandatory_savings',
        'total_deductions',
        'total_loan_cost',
        'total_repayable',
        'cash_to_client',
        'order_id',
        'seed_id',
        'createdby'
    ];

    protected $casts = [
        'request_date' => 'date',
        'disbursement_date' => 'date',
        'requested_amount' => 'decimal:2',
        'service_charges' => 'decimal:2',
        'mandatory_savings' => 'decimal:2',
        'total_deductions' => 'decimal:2',
        'total_loan_cost' => 'decimal:2',
        'total_repayable' => 'decimal:2',
        'cash_to_client' => 'decimal:2',
        'interest_rate' => 'decimal:2',
        'repayment_term' => 'integer',
        'order_id' => 'integer',
        'seed_id' => 'integer',
        'createdby' => 'integer',
    ];

    // Relations
    public function client()
    {
        return $this->belongsTo(Client::class, 'client_id');
    }

   public function seed()
{
    return $this->belongsTo(InputsActivitiesCostsNeeded::class, 'seed_id'); 
}

 

    public function creator()
    {
        return $this->belongsTo(User::class, 'createdby');
    }

    // Scopes
    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

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

    public function scopeByClient($query, $clientId)
    {
        return $query->where('client_id', $clientId);
    }

    public function scopeByClientAndSeed($query, $clientId, $seedId)
    {
        return $query->where('client_id', $clientId)->where('seed_id', $seedId);
    }

    public function scopeLatestFirst($query)
    {
        return $query->orderBy('created_at', 'desc');
    }
}