<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

class Affiliate extends Model
{
    protected $keyType = 'string';
    public $incrementing = false;

    protected $fillable = [
        'user_id',
        'code',
        'status',
        'total_referrals',
        'qualified_referrals',
        'total_credits_earned',
        'pending_credits',
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (!$model->id) {
                $model->id = (string) Str::uuid();
            }
        });
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

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

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

    public function getReferralLinkAttribute(): string
    {
        return 'https://www.aziros.com/register?ref=' . $this->code;
    }

    public static function generateCode(User $user): string
    {
        // Format: AZ-XXXXXX (6 alphanumerische Zeichen, ohne verwechselbare Buchstaben)
        $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // ohne I, O, 0, 1

        do {
            $random = '';
            for ($i = 0; $i < 6; $i++) {
                $random .= $chars[random_int(0, strlen($chars) - 1)];
            }
            $code = 'AZ-' . $random;
        } while (static::where('code', $code)->exists());

        return $code;
    }
}
