<?php

namespace App\Models;

use App\Constants\Status;
use App\Traits\Searchable;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use Searchable, Notifiable;

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token', 'ver_code'];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'address' => 'object',
        'kyc_data' => 'object',
        'ver_code_send_at' => 'datetime',
        'network_activated_at' => 'datetime',
        'app_downloaded_at' => 'datetime',
        'coupon_issued_at' => 'datetime',
    ];

    protected $guarded = [];

    public function loginLogs()
    {
        return $this->hasMany(UserLogin::class);
    }

    public function transactions()
    {
        return $this->hasMany(Transaction::class)->orderBy('id', 'desc');
    }

    public function deposits()
    {
        return $this->hasMany(Deposit::class)->where('status', '!=', Status::PAYMENT_INITIATE);
    }

    public function withdrawals()
    {
        return $this->hasMany(Withdrawal::class)->where('status', '!=', Status::PAYMENT_INITIATE);
    }

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

    public function level()
    {
        return $this->belongsTo(Level::class, 'rank');
    }

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

    public function allReferrals()
    {
        return $this->referrals()->with('allReferrals');
    }

    public function plan()
    {
        return $this->belongsTo(Plan::class);
    }

    public function rewards()
    {
        return $this->hasMany(Reward::class);
    }

    public function paidPayments()
    {
        return $this->hasMany(Payment::class, 'payer_user_id');
    }

    public function receivedPayments()
    {
        return $this->hasMany(Payment::class, 'receiver_user_id');
    }

    public function planPurchases()
    {
        return $this->hasMany(PlanPurchase::class);
    }

    public function bankDetail()
    {
        return $this->hasOne(BankDetail::class);
    }

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

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

    public function coupons()
    {
        return $this->hasMany(Coupon::class);
    }

    public function fullname(): Attribute
    {
        return new Attribute(get: fn() => $this->firstname . ' ' . $this->lastname);
    }

    // SCOPES
    public function scopeActive($query)
    {
        return $query->where('dummy_person', false)
            ->where('status', Status::USER_ACTIVE)
            ->where('ev', Status::VERIFIED)
            ->where('sv', Status::VERIFIED);
    }

    public function scopeBanned($query)
    {
        return $query->where('dummy_person', false)->where('status', Status::USER_BAN);
    }

    public function scopeEmailUnverified($query)
    {
        return $query->where('dummy_person', false)->where('ev', Status::NO);
    }

    public function scopeMobileUnverified($query)
    {
        return $query->where('dummy_person', false)->where('sv', Status::NO);
    }

    public function scopeKycUnverified($query)
    {
        return $query->where('dummy_person', false)->where('kv', Status::KYC_UNVERIFIED);
    }

    public function scopeKycPending($query)
    {
        return $query->where('dummy_person', false)->where('kv', Status::KYC_PENDING);
    }

    public function scopeKycRejected($query)
    {
        return $query->where('dummy_person', false)->where('kv', Status::KYC_REJECTED);
    }

    public function scopeEmailVerified($query)
    {
        return $query->where('dummy_person', false)->where('ev', Status::VERIFIED);
    }

    public function scopeMobileVerified($query)
    {
        return $query->where('dummy_person', false)->where('sv', Status::VERIFIED);
    }

    public function scopeWithBalance($query)
    {
        return $query->where('dummy_person', false)->where('balance', '>', 0);
    }

    public function scopeNotPurchased($query)
    {
        return $query->where('dummy_person', false)->where('network_status', Status::NetworkPending);
    }

    public function scopePlanPurchased($query)
    {
        return $query->where('dummy_person', false)->where('network_status', Status::NetworkPlanPurchased);
    }

    public function scopeFullActivated($query)
    {
        return $query->where('dummy_person', false)->where('network_status', Status::NetworkFullActivated);
    }
    public function scopedownloadAppUserList($query)
    {
        return $query->whereNotNull('app_downloaded_at')->withCount([
            'coupons as recently_coupon_issued' => function ($query) {
                $query->whereColumn('coupons.created_at', '>', 'app_downloaded_at');
            },
        ]);
    }

    public function scopeInDebt($query) {
        return $query->where('dummy_person', false)->where('current_debt_value', '!=', 0);
    }

    public function networkStatusBadge(): Attribute
    {
        return new Attribute(
            get: function () {
                $badges = [
                    Status::NetworkPending => '<span class="badge bg-info">Pending</span>',
                    Status::NetworkPlanPurchased => '<span class="badge bg-secondary">Plan Purchased</span>',
                    Status::NetworkFullActivated => '<span class="badge bg-success">Full Activated</span>',
                ];
                return $badges[$this->network_status] ?? '<span class="badge bg-danger">Unknown</span>';
            },
        );
    }
}
