<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Withdrawal;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class AdminWithdrawalController extends Controller
{
    /**
     * Afficher la liste des demandes de retrait en attente
     */
    public function index(Request $request)
    {
        $query = Withdrawal::query();

        // Filtrer par statut
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        } else {
            // Par défaut, afficher les demandes en attente
            $query->where('status', 'pending');
        }

        // Recherche par nom d'utilisateur ou email
        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}%");
            });
        }

        // Filtre par montant
        if ($request->filled('min_amount')) {
            $query->where('amount', '>=', $request->min_amount);
        }
        if ($request->filled('max_amount')) {
            $query->where('amount', '<=', $request->max_amount);
        }

        // Trier par date décroissante
        $withdrawals = $query->orderBy('created_at', 'desc')->paginate(20);

        // Statistiques
        $stats = [
            'total_pending' => Withdrawal::where('status', 'pending')->count(),
            'total_amount_pending' => Withdrawal::where('status', 'pending')->sum('amount'),
            'approved_today' => Withdrawal::where('status', 'approved')
                ->whereDate('created_at', now()->toDateString())
                ->count(),
            'rejected_today' => Withdrawal::where('status', 'rejected')
                ->whereDate('created_at', now()->toDateString())
                ->count(),
        ];

        return view('admin.withdrawals.index', compact('withdrawals', 'stats'));
    }

    /**
     * Afficher les détails d'une demande de retrait
     */
    public function show(Withdrawal $withdrawal)
    {
        return view('admin.withdrawals.show', compact('withdrawal'));
    }

    /**
     * Approuver une demande de retrait
     */
    public function approve(Request $request, Withdrawal $withdrawal)
    {
        if ($withdrawal->status !== 'pending') {
            return redirect()->back()->with('error', 'Cette demande ne peut pas être approuvée (statut: ' . $withdrawal->status . ')');
        }

        try {
            $withdrawal->update([
                'status' => 'approved',
                'approved_by' => auth()->id(),
                'approved_at' => now(),
                'notes' => $request->input('notes', 'Approuvé par admin'),
            ]);

            // Notification à l'utilisateur
            if ($withdrawal->user) {
                $withdrawal->user->notify(new \App\Notifications\WithdrawalApprovedNotification($withdrawal));
            }

            Log::info("Retrait #{$withdrawal->id} approuvé par " . auth()->user()->name);

            return redirect()->back()->with('success', 'Demande de retrait approuvée avec succès !');
        } catch (\Exception $e) {
            Log::error("Erreur approbation retrait: " . $e->getMessage());
            return redirect()->back()->with('error', 'Erreur lors de l\'approbation');
        }
    }

    /**
     * Rejeter une demande de retrait
     */
    public function reject(Request $request, Withdrawal $withdrawal)
    {
        $request->validate([
            'reason' => 'required|string|min:10|max:500'
        ]);

        if ($withdrawal->status !== 'pending') {
            return redirect()->back()->with('error', 'Cette demande ne peut pas être rejetée');
        }

        try {
            $withdrawal->update([
                'status' => 'rejected',
                'approved_by' => auth()->id(),
                'approved_at' => now(),
                'rejection_reason' => $request->reason,
            ]);

            // Rembourser le montant au portefeuille si déjà débité
            if ($withdrawal->wallet) {
                $withdrawal->wallet->increment('balance', $withdrawal->amount);
            }

            // Notification à l'utilisateur
            if ($withdrawal->user) {
                $withdrawal->user->notify(new \App\Notifications\WithdrawalRejectedNotification($withdrawal, $request->reason));
            }

            Log::info("Retrait #{$withdrawal->id} rejeté par " . auth()->user()->name . " - Raison: " . $request->reason);

            return redirect()->back()->with('success', 'Demande de retrait rejetée !');
        } catch (\Exception $e) {
            Log::error("Erreur rejet retrait: " . $e->getMessage());
            return redirect()->back()->with('error', 'Erreur lors du rejet');
        }
    }

    /**
     * Approuver plusieurs demandes en masse
     */
    public function approveBatch(Request $request)
    {
        $request->validate([
            'withdrawal_ids' => 'required|array',
            'withdrawal_ids.*' => 'exists:withdrawals,id'
        ]);

        $count = 0;
        foreach ($request->withdrawal_ids as $id) {
            $withdrawal = Withdrawal::find($id);
            if ($withdrawal && $withdrawal->status === 'pending') {
                $withdrawal->update([
                    'status' => 'approved',
                    'approved_by' => auth()->id(),
                    'approved_at' => now(),
                ]);
                $count++;
            }
        }

        return redirect()->back()->with('success', "{$count} demande(s) approuvée(s) avec succès !");
    }

    /**
     * Exporter les demandes de retrait
     */
    public function export(Request $request)
    {
        $query = Withdrawal::query();

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        $withdrawals = $query->get();

        $filename = 'withdrawals_' . now()->format('Y-m-d_H-i-s') . '.csv';
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => "attachment; filename=\"{$filename}\"",
        ];

        $callback = function() use ($withdrawals) {
            $file = fopen('php://output', 'w');
            fputcsv($file, ['ID', 'Utilisateur', 'Email', 'Montant', 'Statut', 'Date', 'Approuvé par']);

            foreach ($withdrawals as $withdrawal) {
                fputcsv($file, [
                    $withdrawal->id,
                    $withdrawal->user->name ?? 'N/A',
                    $withdrawal->user->email ?? 'N/A',
                    $withdrawal->amount,
                    $withdrawal->status,
                    $withdrawal->created_at->format('Y-m-d H:i:s'),
                    $withdrawal->approver?->name ?? 'N/A',
                ]);
            }

            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }
}
