<?php

namespace App\Http\Controllers;

use App\Models\ResellerProfile;
use App\Models\Raffle;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class ResellerWebController extends Controller
{
    /**
     * Muestra la vista web de registro para un revendedor o enlace de referido.
     */
    public function showRegistrationForm(Request $request, $code = null)
    {
        // El código puede venir en la ruta /r/{code}, /ref/{code} o en parámetro query ?ref=... o ?reseller=...
        $refCode = $code ?? $request->query('ref') ?? $request->query('reseller') ?? $request->query('code');
        
        $reseller = null;
        $referrerUser = null;
        $resellerName = null;

        if (!empty($refCode)) {
            $refCode = trim(strtoupper($refCode));
            
            // Buscar primero en perfiles de revendedor
            $resellerProfile = ResellerProfile::where('reseller_code', $refCode)->with('user')->first();
            
            if ($resellerProfile) {
                $reseller = $resellerProfile;
                $resellerName = $resellerProfile->user ? $resellerProfile->user->name : 'Revendedor Oficial Wincar';
            } else {
                // Buscar por código de referido de usuario común
                $referrerUser = User::where('referral_code', $refCode)->first();
                if ($referrerUser) {
                    $resellerName = $referrerUser->name;
                }
            }
        }

        // Cargar sorteos activos para mostrar en la landing
        $activeRaffles = Raffle::where('status', 'active')
            ->orderBy('is_featured', 'desc')
            ->orderBy('created_at', 'desc')
            ->take(4)
            ->get();

        return view('reseller.register', [
            'refCode' => $refCode,
            'reseller' => $reseller,
            'referrerUser' => $referrerUser,
            'resellerName' => $resellerName,
            'activeRaffles' => $activeRaffles,
        ]);
    }

    /**
     * Procesar el registro web desde el formulario del código QR
     */
    public function register(Request $request)
    {
        $disposableDomains = [
            'mailinator.com', 'tempmail.com', '10minutemail.com', 'guerrillamail.com',
            'yopmail.com', 'trashmail.com', 'dispostable.com', 'temp-mail.org',
            'fakeinbox.com', 'sharklasers.com', 'getairmail.com', 'maildrop.cc'
        ];

        $emailParts = explode('@', strtolower(trim($request->email ?? '')));
        $emailDomain = end($emailParts);

        if (in_array($emailDomain, $disposableDomains)) {
            return back()->withInput()->withErrors([
                'email' => 'No se permiten correos temporales o desechables para registrarse.'
            ]);
        }

        $validator = Validator::make($request->all(), [
            'name' => [
                'required',
                'string',
                'max:255',
                function ($attribute, $value, $fail) {
                    $parts = array_filter(explode(' ', trim($value)));
                    if (count($parts) < 2) {
                        $fail('Por favor ingresa tu nombre y al menos un apellido completo.');
                    }
                },
            ],
            'email' => 'required|string|email|max:255|unique:users',
            'cedula' => 'required|string|min:7|max:30|unique:users',
            'phone' => 'required|string|min:8|max:50',
            'password' => 'required|string|min:8|confirmed',
            'referred_by_code' => 'nullable|string',
        ], [
            'name.required' => 'El nombre completo es obligatorio.',
            'email.required' => 'El correo electrónico es obligatorio.',
            'email.unique' => 'Este correo electrónico ya se encuentra registrado.',
            'cedula.required' => 'La cédula es obligatoria.',
            'cedula.unique' => 'Esta cédula ya está registrada en el sistema.',
            'phone.required' => 'El número de teléfono es obligatorio.',
            'password.required' => 'La contraseña es obligatoria.',
            'password.min' => 'La contraseña debe tener al menos 8 caracteres.',
            'password.confirmed' => 'Las contraseñas no coinciden.',
        ]);

        if ($validator->fails()) {
            return back()->withInput()->withErrors($validator);
        }

        $referredById = null;
        $refCode = trim(strtoupper($request->referred_by_code ?? ''));

        if (!empty($refCode)) {
            $reseller = ResellerProfile::where('reseller_code', $refCode)->first();
            if ($reseller) {
                $referredById = $reseller->user_id;
            } else {
                $referrer = User::where('referral_code', $refCode)->first();
                if ($referrer) {
                    $referredById = $referrer->id;
                }
            }
        }

        // Obtener el rol por defecto de 'customer'
        $clientRoleId = DB::table('roles')->where('name', 'customer')->value('id') ?? 3;

        $user = User::create([
            'name' => trim($request->name),
            'email' => strtolower(trim($request->email)),
            'cedula' => trim($request->cedula),
            'phone' => trim($request->phone),
            'password' => Hash::make($request->password),
            'role_id' => $clientRoleId,
            'referred_by_id' => $referredById,
            'wallet_balance' => 0.00,
        ]);

        // Generar referral code propio
        if (!$user->referral_code) {
            $user->referral_code = User::generateUniqueReferralCode($user->name);
            $user->save();
        }

        return view('reseller.success', [
            'user' => $user,
            'resellerCode' => $refCode,
        ]);
    }
}
