<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Affiliate extends AbstractModel
{
    use SoftDeletes;

    protected $table = 'affiliates';

    protected $fillable = [
        'code',
        'campaign_name',
        'campaign_description',
        'is_active',
        'created_by',
        'clicks_count',
        'registrations_count',
        'orders_count'
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
            'clicks_count' => 'integer',
            'registrations_count' => 'integer',
            'orders_count' => 'integer',
            'deleted_at' => 'datetime',
        ];
    }

    /**
     * @return BelongsTo
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * @return BelongsToMany
     */
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'user_affiliates', 'affiliate_id', 'user_id')
            ->withPivot('clicked_at', 'registered_at')
            ->withTimestamps();
    }

    /**
     * Generate the affiliate tracking link
     * 
     * @return string
     */
    public function getTrackingLinkAttribute(): string
    {
        $baseUrl = config('app.url');
        return $baseUrl . '/signup?tracking=' . $this->code;
    }
}

