<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Installment extends Model
{
    protected $fillable = [
        'order_id',
        'customer_cnic',
        'customer_address',
        'customer_contact',
        'guarantor_name',
        'guarantor_cnic',
        'guarantor_contact',
        'guarantor_address',
        'guarantor_relation',
        'total_amount',
        'down_payment',
        'financed_amount',
        'markup_percentage',
        'markup_amount',
        'total_payable',
        'number_of_installments',
        'installment_amount',
        'installment_frequency',
        'start_date',
        'end_date',
        'status',
        'contract_generated_at',
        'contract_path',
        'terms_and_conditions',
        'notes',
    ];

    protected $casts = [
        'start_date' => 'date',
        'end_date' => 'date',
        'contract_generated_at' => 'datetime',
        'total_amount' => 'decimal:2',
        'down_payment' => 'decimal:2',
        'financed_amount' => 'decimal:2',
        'markup_percentage' => 'decimal:2',
        'markup_amount' => 'decimal:2',
        'total_payable' => 'decimal:2',
        'installment_amount' => 'decimal:2',
    ];

    public function order()
    {
        return $this->belongsTo(Order::class);
    }

    public function documents()
    {
        return $this->hasMany(InstallmentDocument::class);
    }

    public function payments()
    {
        return $this->hasMany(InstallmentPayment::class)->orderBy('installment_number');
    }

    public function pendingPayments()
    {
        return $this->hasMany(InstallmentPayment::class)
            ->where('status', 'pending')
            ->orderBy('due_date');
    }

    public function overduePayments()
    {
        return $this->hasMany(InstallmentPayment::class)
            ->where('status', 'overdue')
            ->orderBy('due_date');
    }

    // Helper method to check if installment is completed
    public function isCompleted(): bool
    {
        return $this->payments()->where('status', 'paid')->count() === $this->number_of_installments;
    }

    // Helper method to get total paid amount
    public function getTotalPaidAmount(): float
    {
        return $this->payments()->sum('amount_paid') + $this->down_payment;
    }

    // Helper method to get remaining balance
    public function getRemainingBalance(): float
    {
        return $this->total_payable - $this->getTotalPaidAmount() + $this->down_payment;
    }
}