<?php

namespace App\Services;

use App\Models\User;
use App\Models\Seller;
use App\Models\Product;
use App\Models\Order;
use App\Models\Setting;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class SellerService
{
    public function registerSeller(User $user, array $data)
    {
        if ($user->seller) {
            throw new \Exception('Cet utilisateur est déjà un vendeur');
        }

        $seller = Seller::create([
            'user_id' => $user->id,
            'shop_name' => $data['shop_name'],
            'shop_slug' => Str::slug($data['shop_name']),
            'description' => $data['description'] ?? null,
            'phone' => $data['phone'] ?? null,
            'email' => $data['email'] ?? $user->email,
            'address' => $data['address'] ?? null,
            'city' => $data['city'] ?? null,
            'country' => $data['country'] ?? null,
            'kyc_status' => 'pending',
            'commission_rate' => floatval(Setting::get('default_seller_commission', 10)),
        ]);

        Log::info('Nouveau vendeur inscrit', [
            'seller_id' => $seller->id,
            'user_id' => $user->id,
        ]);

        return $seller;
    }

    public function submitKyc(Seller $seller, array $documents)
    {
        $uploadedDocs = [];

        foreach ($documents as $type => $file) {
            if ($file) {
                // Nom lisible : timestamp_type_nomoriginal.ext
                $fileName = time() . '_' . $type . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $file->getClientOriginalName());
                $path = $file->storeAs("kyc/{$seller->id}", $fileName, 'public');
                $uploadedDocs[$type] = $path;
            }
        }

        $seller->update([
            'kyc_documents' => $uploadedDocs,
            'kyc_status' => 'submitted',
        ]);

        Log::info('Documents KYC soumis', [
            'seller_id' => $seller->id,
            'documents' => array_keys($uploadedDocs),
        ]);

        return $seller;
    }

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

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

        Log::info('KYC vendeur approuvé', [
            'seller_id' => $seller->id,
            'approved_by' => $approvedBy,
        ]);

        try {
            $notificationService = new NotificationService();
            $notificationService->send(
                $seller->user,
                'kyc_approved',
                'Votre boutique est approuvée',
                'Félicitations ! Votre demande de vendeur a été approuvée. Vous pouvez maintenant ajouter vos produits.',
                [],
                '/seller/dashboard'
            );
        } catch (\Exception $e) {
            Log::error('Erreur notification KYC: ' . $e->getMessage());
        }

        return $seller;
    }

    public function rejectKyc(Seller $seller, $reason)
    {
        $seller->update([
            'kyc_status' => 'rejected',
            'kyc_rejection_reason' => $reason,
        ]);

        Log::info('KYC vendeur rejeté', [
            'seller_id' => $seller->id,
            'reason' => $reason,
        ]);

        try {
            $notificationService = new NotificationService();
            $notificationService->send(
                $seller->user,
                'kyc_rejected',
                'Demande de vendeur rejetée',
                "Votre demande a été rejetée pour la raison suivante: {$reason}",
                [],
                '/seller/kyc'
            );
        } catch (\Exception $e) {
            Log::error('Erreur notification rejet KYC: ' . $e->getMessage());
        }

        return $seller;
    }

    public function getSellerStats(Seller $seller)
    {
        $totalSales = Order::whereHas('items', function ($q) use ($seller) {
            $q->whereHas('product', function ($pq) use ($seller) {
                $pq->where('seller_id', $seller->id);
            });
        })->where('status', 'delivered')->sum('total_amount');

        $totalOrders = Order::whereHas('items', function ($q) use ($seller) {
            $q->whereHas('product', function ($pq) use ($seller) {
                $pq->where('seller_id', $seller->id);
            });
        })->count();

        $pendingOrders = Order::whereHas('items', function ($q) use ($seller) {
            $q->whereHas('product', function ($pq) use ($seller) {
                $pq->where('seller_id', $seller->id);
            });
        })->whereIn('status', ['pending', 'confirmed', 'processing'])->count();

        $totalProducts = $seller->products()->count();
        $activeProducts = $seller->products()->where('is_active', true)->count();

        return [
            'total_sales' => $totalSales,
            'total_orders' => $totalOrders,
            'pending_orders' => $pendingOrders,
            'total_products' => $totalProducts,
            'active_products' => $activeProducts,
            'rating' => $seller->rating,
            'total_reviews' => $seller->total_reviews,
            'commission_rate' => $seller->commission_rate,
        ];
    }

    public function addProduct(Seller $seller, array $data)
    {
        if (!$seller->canSell()) {
            throw new \Exception('Votre boutique n\'est pas encore approuvée');
        }

        $requireApproval = Setting::get('require_product_approval', true);

        $product = Product::create([
            'seller_id' => $seller->id,
            'category_id' => $data['category_id'],
            'name' => $data['name'],
            'slug' => Str::slug($data['name']) . '-' . uniqid(),
            'description' => $data['description'] ?? null,
            'price' => $data['price'],
            'compare_price' => $data['compare_price'] ?? null,
            'stock' => $data['stock'] ?? 0,
            'images' => $data['images'] ?? [],
            'is_active' => !$requireApproval,
            'approval_status' => $requireApproval ? 'pending' : 'approved',
            'mlm_commission_rate' => $data['mlm_commission_rate'] ?? 5,
        ]);

        Log::info('Nouveau produit ajouté par vendeur', [
            'product_id' => $product->id,
            'seller_id' => $seller->id,
        ]);

        return $product;
    }

    public function approveProduct(Product $product)
    {
        $product->update([
            'is_active' => true,
            'approval_status' => 'approved',
            'is_approved' => true,
        ]);

        Log::info('Produit approuvé', ['product_id' => $product->id]);

        return $product;
    }

    public function rejectProduct(Product $product, $reason)
    {
        $product->update([
            'approval_status' => 'rejected',
            'is_approved' => false,
        ]);

        Log::info('Produit rejeté', [
            'product_id' => $product->id,
            'reason' => $reason,
        ]);

        return $product;
    }

    public function calculateSellerRevenue(Seller $seller, Order $order)
    {
        $sellerItems = $order->items()->whereHas('product', function ($q) use ($seller) {
            $q->where('seller_id', $seller->id);
        })->get();

        $subtotal = $sellerItems->sum('subtotal');
        $commission = ($subtotal * $seller->commission_rate) / 100;
        $netRevenue = $subtotal - $commission;

        return [
            'subtotal' => $subtotal,
            'commission' => $commission,
            'commission_rate' => $seller->commission_rate,
            'net_revenue' => $netRevenue,
        ];
    }

    public function getTopSellers($limit = 10)
    {
        return Seller::active()
            ->verified()
            ->orderByDesc('total_sales')
            ->limit($limit)
            ->get();
    }

    public function getFeaturedSellers($limit = 6)
    {
        return Seller::active()
            ->verified()
            ->where('is_featured', true)
            ->inRandomOrder()
            ->limit($limit)
            ->get();
    }

    public function searchSellers($query, $filters = [])
    {
        $sellers = Seller::active()->verified();

        if ($query) {
            $sellers->where(function ($q) use ($query) {
                $q->where('shop_name', 'like', "%{$query}%")
                  ->orWhere('description', 'like', "%{$query}%");
            });
        }

        if (!empty($filters['country'])) {
            $sellers->where('country', $filters['country']);
        }

        if (!empty($filters['min_rating'])) {
            $sellers->where('rating', '>=', $filters['min_rating']);
        }

        return $sellers->orderByDesc('rating')->paginate(20);
    }
}
