<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Commission;
use App\Models\User;
use Illuminate\Http\Request;

class CommissionController extends Controller
{
    public function index(Request $request)
    {
        $query = Commission::with('user');
        
        if ($request->filled('search')) {
            $search = $request->search;
            $query->whereHas('user', function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%")
                  ->orWhere('member_code', 'like', "%{$search}%");
            });
        }
        
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        
        if ($request->filled('type')) {
            $query->where('type', $request->type);
        }
        
        if ($request->filled('level')) {
            $query->where('level', $request->level);
        }
        
        if ($request->filled('min_amount')) {
            $query->where('amount', '>=', $request->min_amount);
        }
        
        if ($request->filled('max_amount')) {
            $query->where('amount', '<=', $request->max_amount);
        }
        
        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }
        
        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }
        
        $commissions = $query->orderBy('created_at', 'desc')->paginate(20)->appends($request->all());
        $totalCommissions = Commission::sum('amount');
        $pendingCommissions = Commission::where('status', 'pending')->sum('amount');
        
        return view('admin.commissions.index', compact('commissions', 'totalCommissions', 'pendingCommissions'));
    }

    public function updateStatus(Request $request, Commission $commission)
    {
        $validated = $request->validate([
            'status' => 'required|in:pending,approved,paid,rejected'
        ]);

        $commission->update(['status' => $validated['status']]);

        return back()->with('success', 'Statut de la commission mis à jour !');
    }

    public function byUser()
    {
        $users = User::withSum('commissions', 'amount')
            ->get()
            ->filter(fn($user) => $user->commissions_sum_amount > 0)
            ->sortByDesc('commissions_sum_amount')
            ->values();

        $perPage = 20;
        $currentPage = request()->get('page', 1);
        $pagedData = $users->slice(($currentPage - 1) * $perPage, $perPage)->all();
        
        $users = new \Illuminate\Pagination\LengthAwarePaginator(
            $pagedData,
            $users->count(),
            $perPage,
            $currentPage,
            ['path' => request()->url()]
        );

        return view('admin.commissions.by-user', compact('users'));
    }
}
