<?php

namespace App\Models;

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

class Application extends Model
{
    use HasFactory;

    protected $table = 'applications';

    protected $fillable = [
        // Identification
        'application_number',
        'customer_id',
        'product_id',
        'branch_id',
        'company_id',
        
        // Loan Details
        'loan_amount',
        'loan_tenure',
        'loan_purpose',
        'interest_rate',
        'estimated_monthly_payment',
        'installment_amount', // Added this
        'payment_frequency',
        'source',

        // Bank Details (NEW)
        'bank_branch',
        'account_number',

        // Employment Details (NEW)
        'job_title',
        'employer_name',
        'employer_physical_address',
        'employer_postal_address',
        'employer_town_province',
        'gross_salary',
        'net_salary',
        'employment_type',
        'employment_years',
        'retirement_year',
        'employee_number',
        'contract_expiry_date',

        // Next of Kin Details (NEW)
        'kin_surname',
        'kin_first_name',
        'kin_physical_address',
        'kin_postal_address',
        'kin_town',
        'kin_province',
        'kin_country',
        'kin_telephone',
        'kin_email',
        'kin_relationship',

        // Status & Meta
        'status',
        'submitted_at',
        'reviewed_at',
        'approved_at',
        'disbursed_at',
        'rejection_reason',
        'admin_notes',
        'disbursement_notes',
        'created_by',
        'reviewed_by',
        'disbursed_by',
        'loan_id', // Links to DisbursedLoan if approved
    ];

    protected $casts = [
        'submitted_at' => 'datetime',
        'reviewed_at' => 'datetime',
        'approved_at' => 'datetime',
        'disbursed_at' => 'datetime',
        'contract_expiry_date' => 'date',
        'loan_amount' => 'decimal:2',
        'interest_rate' => 'decimal:2',
        'estimated_monthly_payment' => 'decimal:2',
        'gross_salary' => 'decimal:2',
        'net_salary' => 'decimal:2',
    ];

    // ================= RELATIONSHIPS =================

    public function customer()
    {
        return $this->belongsTo(Customer::class, 'customer_id');
    }

    public function product()
    {
        return $this->belongsTo(LoanType::class, 'product_id');
    }

    public function loan()
    {
        return $this->hasOne(DisbursedLoan::class, 'application_id');
    }

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

    public function reviewer()
    {
        return $this->belongsTo(User::class, 'reviewed_by');
    }
    
    public function documents(): HasMany
    {
        return $this->hasMany(LoanApplicationDocument::class, 'application_id');
    }
}