<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Models\ReferralCommission;

class ReferralPayout extends BaseModel
{
    use HasFactory;

    protected $fillable = [
        'referral_user_id',
        'amount',
        'status',
        'attachment_url',
        'notes',
        'payment_method',
        'payment_details',
        'requested_at',
        'processed_at',
        'processed_by',
    ];

    protected $casts = [
        'amount' => 'decimal:2',
        'payment_details' => 'array',
        'requested_at' => 'datetime',
        'processed_at' => 'datetime',
    ];

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

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

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

    public function commissions()
    {
        return $this->belongsToMany(ReferralCommission::class, 'referral_commission_payouts', 'payout_id', 'commission_id')
                    ->withPivot(['commission_amount', 'status', 'included_at', 'processed_at', 'notes'])
                    ->withTimestamps();
    }

    public function getTotalCommissionAmount()
    {
        return $this->commissionPayouts()->sum('commission_amount');
    }

    public function getCommissionCount()
    {
        return $this->commissionPayouts()->count();
    }

    public function approve($attachmentUrl = null, $notes = null, $processedBy = null)
    {
        $this->update([
            'status' => 'paid',
            'attachment_url' => $attachmentUrl,
            'notes' => $notes,
            'processed_at' => now(),
            'processed_by' => $processedBy,
        ]);

        // Mark all included commissions as completed
        $this->commissionPayouts()->requested()->get()->each(function ($commissionPayout) {
            $commissionPayout->markAsCompleted();
        });

        // Update commission status to paid
        ReferralCommission::whereIn('id', $this->commissionPayouts()->pluck('commission_id'))->update(['status' => 'paid', 'paid_at' => now()]);
    }

    public function reject($notes = null, $processedBy = null)
    {
        $this->update([
            'status' => 'rejected',
            'notes' => $notes,
            'processed_at' => now(),
            'processed_by' => $processedBy,
        ]);

        // Mark all included commissions as rejected and make them available again
        $this->commissionPayouts()->requested()->get()->each(function ($commissionPayout) use ($notes) {
            $commissionPayout->markAsRejected($notes);
        });

        // Reset commission status back to approved (make them available for future payouts)
        ReferralCommission::whereIn('id', $this->commissionPayouts()->pluck('commission_id'))->update(['status' => 'approved']);
    }

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

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

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