<?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\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

class Investment extends Model
{
    use HasFactory, HasUuids;

    protected $fillable = [
        'reference',
        'investor_id',
        'investor_name',
        'email',
        'phone',
        'country',
        'investor_type',
        'investment_tier',
        'investment_amount',
        'shares',
        'share_price',
        'currency',
        'investment_term',
        'payment_status',
        'payment_reference',
        'payment_method',
        'terms_accepted',
        'memorandum_read',
        'risks_understood',
        'risk_tolerance_confirmed',
        'newsletter_subscribed',
        'call_requested',
        'payment_completed_at',
        'agreement_sent_at',
        'agreement_signed_at',
        'status',
        'notes',
        'ip_address',
        'user_agent',
        'agreement_document_url',
    ];

    protected $casts = [
        'investment_amount' => 'decimal:2',
        'shares' => 'integer',
        'share_price' => 'decimal:2',
        'terms_accepted' => 'boolean',
        'memorandum_read' => 'boolean',
        'risks_understood' => 'boolean',
        'risk_tolerance_confirmed' => 'boolean',
        'newsletter_subscribed' => 'boolean',
        'call_requested' => 'boolean',
        'payment_completed_at' => 'datetime',
        'agreement_sent_at' => 'datetime',
        'agreement_signed_at' => 'datetime',
    ];

    /**
     * Tier minimums in USD
     */
    /**
     * Tier minimums in USD
     */
    public const TIER_MINIMUMS = [
        'growth' => 100,
        'strategic' => 1000,
        'anchor' => 5000,
    ];

    /**
     * Tier minimums in KES
     */
    public const TIER_MINIMUMS_KES = [
        'growth' => 13000,
        'strategic' => 130000,
        'anchor' => 650000,
    ];

    /**
     * Expected ROI percentages by tier
     */
    public const TIER_ROI = [
        'growth' => 15,
        'strategic' => 18,
        'anchor' => 22,
    ];

    /**
     * Get the investor that owns this investment
     */
    public function investor(): BelongsTo
    {
        return $this->belongsTo(Investor::class);
    }

    /**
     * Get all payment transactions for this investment
     */
    public function paymentTransactions(): HasMany
    {
        return $this->hasMany(PaymentTransaction::class);
    }

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

    /**
     * Get email logs for this investment
     */
    public function emailLogs(): HasMany
    {
        return $this->hasMany(EmailLog::class);
    }

    /**
     * Generate a unique investment reference
     */
    public static function generateReference(): string
    {
        do {
            $reference = 'MSL-INV-' . date('Ymd') . '-' . strtoupper(Str::random(8));
        } while (static::where('reference', $reference)->exists());

        return $reference;
    }

    /**
     * Get the minimum amount for the investment tier
     */
    public function getTierMinimum(): float
    {
        return self::TIER_MINIMUMS[$this->investment_tier] ?? 0;
    }

    /**
     * Get expected ROI percentage
     */
    public function getExpectedRoi(): float
    {
        return self::TIER_ROI[$this->investment_tier] ?? 0;
    }

    /**
     * Calculate expected returns based on tier and term
     */
    public function calculateExpectedReturns(): float
    {
        $roiPercentage = $this->getExpectedRoi();
        $years = $this->investment_term ?? 1;
        
        return $this->investment_amount * ($roiPercentage / 100) * $years;
    }

    /**
     * Check if all compliance checkboxes are checked
     */
    public function isComplianceComplete(): bool
    {
        return $this->terms_accepted
            && $this->memorandum_read
            && $this->risks_understood
            && $this->risk_tolerance_confirmed;
    }

    /**
     * Scope for pending payments
     */
    public function scopePendingPayment($query)
    {
        return $query->where('status', 'pending_payment');
    }

    /**
     * Scope for active investments
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * Scope for confirmed payments
     */
    public function scopePaymentConfirmed($query)
    {
        return $query->where('payment_status', 'confirmed');
    }
}
