<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;
use App\Notifications\ResetPasswordNotification;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * Kolom yang bisa diisi mass-assignment.
     */
    protected $fillable = [
    'name',
    'email',
    'phone',
    'password',
    'balance',
    'referrer_id',
    'api_key',
    'webhook_url',

    'telegram_id',
    'telegram_username',
    'telegram_photo_url',
    'register_source',
    'reseller',
];

    /**
     * Kolom yang disembunyikan.
     */
    protected $hidden = [
        'password',
        'remember_token',
        'api_key', // 🔥 biar gak ke expose
    ];

    /**
     * Konversi otomatis tipe data.
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    /**
     * Boot model
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($user) {
            // 🔹 referral code
            $user->referral_code = self::generateReferralCode();

            // 🔹 api key
            if (empty($user->api_key)) {
                $user->api_key = self::generateApiKey();
            }
        });
    }

    /**
     * Generate referral code unik
     */
    public static function generateReferralCode()
    {
        do {
            $code = strtoupper(Str::random(8));
        } while (self::where('referral_code', $code)->exists());

        return $code;
    }

    /**
     * Generate API key unik
     */
    public static function generateApiKey()
    {
        do {
            $key = 'N_' . Str::random(40);
        } while (self::where('api_key', $key)->exists());

        return $key;
    }

    /**
     * Reset password notification
     */
    public function sendPasswordResetNotification($token)
    {
        $this->notify(new ResetPasswordNotification($token));
    }

    /* ========================================================
     | 🔹 RELASI MODEL
     |======================================================== */

    public function orders()
    {
        return $this->hasMany(Order::class, 'user_id');
    }

    public function deposits()
    {
        return $this->hasMany(Deposit::class, 'user_id');
    }

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

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

    public function referralCommissions()
    {
        return $this->hasMany(ReferralCommission::class, 'referrer_id');
    }
}