<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use App\Services\EmailService;
use App\Services\NotificationService;
use App\Helpers\RoleHelper;
use Carbon\Carbon;

class AuthController extends Controller
{
    public function showAdminLogin()
    {
        return view('auth.admin-login');
    }

    public function adminLogin(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required'
        ]);

        $user = User::where('email', $request->email)->first();

        if ($user && Hash::check($request->password, $user->password)) {
            // Vérifier si l'utilisateur a accès au back-office
            if (RoleHelper::canAccessBackoffice($user->role)) {
                Auth::login($user);
                $request->session()->regenerate();
                
                \App\Models\UserActivityLog::log('login', 'Connexion back-office réussie');
                
                // Redirection selon le rôle
                return redirect()->route($this->getDashboardRoute($user->role));
            } else {
                return back()->with('error', 'Accès refusé. Vous n\'avez pas les droits d\'accès au back-office.');
            }
        }

        return back()->with('error', 'Email ou mot de passe incorrect.');
    }

    /**
     * Obtenir la route du dashboard selon le rôle
     */
    protected function getDashboardRoute(string $role): string
    {
        return match($role) {
            'super_admin', 'admin', 'sub_admin' => 'admin.dashboard',
            'comptabilite' => 'comptabilite.dashboard',
            'accountant' => 'accountant.dashboard',
            'marketing' => 'marketing.dashboard',
            'community_manager' => 'community.dashboard',
            'verifier' => 'verifier.dashboard',
            default => 'admin.dashboard',
        };
    }

    public function adminDashboard()
    {
        if (!Auth::check() || !RoleHelper::canAccessBackoffice(Auth::user()->role)) {
            return redirect()->route('admin.login');
        }

        return view('admin.dashboard');
    }

    public function logout(Request $request)
    {
        if (auth()->check()) {
            \App\Models\UserActivityLog::log('logout', 'Déconnexion');
        }
        
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect('/');
    }

    public function showMemberLogin()
    {
        return view('member.auth.login');
    }

    public function memberLogin(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required'
        ]);

        $user = User::where('email', $request->email)->first();

        if ($user && Hash::check($request->password, $user->password)) {
            // Vérifier si l'utilisateur peut accéder à l'espace membre (member, affiliate, user)
            if (RoleHelper::canAccessMemberArea($user->role)) {
                if (!$user->email_verified_at) {
                    return back()->with('error', 'Veuillez vérifier votre email avant de vous connecter. Vérifiez votre boîte mail pour le code de vérification.');
                }

                Auth::login($user);
                $request->session()->regenerate();
                
                \App\Models\UserActivityLog::log('login', 'Connexion membre réussie');
                
                return redirect()->route('member.dashboard');
            } else {
                return back()->with('error', 'Accès réservé aux membres.');
            }
        }

        return back()->with('error', 'Email ou mot de passe incorrect.');
    }

    public function showRegister()
    {
        return view('member.auth.register');
    }

    public function register(Request $request)
    {
        // Normaliser les données sensibles avant validation
        $request->merge([
            'sponsor_code' => $request->filled('sponsor_code')
                ? strtoupper(trim($request->input('sponsor_code')))
                : null,
        ]);

        $validated = $request->validate([
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'country' => 'required|string|max:255',
            'country_code' => 'required|string|max:10',
            'city' => 'required|string|max:255',
            'address' => 'required|string',
            'phone' => 'required|string|max:20',
            'whatsapp' => 'nullable|string|max:20',
            'password' => 'required|string|min:6|confirmed',
            'sponsor_code' => 'nullable|exists:users,member_code'
        ], [
            'sponsor_code.exists' => 'Le code membre saisi est introuvable.'
        ]);

        $memberCode = 'MBR' . rand(1000, 9999);
        while (User::where('member_code', $memberCode)->exists()) {
            $memberCode = 'MBR' . rand(1000, 9999);
        }

        $sponsorId = null;
        $sponsor = null;
        if (!empty($validated['sponsor_code'])) {
            $sponsor = User::where('member_code', $validated['sponsor_code'])->first();
            $sponsorId = $sponsor ? $sponsor->id : null;
        }

        $verificationCode = str_pad(rand(0, 999999), 6, '0', STR_PAD_LEFT);
        
        $fullName = $validated['first_name'] . ' ' . $validated['last_name'];

        $user = User::create([
            'name' => $fullName,
            'first_name' => $validated['first_name'],
            'last_name' => $validated['last_name'],
            'email' => $validated['email'],
            'country' => $validated['country'],
            'country_code' => $validated['country_code'],
            'city' => $validated['city'],
            'address' => $validated['address'],
            'phone' => $validated['phone'],
            'whatsapp' => $validated['whatsapp'] ?? null,
            'password' => Hash::make($validated['password']),
            'role' => 'member',
            'member_code' => $memberCode,
            'sponsor_id' => $sponsorId,
            'is_active' => true,
            'email_verification_code' => $verificationCode,
            'verification_code_sent_at' => now(),
        ]);

        // Envoi de l'email de vérification
        $emailSent = EmailService::sendVerificationCode($user->email, $verificationCode, $user->name);

        if (!$emailSent) {
            // Si l'email n'est pas envoyé, on peut logger l'erreur mais on continue le processus
            \Illuminate\Support\Facades\Log::error("Échec de l'envoi de l'email de vérification pour: " . $user->email);
        }

        // Notification au parrain
        if ($sponsor) {
            EmailService::sendReferralNotification($sponsor->email, [
                'sponsor_name' => $sponsor->name,
                'new_member_name' => $user->name,
                'new_member_code' => $user->member_code,
                'registration_date' => now()->format('d/m/Y à H:i')
            ]);
        }

        // Créer l'adresse par défaut de l'utilisateur
        \App\Models\UserAddress::create([
            'user_id' => $user->id,
            'label' => 'Adresse principale',
            'full_name' => $fullName,
            'phone' => $validated['phone'],
            'country' => $validated['country'],
            'city' => $validated['city'],
            'district' => null,
            'address' => $validated['address'],
            'is_default' => true,
        ]);

        // Stocker user_id en session persistante (pas flash data)
        $request->session()->put('user_id', $user->id);

        return redirect()->route('member.verify-email')->with('success', 'Inscription réussie ! Un code de vérification a été envoyé à votre email.');
    }

    public function showVerifyEmail(Request $request)
    {
        $userId = session('user_id');
        
        if (!$userId) {
            return redirect()->route('member.register')->with('error', 'Veuillez d\'abord compléter votre inscription.');
        }

        $user = User::find($userId);
        if (!$user) {
            $request->session()->forget('user_id');
            return redirect()->route('member.register')->with('error', 'Utilisateur introuvable.');
        }

        return view('member.auth.verify-email', ['user' => $user]);
    }

    public function verifyEmail(Request $request)
    {
        $request->validate([
            'code' => 'required|string|size:6'
        ]);

        $userId = session('user_id');
        if (!$userId) {
            return redirect()->route('member.register')->with('error', 'Session expirée. Veuillez vous réinscrire.');
        }

        $user = User::find($userId);

        if (!$user) {
            $request->session()->forget('user_id');
            return redirect()->route('member.register')->with('error', 'Utilisateur non trouvé.');
        }

        if ($user->email_verified_at) {
            $request->session()->forget('user_id');
            return redirect()->route('member.login')->with('success', 'Email déjà vérifié. Vous pouvez vous connecter.');
        }

        if ($user->email_verification_code !== $request->code) {
            return back()->with('error', 'Code de vérification incorrect.');
        }

        if (Carbon::parse($user->verification_code_sent_at)->addMinutes(15)->isPast()) {
            return back()->with('error', 'Code de vérification expiré. Demandez un nouveau code.');
        }

        $user->update([
            'email_verified_at' => now(),
            'email_verification_code' => null,
            'verification_code_sent_at' => null
        ]);

        // Envoyer l'email de bienvenue avec le guide complet
        NotificationService::sendWelcomeMemberEmail($user);

        $request->session()->forget('user_id');

        return redirect()->route('member.verify-success');
    }

    public function resendVerificationCode(Request $request)
    {
        $userId = session('user_id');
        if (!$userId) {
            return redirect()->route('member.register')->with('error', 'Session expirée. Veuillez vous réinscrire.');
        }

        $user = User::find($userId);

        if (!$user) {
            $request->session()->forget('user_id');
            return redirect()->route('member.register')->with('error', 'Utilisateur non trouvé.');
        }

        if ($user->email_verified_at) {
            $request->session()->forget('user_id');
            return redirect()->route('member.login')->with('success', 'Email déjà vérifié.');
        }

        $verificationCode = str_pad(rand(0, 999999), 6, '0', STR_PAD_LEFT);

        $user->update([
            'email_verification_code' => $verificationCode,
            'verification_code_sent_at' => now()
        ]);

        EmailService::sendVerificationCode($user->email, $verificationCode, $user->name);

        return back()->with('success', 'Un nouveau code de vérification a été envoyé à votre email.');
    }
    public function showSellerLogin()
    {
        return view('seller.auth.login');
    }

    public function sellerLogin(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required'
        ]);

        $user = User::where('email', $request->email)->first();

        if ($user && Hash::check($request->password, $user->password)) {
            $seller = $user->seller;
            
            if (!$seller) {
                return back()->with('error', 'Aucun compte vendeur associé à cet email.');
            }
            
            if (!$user->email_verified_at) {
                return back()->with('error', 'Veuillez vérifier votre email avant de vous connecter.');
            }

            if (!$seller->is_active || $seller->kyc_status !== 'approved') {
                return back()->with('error', 'Votre compte vendeur n\'est pas encore approuvé.');
            }

            Auth::login($user);
            $request->session()->regenerate();
            
            return redirect()->route('seller.dashboard');
        }

        return back()->with('error', 'Email ou mot de passe incorrect.');
    }

    public function showSellerRegister()
    {
        return view('seller.auth.register');
    }

    public function sellerRegister(Request $request)
    {
        $validated = $request->validate([
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'phone' => 'required|string|max:20',
            'shop_name' => 'required|string|max:255',
            'category' => 'required|string',
            'description' => 'nullable|string',
            'country' => 'required|string|max:255',
            'city' => 'required|string|max:255',
            'address' => 'required|string',
            'password' => 'required|string|min:6|confirmed',
            // Documents KYC (optionnels lors de l'inscription)
            'business_type' => 'nullable|string|in:individual,company,association',
            'business_name' => 'nullable|string|max:255',
            'business_registration' => 'nullable|string|max:100',
            'tax_id' => 'nullable|string|max:100',
            'id_document' => 'nullable|file|mimes:jpg,jpeg,png,pdf|max:5120',
            'address_proof' => 'nullable|file|mimes:jpg,jpeg,png,pdf|max:5120',
            'business_document' => 'nullable|file|mimes:jpg,jpeg,png,pdf|max:5120',
            'business_photo' => 'nullable|file|mimes:jpg,jpeg,png|max:5120',
            // Conditions d'utilisation
            'terms' => 'required|accepted',
        ], [
            'terms.required' => 'Vous devez accepter les conditions generales de vente.',
            'terms.accepted' => 'Vous devez accepter les conditions generales de vente.',
        ]);

        $memberCode = 'SLR' . rand(1000, 9999);
        while (User::where('member_code', $memberCode)->exists()) {
            $memberCode = 'SLR' . rand(1000, 9999);
        }

        $user = User::create([
            'name' => $validated['first_name'] . ' ' . $validated['last_name'],
            'first_name' => $validated['first_name'],
            'last_name' => $validated['last_name'],
            'email' => $validated['email'],
            'phone' => $validated['phone'],
            'country' => $validated['country'],
            'city' => $validated['city'],
            'address' => $validated['address'],
            'password' => Hash::make($validated['password']),
            'role' => 'user',
            'member_code' => $memberCode,
            'is_active' => true,
            'email_verified_at' => now(),
        ]);

        $slug = \Illuminate\Support\Str::slug($validated['shop_name']);
        
        // Créer le seller d'abord pour avoir l'ID
        $seller = \App\Models\Seller::create([
            'user_id' => $user->id,
            'shop_name' => $validated['shop_name'],
            'shop_slug' => $slug,
            'category' => $validated['category'],
            'description' => $validated['description'] ?? '',
            'phone' => $validated['phone'],
            'email' => $validated['email'],
            'address' => $validated['address'],
            'city' => $validated['city'],
            'country' => $validated['country'],
            'business_type' => $validated['business_type'] ?? 'individual',
            'business_name' => $validated['business_name'] ?? null,
            'business_registration' => $validated['business_registration'] ?? null,
            'tax_id' => $validated['tax_id'] ?? null,
            'is_active' => false,
            'kyc_status' => $request->hasFile('id_document') ? 'submitted' : 'pending', // pending si pas de documents
            'commission_rate' => 10,
            'kyc_submitted_at' => $request->hasFile('id_document') ? now() : null,
        ]);
        
        // Upload des documents KYC (si fournis) - Avec copie vers public/storage pour cPanel
        $idDocPath = null;
        if ($request->hasFile('id_document')) {
            $idDocPath = $this->storeKycDocument($request->file('id_document'), $seller->id, 'id');
        }
        
        $addressProofPath = null;
        if ($request->hasFile('address_proof')) {
            $addressProofPath = $this->storeKycDocument($request->file('address_proof'), $seller->id, 'address');
        }
            
        $businessDocPath = null;
        if ($request->hasFile('business_document')) {
            $businessDocPath = $this->storeKycDocument($request->file('business_document'), $seller->id, 'business');
        }
            
        $businessPhotoPath = null;
        if ($request->hasFile('business_photo')) {
            $businessPhotoPath = $this->storeKycDocument($request->file('business_photo'), $seller->id, 'photo');
        }
        
        // Mettre à jour le seller avec les chemins des documents
        $seller->update([
            'id_document' => $idDocPath,
            'address_proof' => $addressProofPath,
            'business_document' => $businessDocPath,
            'business_photo' => $businessPhotoPath,
        ]);

        \App\Models\Wallet::create([
            'user_id' => $user->id,
            'balance' => 0,
            'pending_balance' => 0,
            'currency' => 'XOF',
        ]);

        // Créer l'adresse par défaut du vendeur
        \App\Models\UserAddress::create([
            'user_id' => $user->id,
            'label' => 'Adresse boutique',
            'full_name' => $validated['first_name'] . ' ' . $validated['last_name'],
            'phone' => $validated['phone'],
            'country' => $validated['country'],
            'city' => $validated['city'],
            'district' => null,
            'address' => $validated['address'],
            'is_default' => true,
        ]);

        return redirect()->route('seller.login')->with('success', 'Inscription réussie ! Vos documents sont en cours de vérification. Vous recevrez une notification par email.');
    }

    public function sellerDashboard()
    {
        if (!Auth::check() || !Auth::user()->seller) {
            return redirect()->route('seller.login');
        }

        $seller = Auth::user()->seller;
        return view('seller.dashboard', compact('seller'));
    }

    /**
     * Stocke un document KYC avec copie vers public/storage pour compatibilité cPanel
     * 
     * @param \Illuminate\Http\UploadedFile $file
     * @param int $sellerId
     * @param string $type (id, address, business, photo)
     * @return string|null Chemin relatif du fichier
     */
    protected function storeKycDocument($file, int $sellerId, string $type): ?string
    {
        if (!$file) {
            return null;
        }

        // Nom lisible : timestamp_nomoriginal.ext
        $fileName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $file->getClientOriginalName());
        $relativePath = 'kyc/' . $sellerId . '/' . $type;
        $fullPath = $relativePath . '/' . $fileName;

        // 1. Stocker dans storage/app/public/
        $file->storeAs($relativePath, $fileName, 'public');

        // 2. Copier vers public/storage/ pour compatibilité cPanel (pas de lien symbolique)
        $publicDir = public_path('storage/' . $relativePath);
        if (!is_dir($publicDir)) {
            mkdir($publicDir, 0755, true);
        }

        $storagePath = storage_path('app/public/' . $fullPath);
        $publicPath = public_path('storage/' . $fullPath);

        if (file_exists($storagePath)) {
            copy($storagePath, $publicPath);
        }

        return $fullPath;
    }
}
