<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Seller;
use App\Models\User;
use Illuminate\Http\Request;
use App\Services\NotificationService;

class SellerController extends Controller
{
    public function index(Request $request)
    {
        $query = Seller::with('user');

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

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('shop_name', 'like', "%{$search}%")
                  ->orWhereHas('user', function($q2) use ($search) {
                      $q2->where('name', 'like', "%{$search}%")
                         ->orWhere('email', 'like', "%{$search}%");
                  });
            });
        }

        $sellers = $query->latest()->paginate(20);
        return view('admin.sellers.index', compact('sellers'));
    }

    public function show(Seller $seller)
    {
        $seller->load(['user', 'products']);
        return view('admin.sellers.show', compact('seller'));
    }

    public function approveKyc(Seller $seller)
    {
        $seller->update([
            'kyc_status' => 'approved',
            'kyc_approved_at' => now(),
            'is_active' => true,
            'is_verified' => true
        ]);

        $seller->user->update(['role' => 'seller']);

        // Notification au seller
        NotificationService::sellerKycStatus($seller->user_id, 'approved');

        return redirect()->route('admin.sellers.show', $seller)
            ->with('success', 'KYC approuvé avec succès');
    }

    public function rejectKyc(Request $request, Seller $seller)
    {
        $request->validate(['rejection_reason' => 'required|string|max:500']);

        $seller->update([
            'kyc_status' => 'rejected',
            'kyc_rejection_reason' => $request->rejection_reason,
            'is_active' => false
        ]);

        // Notification au seller
        NotificationService::sellerKycStatus($seller->user_id, 'rejected', $request->rejection_reason);

        return redirect()->route('admin.sellers.show', $seller)
            ->with('success', 'KYC rejeté');
    }

    public function toggleActive(Seller $seller)
    {
        $seller->update(['is_active' => !$seller->is_active]);
        
        // Notification au seller
        NotificationService::sellerAccountStatus($seller->user_id, $seller->is_active);
        
        return redirect()->back()
            ->with('success', $seller->is_active ? 'Vendeur activé' : 'Vendeur désactivé');
    }

    public function toggleFeatured(Seller $seller)
    {
        $seller->update(['is_featured' => !$seller->is_featured]);
        
        // Notification au seller
        NotificationService::sellerFeatured($seller->user_id, $seller->is_featured);
        
        return redirect()->back()
            ->with('success', $seller->is_featured ? 'Vendeur mis en avant' : 'Mise en avant retirée');
    }

    public function updateCommission(Request $request, Seller $seller)
    {
        $request->validate(['commission_rate' => 'required|numeric|min:0|max:100']);
        $seller->update(['commission_rate' => $request->commission_rate]);
        
        // Notification au seller
        NotificationService::sellerCommissionRateChanged($seller->user_id, $request->commission_rate);
        
        return redirect()->back()->with('success', 'Commission mise à jour');
    }

    public function create()
    {
        $users = User::whereDoesntHave('seller')->where('role', '!=', 'admin')->get();
        return view('admin.sellers.create', compact('users'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'user_id' => 'nullable|exists:users,id',
            'email' => 'required_without:user_id|email|unique:users,email',
            'name' => 'required_without:user_id|string|max:255',
            'password' => 'required_without:user_id|string|min:6',
            'shop_name' => 'required|string|max:255',
            'shop_description' => 'nullable|string',
            'category' => 'nullable|string|max:100',
            'phone' => 'nullable|string|max:20',
            'city' => 'nullable|string|max:255',
            'address' => 'nullable|string',
            'commission_rate' => 'required|numeric|min:0|max:100',
            'is_active' => 'boolean',
            'kyc_status' => 'required|in:pending,submitted,approved,rejected',
            // Business info
            'business_type' => 'nullable|string|in:individual,company,association',
            'business_name' => 'nullable|string|max:255',
            'business_registration' => 'nullable|string|max:100',
            // Documents
            'id_document' => 'nullable|file|mimes:jpg,jpeg,png,pdf|max:5120',
            'address_proof' => 'nullable|file|mimes:jpg,jpeg,png,pdf|max:5120',
        ]);

        // Si KYC approuvé, activer automatiquement
        $isActive = $validated['is_active'] ?? false;
        if ($validated['kyc_status'] === 'approved') {
            $isActive = true;
        }

        if (!$request->user_id) {
            $memberCode = 'SLR' . rand(1000, 9999);
            while (User::where('member_code', $memberCode)->exists()) {
                $memberCode = 'SLR' . rand(1000, 9999);
            }
            
            $user = User::create([
                'name' => $validated['name'],
                'email' => $validated['email'],
                'password' => bcrypt($validated['password']),
                'role' => 'seller',
                'member_code' => $memberCode,
                'is_active' => true,
                'email_verified_at' => now()
            ]);
            $validated['user_id'] = $user->id;
        } else {
            User::find($validated['user_id'])->update(['role' => 'seller']);
        }

        $slug = \Illuminate\Support\Str::slug($validated['shop_name']);
        
        $seller = Seller::create([
            'user_id' => $validated['user_id'],
            'shop_name' => $validated['shop_name'],
            'shop_slug' => $slug,
            'description' => $validated['shop_description'] ?? null,
            'category' => $validated['category'] ?? null,
            'phone' => $validated['phone'] ?? null,
            'city' => $validated['city'] ?? null,
            'address' => $validated['address'] ?? null,
            'commission_rate' => $validated['commission_rate'],
            'is_active' => $isActive,
            'kyc_status' => $validated['kyc_status'],
            'is_verified' => $validated['kyc_status'] === 'approved',
            'business_type' => $validated['business_type'] ?? null,
            'business_name' => $validated['business_name'] ?? null,
            'business_registration' => $validated['business_registration'] ?? null,
            'kyc_approved_at' => $validated['kyc_status'] === 'approved' ? now() : null,
        ]);

        // Upload des documents si fournis - Nom lisible : timestamp_nomoriginal.ext
        if ($request->hasFile('id_document')) {
            $idDoc = $request->file('id_document');
            $idDocName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $idDoc->getClientOriginalName());
            $idDocPath = $idDoc->storeAs('kyc/' . $seller->id . '/id', $idDocName, 'public');
            $seller->update(['id_document' => $idDocPath]);
        }
        
        if ($request->hasFile('address_proof')) {
            $addressDoc = $request->file('address_proof');
            $addressName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $addressDoc->getClientOriginalName());
            $addressProofPath = $addressDoc->storeAs('kyc/' . $seller->id . '/address', $addressName, 'public');
            $seller->update(['address_proof' => $addressProofPath]);
        }

        // Créer le wallet
        \App\Models\Wallet::firstOrCreate(
            ['user_id' => $validated['user_id']],
            ['balance' => 0, 'pending_balance' => 0, 'currency' => 'XOF']
        );

        return redirect()->route('admin.sellers.index')
            ->with('success', 'Seller créé avec succès' . ($isActive ? ' et activé' : ''));
    }

    public function edit(Seller $seller)
    {
        $seller->load('user');
        return view('admin.sellers.edit', compact('seller'));
    }

    public function update(Request $request, Seller $seller)
    {
        $validated = $request->validate([
            'shop_name' => 'required|string|max:255',
            'shop_description' => 'nullable|string',
            'phone' => 'nullable|string|max:20',
            'address' => 'nullable|string',
            'commission_rate' => 'required|numeric|min:0|max:100',
            'is_active' => 'boolean',
            'is_featured' => 'boolean',
            'kyc_status' => 'required|in:pending,approved,rejected'
        ]);

        $seller->update([
            'shop_name' => $validated['shop_name'],
            'shop_description' => $validated['shop_description'] ?? null,
            'phone' => $validated['phone'] ?? null,
            'address' => $validated['address'] ?? null,
            'commission_rate' => $validated['commission_rate'],
            'is_active' => $validated['is_active'] ?? false,
            'is_featured' => $validated['is_featured'] ?? false,
            'kyc_status' => $validated['kyc_status'],
            'is_verified' => $validated['kyc_status'] === 'approved'
        ]);

        return redirect()->route('admin.sellers.index')
            ->with('success', 'Seller mis a jour');
    }

    public function destroy(Seller $seller)
    {
        $seller->user->update(['role' => 'member']);
        $seller->delete();
        return redirect()->route('admin.sellers.index')
            ->with('success', 'Seller supprime');
    }
}
