<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\File;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    // ✅ Fillable attributes
    protected $fillable = [
        'name',
        'email',
        'mobile',
        'password',
        'profile_photo',
        'referred_by',       // যিনি রেফার করেছেন তার user_id
        'referral_code',     // এই ইউজারের নিজস্ব ইউনিক রেফারেল কোড
        'balance',
        'voucher_balance',
        'ban_reason',
        'withdraw_hold',
        'withdraw_hold_reason',
        'admin_message',
        'leadership_referral_enabled',
    ];

    // ✅ Hidden attributes
    protected $hidden = [
        'password',
        'remember_token',
    ];
    
    
    
    protected $casts = [
    'created_at' => 'datetime',
    'updated_at' => 'datetime',
    'activated_at' => 'datetime',
    'withdraw_hold' => 'boolean',
];
    

    // ✅ Cast attributes
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }


private static $image, $imageExtension, $imageName, $directory;

    public static function saveProfileImage($request)
    {
        self::$image = $request->file('profile_photo');
        self::$imageExtension = self::$image->getClientOriginalExtension();
        self::$imageName = time() . '_' . uniqid() . '.' . self::$imageExtension;
        self::$directory = ensure_public_directory('images/profile');

        $destination = rtrim(self::$directory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;

        $user = auth()->user();

        // পুরাতন ছবি ডিলিট
        if ($user->profile_photo) {
            $oldPath = trim((string) $user->profile_photo);
            $oldPhoto = str_contains($oldPath, '/')
                ? public_asset_path($oldPath)
                : public_asset_path('images/profile/' . $oldPath);

            if (File::exists($oldPhoto)) {
                File::delete($oldPhoto);
            }
        }

        self::$image->move(self::$directory, self::$imageName);
        optimize_uploaded_image(self::$directory . DIRECTORY_SEPARATOR . self::$imageName);

        return self::$imageName;

    }

    public static function updateProfile($request)
    {
        $user = auth()->user();

        $user->name = $request->name;
        $user->mobile = $request->mobile;

        if ($request->hasFile('profile_photo')) {
            $user->profile_photo = self::saveProfileImage($request);
        }

        $user->save();
    }


// ✅ যিনি এই ইউজারকে রেফার করেছেন
    public function referrer()
    {
        return $this->belongsTo(User::class, 'referred_by', 'referral_code');
    }

    // ✅ এই ইউজার যাদের রেফার করেছে
    public function referrals()
    {
        return $this->hasMany(User::class, 'referred_by', 'referral_code');
    }

    // ✅ বিকল্প নাম: uplink (উপরের লেভেলের ইউজার)
    public function upline()
{
    $ref = trim((string) $this->referred_by);
    if ($ref === '') {
        return null;
    }

    $upline = User::where('referral_code', $ref)->first();
    if ($upline) {
        return $upline;
    }

    if (ctype_digit($ref)) {
        return User::find((int) $ref);
    }

    return null;
}
    

    // ✅ ব্যালেন্স লগ রিলেশন
    public function balanceLogs()
    {
        return $this->hasMany(BalanceLog::class);
    }

    // ✅ ব্যালেন্স যোগ করার ফাংশন (অটো লগ ইনসার্ট করে)
    public function addBalance($amount)
    {
        $this->balance += $amount;
        $this->save();

        $this->balanceLogs()->create([
            'amount' => $amount,
        ]);
    }

    // ✅ ইউজার কোন কোন Leadership অর্জন করেছে
    public function userLeaderships()
    {
        return $this->hasMany(UserLeadership::class);
    }

    // ✅ ইউজার একটি নির্দিষ্ট Leadership লেভেল অর্জন করেছে কিনা (উদাহরণ ফাংশন)
    public function hasAchievedLevel($level_id)
    {
        return $this->userLeaderships()->where('leadership_level_id', $level_id)->exists();
    }

    // ✅ ইউজার কোনো লেভেল অর্জনের রেকর্ড (ডায়নামিক রিটার্ন)
    public function getLeadershipLevel($level_id)
    {
        return $this->userLeaderships()->where('leadership_level_id', $level_id)->first();
    }

    public function gmailSales()
{
    return $this->hasMany(\App\Models\GmailSale::class);
}

public function favorites()
{
    return $this->hasMany(\App\Models\Favorite::class);
}

public function favoriteProducts()
{
    return $this->belongsToMany(\App\Models\Product::class, 'favorites');
}

public function welcomeOfferClaim()
{
    return $this->hasOne(\App\Models\WelcomeOfferClaim::class);
}

public function typingJobSubmissions()
{
    return $this->hasMany(\App\Models\TypingJobSubmission::class);
}

}
