<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Storage;

class Customer extends Authenticatable
{
    use HasFactory, Notifiable;

    protected $table = 'customer';
    
    protected $primaryKey = 'id';
    
    public $incrementing = true;
    
    protected $keyType = 'int';

    /**
     * The attributes that are mass assignable.
     */
    protected $fillable = [
        // System Fields
        'customer_number',
        
        // Personal Information
        'title',
        'surname',
        'first_name',
        'middle_name',
        'customer',
        'dob',
        
        // Contact Information
        'email',
        'phone',
        'office_phone',
        
        // Address Information
        'town',
        'address',
        'province',
        
        // Professional Information
        'occupation',
        'income',
        'bname',
        'company',
        'bstartdate',
        
        // Identification
        'cgroup',
        'idtype',
        'number',
        'incorporationid',
        'tpin',
        
        // Documents
        'docpath',
        'nrc_front_path',
        'nrc_back_path',
        
        // Status & Verification
        'status',
        'verification_status',
        
        // API Authentication
        'api_key',
        'api_key_expires_at',
        
        // System Fields
        'postdate',
        'pass',
        'userid',
        'branchid',
        'companyid',
        'created_at',
        'updated_at'
    ];

    /**
     * The attributes that should be hidden for arrays.
     */
    protected $hidden = [
        'pass',
        'api_key',
    ];

    /**
     * The attributes that should be cast.
     */
    protected $casts = [
        // Financial
        'income' => 'decimal:2',
        
        // Dates
        'postdate' => 'datetime',
        'bstartdate' => 'date',
        'dob' => 'date',
        'api_key_expires_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        
        // Numeric IDs
        'incorporationid' => 'integer',
        'tpin' => 'integer',
        'userid' => 'integer',
        'branchid' => 'integer',
        'companyid' => 'integer',
        
        // Verification
        'verification_status' => 'string',
    ];

    /**
     * MODEL EVENTS
     */

    /**
     * Boot method for generating customer number and initializing credit score
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($customer) {
            if (empty($customer->customer_number)) {
                $customer->customer_number = static::generateCustomerNumber();
            }
        });

        static::created(function ($customer) {
            // Initialize credit score record for new customer
            try {
                app(\App\Services\CreditScoreService::class)->initializeCreditScore($customer->id);
            } catch (\Exception $e) {
                \Log::error('Failed to auto-initialize credit score for new customer', [
                    'customer_id' => $customer->id,
                    'error' => $e->getMessage()
                ]);
            }
        });
    }

    /**
     * Generate unique customer number in format CU00000001
     */
    public static function generateCustomerNumber()
    {
        // Get the last customer number from the database
        $lastCustomer = static::orderBy('id', 'desc')->first();
        
        if ($lastCustomer && $lastCustomer->customer_number) {
            // Extract the numeric part and increment
            $lastNumber = (int) substr($lastCustomer->customer_number, 2);
            $newNumber = $lastNumber + 1;
        } else {
            // Start from 1 if no customers exist
            $newNumber = 1;
        }
        
        // Format the number with leading zeros and prefix
        $customerNumber = 'CU' . str_pad($newNumber, 8, '0', STR_PAD_LEFT);
        
        return $customerNumber;
    }

    /**
     * RELATIONSHIPS
     */

    /**
     * Get the applications for the customer.
     */
    public function applications()
    {
        return $this->hasMany(Application::class, 'customer_id');
    }

    /**
     * Get the loans for the customer from loanform table.
     */
    public function loans()
    {
        return $this->hasMany(Loan::class, 'customerid', 'id');
    }

    /**
     * Get the disbursed loans for the customer from disbursedloans table.
     */
    public function disbursedLoans()
    {
        return $this->hasMany(DisbursedLoan::class, 'customerid', 'id');
    }

    /**
     * Get all credit score records for this customer
     */
    public function creditScores()
    {
        return $this->hasMany(CustomerCreditScore::class, 'customer_id');
    }

    /**
     * Get the current/latest credit score for this customer
     */
    public function currentCreditScore()
    {
        return $this->hasOne(CustomerCreditScore::class, 'customer_id')
            ->where('is_current', true);
    }

    /**
     * Get historical credit scores (obsolete records)
     */
    public function creditScoreHistory()
    {
        return $this->hasMany(CustomerCreditScore::class, 'customer_id')
            ->where('is_current', false)
            ->orderBy('score_date', 'desc');
    }

    /**
     * Get active loans (loans with status 'active') from disbursedloans table
     */
    public function activeDisbursedLoans()
    {
        return $this->disbursedLoans()->where('status', 'active');
    }

    /**
     * Get active loans from loanform table (for backward compatibility)
     */
    public function activeLoans()
    {
        return $this->loans()->where('status', 'active');
    }

    /**
     * Get disbursed loans from loanform table
     */
    public function disbursedLoansOld()
    {
        return $this->loans()->whereNotNull('disburseddate');
    }

    /**
     * Get the customer's submitted applications.
     */
    public function submittedApplications()
    {
        return $this->applications()->where('status', 'submitted');
    }

    /**
     * Get the customer's approved applications.
     */
    public function approvedApplications()
    {
        return $this->applications()->where('status', 'approved');
    }

    /**
     * Get the customer's rejected applications.
     */
    public function rejectedApplications()
    {
        return $this->applications()->where('status', 'rejected');
    }

    /**
     * Get the customer's pending applications (draft or submitted).
     */
    public function pendingApplications()
    {
        return $this->applications()->whereIn('status', ['draft', 'submitted', 'under_review']);
    }

    /**
     * Get the customer's disbursed applications.
     */
    public function disbursedApplications()
    {
        return $this->applications()->where('status', 'disbursed');
    }

    /**
     * Get the customer's active loan applications (not draft or rejected).
     */
    public function activeApplications()
    {
        return $this->applications()->whereNotIn('status', ['draft', 'rejected']);
    }

    /**
     * Get the customer's latest application.
     */
    public function latestApplication()
    {
        return $this->hasOne(Application::class, 'customer_id')->latest();
    }

    /**
     * Get all repayments for this customer
     */
    public function repayments()
    {
        return $this->hasMany(Repayment::class, 'customerid', 'id');
    }

    /**
     * Get all interest income records for this customer
     */
    public function interestIncome()
    {
        return $this->hasMany(InterestIncome::class, 'customerid', 'id');
    }

    /**
     * CREDIT SCORE RELATED METHODS - UPDATED FOR "NO INITIAL SCORE" APPROACH
     */

    /**
     * Get current credit score value (convenience accessor) - UPDATED
     */
    public function getCurrentCreditScoreAttribute()
    {
        $currentScore = $this->currentCreditScore;
        
        if (!$currentScore || $currentScore->credit_score === null) {
            return null; // Explicitly return null for no score
        }
        
        return $currentScore->credit_score;
    }

    /**
     * Get current score band (convenience accessor) - UPDATED
     */
    public function getCurrentScoreBandAttribute()
    {
        $currentScore = $this->currentCreditScore;
        
        if (!$currentScore || $currentScore->credit_score === null) {
            return 'No History';
        }
        
        return $currentScore->score_band;
    }

    /**
     * Get current credit score change (convenience accessor)
     */
    public function getCreditScoreChangeAttribute()
    {
        return $this->currentCreditScore ? $this->currentCreditScore->score_change : 0;
    }

    /**
     * Get current credit utilization ratio
     */
    public function getCurrentCreditUtilizationAttribute()
    {
        return $this->currentCreditScore ? $this->currentCreditScore->credit_utilization_ratio : 0;
    }

    /**
     * Get current on-time repayment rate
     */
    public function getCurrentRepaymentRateAttribute()
    {
        return $this->currentCreditScore ? $this->currentCreditScore->on_time_repayment_rate : 0;
    }

    /**
     * Check if customer has credit history - NEW METHOD
     */
    public function getHasCreditHistoryAttribute()
    {
        $currentScore = $this->currentCreditScore;
        return $currentScore && $currentScore->credit_score !== null;
    }

    /**
     * Check if customer has no credit history - NEW METHOD
     */
    public function getHasNoCreditHistoryAttribute()
    {
        $currentScore = $this->currentCreditScore;
        return !$currentScore || $currentScore->credit_score === null;
    }

    /**
     * Check if customer has good credit score (above 600) - UPDATED
     */
    public function getHasGoodCreditAttribute()
    {
        return $this->current_credit_score !== null && $this->current_credit_score >= 600;
    }

    /**
     * Check if customer has poor credit score (below 500) - UPDATED
     */
    public function getHasPoorCreditAttribute()
    {
        return $this->current_credit_score !== null && $this->current_credit_score < 500;
    }

    /**
     * Check if customer needs credit attention (defaults, high utilization, etc.) - UPDATED
     */
    public function getNeedsCreditAttentionAttribute()
    {
        if (!$this->currentCreditScore || $this->currentCreditScore->credit_score === null) {
            return false; // No history = no attention needed yet
        }

        return $this->currentCreditScore->credit_score < 500 || 
               $this->currentCreditScore->has_active_default || 
               $this->currentCreditScore->has_recent_late_payment ||
               $this->currentCreditScore->credit_utilization_ratio > 80;
    }

    /**
     * Get credit score trend (improving, declining, stable) - UPDATED
     */
    public function getCreditScoreTrendAttribute()
    {
        if (!$this->currentCreditScore || $this->currentCreditScore->credit_score === null) {
            return 'no_history';
        }

        $change = $this->currentCreditScore->score_change;
        
        if ($change > 0) return 'improving';
        if ($change < 0) return 'declining';
        return 'stable';
    }

    /**
     * Get recommended maximum loan amount based on credit score - UPDATED
     */
    public function getRecommendedMaxLoanAmountAttribute()
    {
        $creditLimit = $this->credit_limit ?? ($this->income * 3); // Default 3x monthly income
        
        if (!$this->currentCreditScore || $this->currentCreditScore->credit_score === null) {
            return $creditLimit * 0.3; // Conservative for no history
        }

        $score = $this->current_credit_score;
        
        return match(true) {
            $score >= 700 => $creditLimit * 0.8, // 80% for excellent
            $score >= 600 => $creditLimit * 0.6, // 60% for good
            $score >= 500 => $creditLimit * 0.4, // 40% for fair
            $score >= 400 => $creditLimit * 0.2, // 20% for poor
            default => $creditLimit * 0.1 // 10% for very poor
        };
    }

    /**
     * Check if customer qualifies for specific loan tier - UPDATED
     */
    public function qualifiesForLoanTier($tierName)
    {
        if (!$this->currentCreditScore || $this->currentCreditScore->credit_score === null) {
            return $tierName === 'No History'; // Only qualifies for "No History" tier
        }

        $score = $this->current_credit_score;
        
        return match($tierName) {
            'Excellent' => $score >= 700,
            'Good' => $score >= 600,
            'Fair' => $score >= 500,
            'Poor' => $score >= 400,
            'Very Poor' => $score < 400,
            'No History' => false, // Has history, doesn't qualify for no history tier
            default => false
        };
    }

    /**
     * Get credit score factors breakdown - UPDATED
     */
    public function getCreditScoreFactorsAttribute()
    {
        if (!$this->currentCreditScore || $this->currentCreditScore->credit_score === null) {
            return ['Limited Credit History'];
        }

        $factors = [];
        $score = $this->currentCreditScore;

        if ($score->on_time_repayment_rate >= 95) {
            $factors[] = 'Excellent Payment History';
        } elseif ($score->on_time_repayment_rate < 80) {
            $factors[] = 'Late Payments';
        }

        if ($score->credit_utilization_ratio <= 30) {
            $factors[] = 'Low Credit Utilization';
        } elseif ($score->credit_utilization_ratio > 75) {
            $factors[] = 'High Credit Utilization';
        }

        if ($score->has_active_default) {
            $factors[] = 'Active Default';
        }

        if ($score->has_recent_late_payment) {
            $factors[] = 'Recent Late Payment';
        }

        if (empty($factors)) {
            $factors[] = 'Standard Credit Profile';
        }

        return $factors;
    }

    /**
     * Get credit improvement recommendations - UPDATED
     */
    public function getCreditImprovementRecommendationsAttribute()
    {
        if (!$this->currentCreditScore || $this->currentCreditScore->credit_score === null) {
            return ['Build credit history with small, well-managed loans'];
        }

        $recommendations = [];
        $score = $this->currentCreditScore;

        if ($score->on_time_repayment_rate < 95) {
            $recommendations[] = 'Make all future payments on time';
        }

        if ($score->credit_utilization_ratio > 50) {
            $recommendations[] = 'Reduce credit utilization below 50%';
        }

        if ($score->has_active_default) {
            $recommendations[] = 'Resolve any outstanding defaults';
        }

        if ($score->late_payments_count > 0) {
            $recommendations[] = 'Avoid late payments for 6 months';
        }

        if (empty($recommendations)) {
            $recommendations[] = 'Maintain current good financial habits';
        }

        return $recommendations;
    }

    /**
     * BUSINESS LOGIC METHODS
     */

    /**
     * Get the authentication password for the user.
     */
    public function getAuthPassword()
    {
        return $this->pass;
    }

    /**
     * Route notifications for the mail channel.
     */
    public function routeNotificationForMail($notification = null)
    {
        return $this->email;
    }

    /**
     * Update verification status
     */
    public function markAsVerified()
    {
        $this->update(['verification_status' => 'verified']);
        return $this;
    }

    /**
     * Mark verification as failed
     */
    public function markAsVerificationFailed()
    {
        $this->update(['verification_status' => 'failed']);
        return $this;
    }

    /**
     * Mark verification as skipped
     */
    public function markAsVerificationSkipped()
    {
        $this->update(['verification_status' => 'skipped']);
        return $this;
    }

    /**
     * Check if customer can apply for loan
     */
    public function canApplyForLoan()
    {
        return $this->status === 'Active' && 
               $this->hasProfilePicture &&
               $this->email &&
               $this->phone &&
               $this->isVerified; // Only verified customers can apply
    }

    /**
     * Check if customer can apply for loan considering credit score - UPDATED
     */
    public function canApplyForLoanWithCreditCheck()
    {
        $basicEligibility = $this->canApplyForLoan();
        
        if (!$basicEligibility) {
            return false;
        }

        // Customers with no credit history can apply (they need to build history)
        if ($this->has_no_credit_history) {
            return true;
        }

        // Additional credit-based restrictions for customers with history
        if ($this->has_poor_credit && $this->activeDisbursedLoans()->count() >= 1) {
            return false; // Limit poor credit customers to one active loan
        }

        if ($this->needs_credit_attention) {
            return false; // Block applications if serious credit issues
        }

        return true;
    }

    /**
     * Get customer's application statistics
     */
    public function getApplicationStats()
    {
        return [
            'total' => $this->applications()->count(),
            'submitted' => $this->submittedApplications()->count(),
            'approved' => $this->approvedApplications()->count(),
            'rejected' => $this->rejectedApplications()->count(),
            'pending' => $this->pendingApplications()->count(),
        ];
    }

    /**
     * Check if customer has reached application limit (e.g., 3 pending applications)
     */
    public function hasReachedApplicationLimit()
    {
        return $this->pendingApplications()->count() >= 3;
    }

    /**
     * Get total next due amount across all active loans
     */
    public function getTotalNextDueAmountAttribute()
    {
        return $this->activeDisbursedLoans->sum('next_due_amount');
    }

    /**
     * Get total overdue amount across all active loans
     */
    public function getTotalOverdueAmountAttribute()
    {
        return $this->activeDisbursedLoans->sum('overdue_amount');
    }

    /**
     * Get total due balance (overdue + next due) across all active loans
     */
    public function getTotalDueBalanceAttribute()
    {
        return $this->activeDisbursedLoans->sum('total_due_balance');
    }

    /**
     * Get enhanced loan statistics using disbursedloans table with due amounts
     */
    public function getLoanStats()
    {
        // Get active loans from disbursedloans table
        $activeLoans = $this->activeDisbursedLoans()->get();
        $totalActiveLoanAmount = $activeLoans->sum('amount');
        $totalActiveLoansCount = $activeLoans->count();
        
        // Calculate actual collection progress based on repayments from disbursedloans table
        $totalExpectedRepayment = 0;
        $totalActualRepayment = 0;
        
        foreach ($activeLoans as $loan) {
            $totalExpectedRepayment += $loan->getTotalRepaymentAttribute();
            $totalActualRepayment += $loan->getTotalRepaidAttribute();
        }
        
        $averageProgress = $totalExpectedRepayment > 0 
            ? round(($totalActualRepayment / $totalExpectedRepayment) * 100, 2)
            : 0;

        // Calculate overdue loans
        $overdueLoans = $activeLoans->filter(function($loan) {
            return $loan->is_overdue;
        });

        return [
            'active_loans_count' => $totalActiveLoansCount,
            'total_active_loan_amount' => $totalActiveLoanAmount,
            'average_collection_progress' => $averageProgress,
            'total_expected_repayment' => $totalExpectedRepayment,
            'total_actual_repayment' => $totalActualRepayment,
            'total_outstanding_balance' => $totalExpectedRepayment - $totalActualRepayment,
            'overdue_loans_count' => $overdueLoans->count(),
            'active_loans' => $activeLoans,
            'total_next_due_amount' => $this->total_next_due_amount,
            'total_overdue_amount' => $this->total_overdue_amount,
            'total_due_balance' => $this->total_due_balance,
        ];
    }

    /**
     * Get comprehensive customer financial overview including credit score - UPDATED
     */
    public function getFinancialOverview()
    {
        $loanStats = $this->getLoanStats();
        
        $creditOverview = [
            'has_history' => $this->has_credit_history,
            'score_band' => $this->current_score_band,
            'trend' => $this->credit_score_trend,
        ];

        // Only include numerical score if customer has credit history
        if ($this->has_credit_history) {
            $creditOverview['current_score'] = $this->current_credit_score;
            $creditOverview['score_change'] = $this->credit_score_change;
            $creditOverview['utilization'] = $this->current_credit_utilization;
            $creditOverview['repayment_rate'] = $this->current_repayment_rate;
            $creditOverview['factors'] = $this->credit_score_factors;
            $creditOverview['recommendations'] = $this->credit_improvement_recommendations;
        } else {
            $creditOverview['message'] = 'No credit history available';
            $creditOverview['recommendations'] = ['Build credit history with your first loan'];
        }

        return [
            'credit_score' => $creditOverview,
            'loan_portfolio' => $loanStats,
            'credit_health' => [
                'has_credit_history' => $this->has_credit_history,
                'has_good_credit' => $this->has_good_credit,
                'needs_attention' => $this->needs_credit_attention,
                'qualifies_for_premium' => $this->qualifiesForLoanTier('Good'),
                'recommended_max_loan' => $this->recommended_max_loan_amount,
            ],
            'overall_risk' => $this->calculateOverallRiskLevel(),
        ];
    }

    /**
     * Calculate overall risk level based on multiple factors - UPDATED
     */
    public function calculateOverallRiskLevel()
    {
        // No credit history = Moderate Risk (not penalized)
        if (!$this->currentCreditScore || $this->currentCreditScore->credit_score === null) {
            return 'Moderate Risk';
        }

        $riskScore = 0;

        // Credit score contribution (40%)
        $creditScoreRisk = match(true) {
            $this->current_credit_score >= 700 => 0.1,
            $this->current_credit_score >= 600 => 0.3,
            $this->current_credit_score >= 500 => 0.6,
            $this->current_credit_score >= 400 => 0.8,
            default => 1.0
        };
        $riskScore += $creditScoreRisk * 0.4;

        // Payment history contribution (30%)
        $repaymentRisk = match(true) {
            $this->current_repayment_rate >= 98 => 0.1,
            $this->current_repayment_rate >= 95 => 0.3,
            $this->current_repayment_rate >= 90 => 0.6,
            $this->current_repayment_rate >= 80 => 0.8,
            default => 1.0
        };
        $riskScore += $repaymentRisk * 0.3;

        // Credit utilization contribution (20%)
        $utilizationRisk = match(true) {
            $this->current_credit_utilization <= 30 => 0.1,
            $this->current_credit_utilization <= 50 => 0.3,
            $this->current_credit_utilization <= 75 => 0.6,
            $this->current_credit_utilization <= 90 => 0.8,
            default => 1.0
        };
        $riskScore += $utilizationRisk * 0.2;

        // Loan portfolio contribution (10%)
        $portfolioRisk = match(true) {
            $this->activeDisbursedLoans()->count() === 0 => 0.1,
            $this->activeDisbursedLoans()->count() === 1 => 0.3,
            $this->activeDisbursedLoans()->count() <= 3 => 0.6,
            default => 0.8
        };
        $riskScore += $portfolioRisk * 0.1;

        return match(true) {
            $riskScore <= 0.3 => 'Low Risk',
            $riskScore <= 0.6 => 'Moderate Risk',
            $riskScore <= 0.8 => 'High Risk',
            default => 'Very High Risk'
        };
    }

    /**
     * Check if customer has any active loans from disbursedloans table
     */
    public function hasActiveLoans()
    {
        return $this->activeDisbursedLoans()->exists();
    }

    /**
     * Get next payment due date across all loans from disbursedloans table
     */
    public function getNextPaymentDueDate()
    {
        $nextPayment = $this->activeDisbursedLoans()
            ->get()
            ->map(function($loan) {
                return $loan->next_payment_due_date;
            })
            ->filter()
            ->sort()
            ->first();

        return $nextPayment;
    }

    /**
     * Get total overdue amount from disbursedloans table
     */
    public function getTotalOverdueAmountOld()
    {
        return $this->activeDisbursedLoans()
            ->get()
            ->filter(function($loan) {
                return $loan->is_overdue;
            })
            ->sum('totalbalance');
    }

    /**
     * API AUTHENTICATION METHODS
     */

    public function generateApiKey(): string
    {
        // Generate a secure random API key
        $apiKey = bin2hex(random_bytes(32));
        
        // Store hashed version in database
        $this->api_key = hash('sha256', $apiKey);
        $this->api_key_expires_at = now()->addDays(30); // 30 days expiry
        $this->save();
        
        return $apiKey;
    }

    public function validateApiKey($apiKey): bool
    {
        if (!$this->api_key || !$this->api_key_expires_at) {
            return false;
        }
        
        return hash_equals($this->api_key, hash('sha256', $apiKey)) && 
               $this->api_key_expires_at->isFuture();
    }

    public function revokeApiKey(): void
    {
        $this->api_key = null;
        $this->api_key_expires_at = null;
        $this->save();
    }

    /**
     * ACCESSORS
     */

    /**
     * Check if customer has profile picture
     */
    public function getHasProfilePictureAttribute()
    {
        return $this->docpath && Storage::disk('public')->exists($this->docpath);
    }

    /**
     * Get profile picture URL
     */
    public function getProfilePictureUrlAttribute()
    {
        return $this->has_profile_picture 
            ? asset('storage/' . $this->docpath) 
            : 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?auto=format&fit=crop&w=500&q=60';
    }

    /**
     * Check if customer is verified
     */
    public function getIsVerifiedAttribute()
    {
        return $this->verification_status === 'verified';
    }

    /**
     * Get customer's age
     */
    public function getAgeAttribute()
    {
        return $this->dob ? \Carbon\Carbon::parse($this->dob)->age : null;
    }

    /**
     * Get customer's full name
     */
    public function getFullNameAttribute()
    {
        return $this->customer;
    }

    /**
     * Get customer's verification status badge color
     */
    public function getVerificationStatusColorAttribute()
    {
        return match($this->verification_status) {
            'verified' => 'green',
            'failed' => 'red',
            'skipped' => 'orange',
            default => 'gray'
        };
    }

    /**
     * Get customer's status badge color
     */
    public function getStatusColorAttribute()
    {
        return match($this->status) {
            'Active' => 'green',
            'Inactive' => 'red',
            'Suspended' => 'orange',
            'Pending' => 'yellow',
            default => 'gray'
        };
    }

    /**
     * Get customer's credit score badge color - UPDATED
     */
    public function getCreditScoreColorAttribute()
    {
        return match($this->current_score_band) {
            'Excellent' => 'green',
            'Good' => 'blue',
            'Fair' => 'yellow',
            'Poor' => 'orange',
            'Very Poor' => 'red',
            'No History' => 'gray',
            default => 'gray'
        };
    }

    /**
     * Get customer's complete address
     */
    public function getCompleteAddressAttribute()
    {
        $addressParts = array_filter([
            $this->address,
            $this->town,
            $this->province
        ]);
        
        return implode(', ', $addressParts);
    }

    /**
     * Get customer's employment info
     */
    public function getEmploymentInfoAttribute()
    {
        $employmentParts = array_filter([
            $this->occupation,
            $this->company
        ]);
        
        return implode(' at ', $employmentParts) ?: 'Not specified';
    }

    /**
     * Get customer's credit limit based on income
     */
    public function getCreditLimitAttribute()
    {
        return $this->income * 3; // 3x monthly income as credit limit
    }
}