<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\OAuthSetting;
use App\Models\Plan;
use App\Models\ReferralCode;
use App\Models\Subscription;
use App\Models\User;
use App\Notifications\CoachWelcome;
use App\Notifications\NewCoachRegistered;
use App\Notifications\ReferralActive;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rules;
use Inertia\Inertia;
use Inertia\Response;

class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     */
    public function create(Request $request): Response
    {
        // Track referral link clicks
        if ($ref = $request->query('ref')) {
            $code = strtoupper($ref);
            $referralCode = ReferralCode::where('code', $code)
                ->where('is_active', true)
                ->first();
            
            if ($referralCode) {
                $referralCode->incrementClicks();
            }
        }
        
        // Get and validate plan parameter
        $planSlug = $request->query('plan');
        $selectedPlan = null;
        
        if ($planSlug) {
            $selectedPlan = Plan::where('slug', $planSlug)
                ->where('is_active', true)
                ->first();
            
            if (!$selectedPlan) {
                Log::warning('Invalid plan slug in registration URL', ['slug' => $planSlug]);
            }
        }

        return Inertia::render('Auth/Register', [
            'googleLoginEnabled' => OAuthSetting::isProviderEnabled('google'),
            'selectedPlan' => $selectedPlan ? [
                'id' => $selectedPlan->id,
                'slug' => $selectedPlan->slug,
                'name' => $selectedPlan->name,
                'price' => (float) $selectedPlan->price,
                'duration_days' => $selectedPlan->duration_days,
            ] : null,
        ]);
    }

    /**
     * Handle an incoming registration request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|lowercase|email|max:255|unique:'.User::class,
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
            'referral_code' => ['nullable', 'string', function ($attribute, $value, $fail) {
                if (empty($value)) {
                    return;
                }
                
                $code = strtoupper($value);
                
                // Check in referral_codes table first
                $referralCode = ReferralCode::where('code', $code)
                    ->where('is_active', true)
                    ->first();
                
                if ($referralCode && $referralCode->isValid()) {
                    return; // Valid promotional code
                }
                
                // Fallback: check user's personal referral code
                $userWithCode = User::where('referral_code', $code)->first();
                
                if ($userWithCode) {
                    return; // Valid user referral code
                }
                
                $fail('El código de referido no es válido o ha expirado.');
            }],
            'plan' => ['nullable', 'string', 'exists:plans,slug'],
        ]);

        $referrer = null;
        $referralCodeRecord = null;
        
        if ($request->referral_code) {
            $code = strtoupper($request->referral_code);
            
            // First try to find in referral_codes table
            $referralCodeRecord = ReferralCode::where('code', $code)
                ->where('is_active', true)
                ->first();
            
            if ($referralCodeRecord && $referralCodeRecord->user_id) {
                // Get the user who owns this referral code
                $referrer = User::find($referralCodeRecord->user_id);
            }
            
            // Fallback: check user's personal referral code
            if (!$referrer) {
                $referrer = User::where('referral_code', $code)->first();
            }
        }

        // Create user as coach with active status
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'role' => 'coach',
            'status' => 'active', 
            'referral_code' => strtoupper(\Illuminate\Support\Str::random(8)),
            'referred_by' => $request->referral_code ? strtoupper($request->referral_code) : null,
        ]);

        // Track usage of promotional referral code
        if ($referralCodeRecord) {
            $referralCodeRecord->increment('uses');
        }

        if ($referrer) {
            $referrer->increment('referral_count');
            
            // Get bonus amount from settings (default $10)
            $referralSettings = \App\Models\ReferralSetting::getSettings();
            $bonusAmount = $referralSettings['bonus_amount'] ?? 10;
            
            // Create referral record
            $referralRecord = \App\Models\Referral::create([
                'referrer_id' => $referrer->id,
                'referred_id' => $user->id,
                'referral_code_id' => $referralCodeRecord?->id,
                'status' => \App\Models\Referral::STATUS_PENDING,
                'reward_amount' => $bonusAmount,
            ]);
            
            // Check if qualification type is 'signup' - give bonus immediately
            if (($referralSettings['qualification_type'] ?? 'first_payment') === 'signup') {
                // Ensure referrer has a wallet
                $wallet = $referrer->wallet ?? \App\Models\Wallet::create(['user_id' => $referrer->id]);
                
                // Add bonus to wallet
                $wallet->increment('balance', $bonusAmount);
                
                // Create transaction
                $transaction = \App\Models\WalletTransaction::create([
                    'wallet_id' => $wallet->id,
                    'type' => 'referral_bonus',
                    'amount' => $bonusAmount,
                    'balance_after' => $wallet->fresh()->balance,
                    'description' => "Bono por referir a {$user->name}",
                ]);
                
                // Update referral status
                $referralRecord->update([
                    'status' => \App\Models\Referral::STATUS_REWARDED,
                    'wallet_transaction_id' => $transaction->id,
                    'qualified_at' => now(),
                    'rewarded_at' => now(),
                ]);
                
                // Notify the referrer
                $referrer->notify(new ReferralActive($user, $bonusAmount));
            }
        }

        // Determine which plan to assign
        $planSlug = $request->plan;
        $selectedPlan = null;
        
        if ($planSlug) {
            $selectedPlan = Plan::where('slug', $planSlug)
                ->where('is_active', true)
                ->first();
        }
        
        // If no valid plan selected, use trial
        if (!$selectedPlan) {
            $selectedPlan = Plan::where('slug', 'trial')->first();
        }
        
        // Auto-assign Trial subscription (free plans)
        // For paid plans, only assign if price is 0
        if ($selectedPlan && (float) $selectedPlan->price <= 0) {
            Subscription::create([
                'user_id' => $user->id,
                'plan_id' => $selectedPlan->id,
                'start_date' => now(),
                'end_date' => now()->addDays($selectedPlan->duration_days),
                'status' => 'active',
            ]);
            
            Log::info('User registered with free plan', [
                'user_id' => $user->id,
                'plan' => $selectedPlan->slug,
            ]);
        }
        
        // Create empty Wallet
        \App\Models\Wallet::create([
            'user_id' => $user->id,
            'balance' => 0,
        ]);

        // Notificar a los administradores sobre el nuevo coach
        $admins = User::where('role', 'admin')->get();
        foreach ($admins as $admin) {
            $admin->notify(new NewCoachRegistered($user));
        }

        // Enviar correo de bienvenida al coach con información del plan
        $user->notify(new CoachWelcome($user, $selectedPlan));

        event(new Registered($user));

        Auth::login($user);

        // Check for paid plan - redirect to checkout
        if ($selectedPlan && (float) $selectedPlan->price > 0) {
            Log::info('User registered, redirecting to checkout for paid plan', [
                'user_id' => $user->id,
                'plan' => $selectedPlan->slug,
                'price' => $selectedPlan->price,
            ]);
            
            return redirect()->route('coach.subscription.show', ['plan' => $selectedPlan->slug])
                ->with('info', 'Completa el pago para activar tu plan ' . $selectedPlan->name);
        }
        
        // Check for plan purchase intent from session (fallback for old flow)
        $planIntent = session()->pull('plan_purchase_intent');
        if ($planIntent && isset($planIntent['plan_slug'])) {
            return redirect()->route('coach.subscription.show', ['plan' => $planIntent['plan_slug']]);
        }

        return redirect()->intended(route('dashboard', absolute: false));
    }
}

