<?php

namespace App\Models;

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

class Investor extends Model
{
    use HasFactory, HasUuids;

    protected $fillable = [
        'email',
        'full_name',
        'phone',
        'country',
        'investor_type',
        'total_invested',
        'active_investments',
        'lifetime_returns',
        'kyc_status',
        'kyc_documents',
        'pep_status',
        'sanctions_checked',
        'risk_profile',
        'communication_preferences',
        'last_login',
        'dashboard_access',
    ];

    protected $casts = [
        'kyc_documents' => 'array',
        'communication_preferences' => 'array',
        'pep_status' => 'boolean',
        'sanctions_checked' => 'boolean',
        'dashboard_access' => 'boolean',
        'total_invested' => 'decimal:2',
        'lifetime_returns' => 'decimal:2',
        'last_login' => 'datetime',
    ];

    /**
     * Get all investments for this investor
     */
    public function investments(): HasMany
    {
        return $this->hasMany(Investment::class);
    }

    /**
     * Get all KYC documents for this investor
     */
    public function kycDocuments(): HasMany
    {
        return $this->hasMany(KycDocument::class);
    }

    /**
     * Get all dividend payments for this investor
     */
    public function dividendPayments(): HasMany
    {
        return $this->hasMany(DividendPayment::class);
    }

    /**
     * Check if KYC is approved
     */
    public function isKycApproved(): bool
    {
        return $this->kyc_status === 'approved';
    }

    /**
     * Update aggregate values from investments
     */
    public function updateAggregates(): void
    {
        $this->total_invested = $this->investments()
            ->where('payment_status', 'confirmed')
            ->sum('investment_amount');

        $this->active_investments = $this->investments()
            ->whereIn('status', ['payment_confirmed', 'agreement_pending', 'active'])
            ->count();

        $this->lifetime_returns = $this->dividendPayments()
            ->where('status', 'completed')
            ->sum('amount');

        $this->save();
    }

    /**
     * Get or create investor by email
     */
    public static function findOrCreateByEmail(string $email, array $attributes = []): self
    {
        return static::firstOrCreate(
            ['email' => strtolower($email)],
            array_merge(['full_name' => $attributes['full_name'] ?? 'Unknown'], $attributes)
        );
    }
}
