<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use App\Models\UserVipInvestment;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\Transaction;
use Illuminate\Support\Facades\DB;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable,SoftDeletes;

    protected $fillable = [
        'name',
        'email',
        'password',
        'phone',
        'image',
        'status',
        'balance',
        'referral_code',
        'referred_by',
        'wallet_info'
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'wallet_info' => 'array',
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
         'balance' => 'integer',
    ];

    // Add this relationship
    public function transactions()
    {
        return $this->hasMany(Transaction::class);
    }

    public function vipInvestments()
    {
        return $this->hasMany(UserVipInvestment::class);
    }

    public function activeVipInvestments()
    {
        return $this->vipInvestments()->where('expires_at', '>', now());
    }

    // public function hasActiveInvestment($productId = null)
    // {
    //     $query = $this->vipInvestments()
    //         ->where('expires_at', '>', now());
            
    //     if ($productId) {
    //         $query->where('vip_product_id', $productId);
    //     }
            
    //     return $query->exists();
    // }
    
    

public function hasActiveInvestmentIn($productId)
{
    // শুধুমাত্র চেক করবে ব্যবহারকারী এই পণ্য কিনেছে কিনা (মেয়াদ不重要)
    return $this->vipInvestments()
        ->where('vip_product_id', $productId)
        ->exists();
}

    public function totalVipEarnings()
    {
        return $this->vipInvestments()
            ->where('expires_at', '>', now())
            ->sum('daily_earnings');
    }

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

    public function referrals()
    {
        return $this->hasMany(User::class, 'referred_by');
    }

    public static function generateReferralCode()
    {
        $length = 8;
        do {
            $code = strtoupper(substr(md5(uniqid()), 0, $length));
        } while (self::where('referral_code', $code)->exists());
        
        return $code;
    }

    public function withdrawals()
    {
        return $this->hasMany(Withdrawal::class);
    }

    public function addReferralBonus($amount)
    {
        if ($this->referred_by) {
            $referrer = User::find($this->referred_by);
            if ($referrer) {
                $bonus = $amount * 0.07;
                $referrer->balance += $bonus;
                $referrer->save();
                
                \App\Models\Transaction::create([
                    'user_id' => $referrer->id,
                    'type' => 'referral_bonus',
                    'amount' => $bonus,
                    'method' => 'referral',
                    'status' => 'approved',
                    'transaction_id' => 'REF-'.uniqid(),
                    'notes' => "Referral bonus from user #{$this->id}'s deposit"
                ]);
            }
        }
    }

    public function getTotalEarningsAttribute()
    {
        return $this->transactions()
            ->whereIn('type', ['earning', 'vip_earnings', 'referral_bonus'])
            ->sum('amount');
    }

    public function getTotalWithdrawalsAttribute()
    {
        return $this->transactions()
            ->where('type', 'withdrawal')
            ->where('status', 'approved')
            ->sum('amount');
    }

    public function getTotalIncomeAttribute()
    {
        return $this->total_earnings - $this->total_withdrawals;
    }

    
    public function getTeamSizeAttribute()
    {
        return $this->referrals()->count();
    }

    public function getIsVipAttribute()
    {
        return $this->vipInvestments()->where('expires_at', '>', now())->exists();
    }
}