<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

class ReferralCommission extends BaseModel
{
    use HasFactory;

    protected $fillable = [
        'referral_user_id',
        'customer_id',
        'order_id',
        'plan_price',
        'commission_rate',
        'commission_amount',
        'status',
        'earned_at',
        'paid_at',
        'meta_data',
    ];

    protected $casts = [
        'plan_price' => 'decimal:2',
        'commission_rate' => 'decimal:2',
        'commission_amount' => 'decimal:2',
        'earned_at' => 'datetime',
        'paid_at' => 'datetime',
        'meta_data' => 'array',
    ];

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

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

    public function payouts()
    {
        return $this->hasMany(ReferralPayout::class, 'referral_user_id', 'referral_user_id');
    }

    public function commissionPayouts()
    {
        return $this->hasMany(ReferralCommissionPayout::class, 'commission_id', 'id');
    }

    public function isIncludedInPayout()
    {
        return $this->commissionPayouts()->whereIn('status', ['requested', 'completed'])->exists();
    }

    public function approve()
    {
        $this->update([
            'status' => 'approved',
            'earned_at' => now(),
        ]);
    }

    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    public function scopeApproved($query)
    {
        return $query->where('status', 'approved');
    }

    public function scopePaid($query)
    {
        return $query->where('status', 'paid');
    }
}
