<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Referral;
use App\Models\ReferralSetting;
use App\Models\User;
use Illuminate\Http\Request;
use Inertia\Inertia;

class ReferralController extends Controller
{
    /**
     * Display listing of referrals.
     */
    public function index(Request $request)
    {
        $query = Referral::with(['referrer:id,name,email', 'referred:id,name,email,created_at']);

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

        // Search
        if ($request->filled('search')) {
            $search = $request->search;
            $query->whereHas('referrer', function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%");
            })->orWhereHas('referred', function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%");
            });
        }

        $referrals = $query->latest()->paginate(20)->withQueryString();

        // Stats
        $stats = [
            'total' => Referral::count(),
            'pending' => Referral::pending()->count(),
            'qualified' => Referral::qualified()->count(),
            'rewarded' => Referral::rewarded()->count(),
            'total_paid' => Referral::rewarded()->sum('reward_amount'),
        ];

        return Inertia::render('Admin/Referrals/Index', [
            'referrals' => $referrals,
            'stats' => $stats,
            'filters' => $request->only(['search', 'status']),
            'settings' => ReferralSetting::getSettings(),
        ]);
    }

    /**
     * Show referral settings page.
     */
    public function settings()
    {
        return Inertia::render('Admin/Referrals/Settings', [
            'settings' => ReferralSetting::getSettings(),
        ]);
    }

    /**
     * Update referral settings.
     */
    public function updateSettings(Request $request)
    {
        $validated = $request->validate([
            'referral_enabled' => 'required|boolean',
            'referral_bonus_amount' => 'required|numeric|min:0',
            'referral_bonus_type' => 'required|in:fixed,percentage',
            'referral_qualification_type' => 'required|in:signup,first_payment,first_month',
            'referral_min_subscription_amount' => 'nullable|numeric|min:0',
        ]);

        ReferralSetting::updateSettings($validated);

        return back()->with('success', 'Configuración actualizada correctamente.');
    }

    /**
     * Show a specific referral.
     */
    public function show(Referral $referral)
    {
        $referral->load(['referrer', 'referred', 'referralCode', 'walletTransaction']);

        return Inertia::render('Admin/Referrals/Show', [
            'referral' => $referral,
        ]);
    }

    /**
     * Approve and process referral reward.
     */
    public function approve(Referral $referral)
    {
        if ($referral->status === Referral::STATUS_REWARDED) {
            return back()->with('error', 'Este referido ya fue recompensado.');
        }

        try {
            // If pending, first mark as qualified
            if ($referral->status === Referral::STATUS_PENDING) {
                $referral->markAsQualified();
            }

            // Process the reward
            $referral->processReward();

            return back()->with('success', 'Referido aprobado y recompensa procesada.');
        } catch (\Exception $e) {
            return back()->with('error', 'Error al procesar: ' . $e->getMessage());
        }
    }

    /**
     * Reject/cancel a referral.
     */
    public function reject(Referral $referral)
    {
        if ($referral->status === Referral::STATUS_REWARDED) {
            return back()->with('error', 'No se puede cancelar un referido ya recompensado.');
        }

        $referral->cancel();

        return back()->with('success', 'Referido cancelado.');
    }
}
