<?php

namespace App\Livewire\Admin\Affiliates;

use App\Models\Affiliate;
use App\Models\AffiliateCreditLog;
use App\Models\AffiliateReferral;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component
{
    use WithPagination;

    public string $search = '';

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function toggleStatus(string $affiliateId)
    {
        $affiliate = Affiliate::findOrFail($affiliateId);
        $affiliate->update([
            'status' => $affiliate->status === 'active' ? 'paused' : 'active',
        ]);

        $this->dispatch('notify', type: 'success', message: 'Affiliate-Status aktualisiert.');
    }

    public function banAffiliate(string $affiliateId)
    {
        Affiliate::findOrFail($affiliateId)->update(['status' => 'banned']);
        $this->dispatch('notify', type: 'success', message: 'Affiliate gesperrt.');
    }

    public function render()
    {
        $affiliates = Affiliate::with('user')
            ->whereHas('user', fn($q) =>
                $q->whereNotIn('role', ['admin', 'super_admin', 'developer', 'support'])
            )
            ->withCount([
                'referrals',
                'referrals as pending_count' => fn($q) => $q->where('status', 'pending'),
                'referrals as paid_count' => fn($q) => $q->where('status', 'paid'),
            ])
            ->when($this->search, fn($q) =>
                $q->whereHas('user', fn($uq) =>
                    $uq->where('name', 'like', '%' . $this->search . '%')
                       ->orWhere('email', 'like', '%' . $this->search . '%')
                )->orWhere('code', 'like', '%' . $this->search . '%')
            )
            ->orderByDesc('total_credits_earned')
            ->paginate(25);

        $stats = [
            'total_affiliates'  => Affiliate::count(),
            'active_affiliates' => Affiliate::where('status', 'active')->count(),
            'total_referrals'   => AffiliateReferral::count(),
            'pending_referrals' => AffiliateReferral::where('status', 'pending')->count(),
            'credits_paid_out'  => AffiliateCreditLog::sum('credits'),
        ];

        return view('livewire.admin.affiliates.index', compact('affiliates', 'stats'))
            ->layout('layouts.app');
    }
}
