<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

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

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'member_code',
        'referral_code',
        'name',
        'email',
        'mobile',
        'address',
        'city',
        'state',
        'pincode',
        'password',
        'role',
        'status',
        'wallet_frozen',
        'upi_locked_at',
        'sponsor_id',
        'placement_parent_id',
        'placement_id',
        'parent_id',
        'placement_leg',
        'position',
        'left_count',
        'right_count',
        'left_business',
        'right_business',
        'carry_forward_left',
        'carry_forward_right',
        'package_amount',
        'current_rank_id',
        'merged_into_user_id',
        'merged_at',
        'closed_at',
        'joined_at',
        'last_login_at',
        'login_otp_enabled',
        'profile_photo_path',
        'dark_mode_enabled',
        'theme_preference',
        'notify_sms_enabled',
        'notify_email_enabled',
        'notify_whatsapp_enabled',
        'notify_push_enabled',
        'auto_rebuy_enabled',
        'auto_upgrade_enabled',
        'current_plan_id',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
        'joined_at' => 'datetime',
        'last_login_at' => 'datetime',
        'package_amount' => 'decimal:2',
        'login_otp_enabled' => 'boolean',
        'wallet_frozen' => 'boolean',
        'upi_locked_at' => 'datetime',
        'merged_at' => 'datetime',
        'closed_at' => 'datetime',
        'dark_mode_enabled' => 'boolean',
        'theme_preference' => 'string',
        'notify_sms_enabled' => 'boolean',
        'notify_email_enabled' => 'boolean',
        'notify_whatsapp_enabled' => 'boolean',
        'notify_push_enabled' => 'boolean',
        'auto_rebuy_enabled' => 'boolean',
        'auto_upgrade_enabled' => 'boolean',
        'left_count' => 'integer',
        'right_count' => 'integer',
        'left_business' => 'decimal:4',
        'right_business' => 'decimal:4',
        'carry_forward_left' => 'decimal:4',
        'carry_forward_right' => 'decimal:4',
    ];

    public function sponsor(): BelongsTo
    {
        return $this->belongsTo(self::class, 'sponsor_id');
    }

    public function placementParent(): BelongsTo
    {
        return $this->belongsTo(self::class, 'placement_parent_id');
    }

    public function placement(): BelongsTo
    {
        return $this->belongsTo(self::class, 'placement_id');
    }

    public function parent(): BelongsTo
    {
        return $this->belongsTo(self::class, 'parent_id');
    }

    public function currentPlan(): BelongsTo
    {
        return $this->belongsTo(Plan::class, 'current_plan_id');
    }

    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class, 'user_roles')->withTimestamps();
    }

    public function walletBalance(): HasOne
    {
        return $this->hasOne(WalletBalance::class);
    }

    public function walletTransactions(): HasMany
    {
        return $this->hasMany(WalletTransaction::class);
    }

    public function binaryCarry(): HasOne
    {
        return $this->hasOne(UserBinaryCarry::class);
    }

    public function userKyc(): HasOne
    {
        return $this->hasOne(UserKyc::class);
    }

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

    public function currentRank(): BelongsTo
    {
        return $this->belongsTo(Rank::class, 'current_rank_id');
    }

    public function notifications(): HasMany
    {
        return $this->hasMany(UserNotification::class);
    }

    public function devices(): HasMany
    {
        return $this->hasMany(UserDevice::class);
    }

    public function ipLogs(): HasMany
    {
        return $this->hasMany(IpLog::class);
    }

    public function commissionLedgers(): HasMany
    {
        return $this->hasMany(CommissionLedger::class);
    }

    public function fraudLogs(): HasMany
    {
        return $this->hasMany(FraudLog::class);
    }

    public function hasRole(string $roleCode): bool
    {
        return $this->roles()->where('code', $roleCode)->exists();
    }

    public function hasPermission(string $permissionCode): bool
    {
        return Permission::query()
            ->where('code', $permissionCode)
            ->whereHas('roles.users', fn ($query) => $query->where('users.id', $this->id))
            ->exists();
    }

    public function getPlacementIdAttribute($value): mixed
    {
        return $value ?? ($this->attributes['placement_parent_id'] ?? null);
    }

    public function setPlacementIdAttribute($value): void
    {
        $this->attributes['placement_id'] = $value;
        $this->attributes['placement_parent_id'] = $value;
        if (! array_key_exists('parent_id', $this->attributes) || $this->attributes['parent_id'] === null) {
            $this->attributes['parent_id'] = $value;
        }
    }

    public function getParentIdAttribute($value): mixed
    {
        return $value ?? ($this->attributes['placement_parent_id'] ?? null);
    }

    public function setParentIdAttribute($value): void
    {
        $this->attributes['parent_id'] = $value;
        $this->attributes['placement_parent_id'] = $value;
        if (! array_key_exists('placement_id', $this->attributes) || $this->attributes['placement_id'] === null) {
            $this->attributes['placement_id'] = $value;
        }
    }

    public function setPlacementParentIdAttribute($value): void
    {
        $this->attributes['placement_parent_id'] = $value;

        if (! array_key_exists('placement_id', $this->attributes) || $this->attributes['placement_id'] === null) {
            $this->attributes['placement_id'] = $value;
        }
        if (! array_key_exists('parent_id', $this->attributes) || $this->attributes['parent_id'] === null) {
            $this->attributes['parent_id'] = $value;
        }
    }

    public function getPositionAttribute($value): mixed
    {
        return $value ?? ($this->attributes['placement_leg'] ?? null);
    }

    public function setPositionAttribute($value): void
    {
        $this->attributes['position'] = $value;
        $this->attributes['placement_leg'] = $value;
    }

    public function setPlacementLegAttribute($value): void
    {
        $this->attributes['placement_leg'] = $value;

        if (! array_key_exists('position', $this->attributes) || $this->attributes['position'] === null) {
            $this->attributes['position'] = $value;
        }
    }
}
