<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use App\Models\Marketplace\Order;
use App\Models\Marketplace\Store;
use Illuminate\Support\Facades\DB;
use App\Models\Marketplace\Product;
use Illuminate\Support\Facades\Auth;
use App\Http\Resources\OrderResource;
use App\Http\Resources\StoreResource;
use App\Http\Resources\ProductResource;
use App\Models\Marketplace\StoreReview;
use Illuminate\Support\Facades\Storage;
use App\Models\Marketplace\OrderProduct;
use App\Models\Marketplace\ProductMedia;
use App\Models\Marketplace\SavedProduct;
use App\Models\Marketplace\ProductReview;
use Illuminate\Support\Facades\Validator;
use App\Models\Marketplace\ProductCategory;
use App\Models\Post;
use App\Models\PostMedia;
use Carbon\Carbon;

class MarketplaceController extends Controller
{
    /**
     * Get marketplace dashboard stats
     */
    public function getDashboardStats()
    {
        try {
            $stats = [
                'total_products' => Product::where('status', 'active')->count(),
                'total_shops' => Store::where('status', 'active')->count(),
                'total_orders' => Auth::check() ?
                    OrderProduct::where('buyer_id', Auth::id())->count() : 0,
                'saved_items' => Auth::check() ?
                    SavedProduct::where('user_id', Auth::id())->count() : 0,

                'category_counts' => ProductCategory::withCount(['products' => function ($query) {
                    $query->where('status', 'active');
                }])->get(),

                'condition_counts' => Product::where('status', 'active')
                    ->select('type', DB::raw('count(*) as count'))
                    ->groupBy('type')
                    ->pluck('count', 'type'),

                'price_ranges' => [
                    'under_100' => Product::where('status', 'active')
                        ->where('price', '<', 100)
                        ->count(),
                    '100_to_500' => Product::where('status', 'active')
                        ->whereBetween('price', [100, 500])
                        ->count(),
                    'over_500' => Product::where('status', 'active')
                        ->where('price', '>', 500)
                        ->count()
                ]
            ];

            return response()->json([
                'status' => 200,
                'message' => 'Stats fetched successfully',
                'data' => $stats
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error fetching stats',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get filtered products with enhanced search
     */
    public function getProducts(Request $request)
    {
        try {
            $query = Product::with(['category', 'media', 'user', 'store'])
                ->where('status', 'active');

            // Apply search filter
            if ($request->filled('search')) {
                $search = $request->input('search');
                $query->where(function ($q) use ($search) {
                    $q->where('name', 'LIKE', "%{$search}%")
                        ->orWhere('description', 'LIKE', "%{$search}%")
                        ->orWhereHas('category', function ($q) use ($search) {
                            $q->where('name', 'LIKE', "%{$search}%");
                        });
                });
            }

            // Apply category filter
            if ($request->filled('category_id')) {
                $query->where('category_id', $request->category_id);
            }

            // Apply store filter
            if ($request->filled('store_id')) {
                $query->where('store_id', $request->store_id);
            }

            // Apply location filter
            if ($request->filled('location')) {
                $query->where('location', 'LIKE', "%{$request->location}%");
            }

            // Apply price range filter
            if ($request->filled('min_price')) {
                $query->where('price', '>=', $request->min_price);
            }
            if ($request->filled('max_price')) {
                $query->where('price', '<=', $request->max_price);
            }

            // Apply condition filter
            if ($request->filled('type')) {
                $query->whereIn('type', (array)$request->type);
            }

            // Apply seller type filter
            if ($request->filled('seller_type')) {
                $query->whereHas('user', function ($q) use ($request) {
                    $q->where('account_type', $request->seller_type);
                });
            }

            // Apply in-stock filter
            if ($request->filled('in_stock') && $request->in_stock) {
                $query->inStock();
            }

            // Apply on-sale filter
            if ($request->filled('on_sale') && $request->on_sale) {
                $query->onSale();
            }

            // Apply sorting
            $sortBy = $request->input('sort_by', 'created_at');
            $sortOrder = $request->input('sort_order', 'desc');

            switch ($sortBy) {
                case 'price':
                    $query->orderBy('price', $sortOrder);
                    break;
                case 'popularity':
                    $query->orderBy('views', $sortOrder);
                    break;
                case 'rating':
                    $query->withAvg('reviews', 'rating')
                        ->orderBy('reviews_avg_rating', $sortOrder);
                    break;
                default:
                    $query->orderBy($sortBy, $sortOrder);
            }

            // Apply pagination
            $limit = $request->input('limit', 12);
            $offset = $request->input('offset', 0);

            $total = $query->count();
            $products = $query->skip($offset)->take($limit)->get();

            return response()->json([
                'status' => 200,
                'message' => 'Products fetched successfully',
                'data' => ProductResource::collection($products),
                'meta' => [
                    'total' => $total,
                    'offset' => $offset,
                    'limit' => $limit,
                    'has_more' => ($offset + $limit) < $total
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error fetching products',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get recommended products
     */
    public function getRecommendedProducts()
    {
        try {
            $query = Product::with(['category', 'media', 'user', 'store'])
                ->where('status', 'active');

            if (Auth::check()) {
                // Get user's interests based on views and saved items
                $userInterests = SavedProduct::where('user_id', Auth::id())
                    ->join('products', 'products.id', '=', 'saved_products.product_id')
                    ->pluck('category_id')
                    ->unique();

                if ($userInterests->isNotEmpty()) {
                    $query->whereIn('category_id', $userInterests);
                }

                // Exclude user's own products
                $query->where('user_id', '!=', Auth::id());
            }

            $products = $query->orderBy('views', 'desc')
                ->limit(6)
                ->get();

            return response()->json([
                'status' => 200,
                'message' => 'Recommended products fetched successfully',
                'data' => ProductResource::collection($products)
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error fetching recommended products',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Save/unsave product
     */
    public function toggleSaveProduct($id)
    {
        try {
            $exists = SavedProduct::where('user_id', Auth::id())
                ->where('product_id', $id)
                ->exists();

            if ($exists) {
                SavedProduct::where('user_id', Auth::id())
                    ->where('product_id', $id)
                    ->delete();
                $message = 'Product removed from saved items';
            } else {
                SavedProduct::create([
                    'user_id' => Auth::id(),
                    'product_id' => $id
                ]);
                $message = 'Product saved successfully';
            }

            return response()->json([
                'status' => 200,
                'message' => $message
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error saving product',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function addProduct(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|min:3|max:100',
            'description' => 'nullable|string|max:500',
            'category_id' => 'required|exists:product_categories,id',
            'store_id' => 'nullable|exists:stores,id',
            'price' => 'required|numeric|min:0',
            'currency' => 'required|string|max:10',
            'location' => 'required|string|max:255',
            'type' => 'required|string|max:50',
            'units' => 'nullable|integer|min:1',
            'stock_quantity' => 'nullable|integer|min:0',
            'sku' => 'nullable|string|max:50',
            'shipping_cost' => 'nullable|numeric|min:0',
            'tax_rate' => 'nullable|numeric|min:0',
            'discount_percentage' => 'nullable|numeric|min:0|max:100',
            'media.*' => 'nullable|image|max:5120',
            'specifications' => 'nullable|array',
            'warranty_info' => 'nullable|string|max:500',
        ]);

        try {
            $store = null;
            // If store_id not provided, check if user has a store
            if (empty($validated['store_id'])) {
                $store = Store::where('user_id', Auth::id())->first();
                if ($store) {
                    $validated['store_id'] = $store->id;
                }
            }

            $product = new Product();
            $product->user_id = Auth::id();
            $product->name = $validated['name'];
            $product->description = $validated['description'] ?? null;
            $product->category_id = $validated['category_id'];
            $product->store_id = $validated['store_id'] ?? null;
            $product->price = $validated['price'];
            $product->currency = $validated['currency'];
            $product->location = $validated['location'];
            $product->type = $validated['type'];
            $product->units = $validated['units'] ?? null;
            $product->stock_quantity = $validated['stock_quantity'] ?? null;
            $product->sku = $validated['sku'] ?? null;
            $product->shipping_cost = $validated['shipping_cost'] ?? null;
            $product->tax_rate = $validated['tax_rate'] ?? null;
            $product->discount_percentage = $validated['discount_percentage'] ?? null;
            $product->specifications = $validated['specifications'] ?? null;
            $product->warranty_info = $validated['warranty_info'] ?? null;
            $product->status = 'active';
            $product->save();

            // Handle media uploads
            if ($request->hasFile('media')) {
                $mediaFiles = $request->file('media');
                foreach ($mediaFiles as $index => $mediaFile) {
                    $path = $mediaFile->store('products', 'public');

                    $media = new ProductMedia();
                    $media->product_id = $product->id;
                    $media->file_path = $path;
                    $media->file_name = $mediaFile->getClientOriginalName();
                    $media->file_type = $mediaFile->getMimeType();
                    $media->file_size = $mediaFile->getSize();
                    $media->sort_order = $index;
                    $media->save();
                }
            }

            // Create a newsfeed post for this product
            $this->createProductPost($product, $request);

            return response()->json([
                'status' => 201,
                'message' => 'Product added successfully',
                'data' => new ProductResource($product->load(['category', 'media', 'user', 'store']))
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error adding product',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get all product categories
     */
    public function getCategories()
    {
        try {
            $categories = ProductCategory::withCount(['products' => function ($query) {
                $query->where('status', 'active');
            }])->get();

            return response()->json([
                'status' => 200,
                'message' => 'Categories fetched successfully',
                'data' => $categories
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'staus' => 500,
                'message' => 'Error fetching categories',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get product detail with related products
     */
    public function getProductDetail($id)
    {
        try {
            $product = Product::with(['category', 'media', 'user', 'store', 'reviews.user'])
                ->findOrFail($id);

            // Increment view count
            $product->increment('views');

            // Get similar products
            $similarProducts = Product::where('category_id', $product->category_id)
                ->where('id', '!=', $product->id)
                ->where('status', 'active')
                ->take(4)
                ->get();

            // Check if user has saved this product
            $isSaved = false;
            if (Auth::check()) {
                $isSaved = $product->isSavedBy(Auth::id());
            }

            return response()->json([
                'status' => 200,
                'message' => 'Product details fetched successfully',
                'data' => [
                    'product' => new ProductResource($product),
                    'similar_products' => ProductResource::collection($similarProducts),
                    'is_saved' => $isSaved
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error fetching product details',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Delete a product
     */
    public function deleteProduct($id)
    {
        try {
            $productModel = new Product();
            $product = $productModel->where(['product_id' => $id, 'user_id' => Auth::id()])->firstOrFail();
            if (!empty($prouct)) {
                $product->deleteProduct($product);
            }

            return response()->json([
                'status' => 200,
                'message' => 'Product deleted successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error deleting product',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get saved products for the authenticated user
     */
    public function getSavedProducts(Request $request)
    {
        try {
            $query = SavedProduct::where('user_id', Auth::id())
                ->with(['product' => function ($query) {
                    $query->with(['category', 'media', 'user', 'store']);
                }]);

            // Apply sorting
            $sortBy = $request->input('sort_by', 'created_at');
            $sortOrder = $request->input('sort_order', 'desc');
            $query->orderBy($sortBy, $sortOrder);

            // Apply pagination
            $limit = $request->input('limit', 12);
            $offset = $request->input('offset', 0);

            $total = $query->count();
            $savedProducts = $query->skip($offset)->take($limit)->get();

            $products = $savedProducts->pluck('product')->filter();

            return response()->json([
                'status' => 200,
                'message' => 'Saved products fetched successfully',
                'data' => ProductResource::collection($products),
                'meta' => [
                    'total' => $total,
                    'offset' => $offset,
                    'limit' => $limit,
                    'has_more' => ($offset + $limit) < $total
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error fetching saved products',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get user's own product listings
     */
    public function getUserProducts(Request $request)
    {
        try {
            $query = Product::where('user_id', Auth::id())
                ->with(['category', 'media', 'store']);

            // Apply status filter
            $status = $request->input('status', 'active');
            if ($status !== 'all') {
                $query->where('status', $status);
            }

            // Apply sorting
            $sortBy = $request->input('sort_by', 'created_at');
            $sortOrder = $request->input('sort_order', 'desc');
            $query->orderBy($sortBy, $sortOrder);

            // Apply pagination
            $limit = $request->input('limit', 12);
            $offset = $request->input('offset', 0);

            $total = $query->count();
            $products = $query->skip($offset)->take($limit)->get();

            return response()->json([
                'status' => 200,
                'message' => 'Your products fetched successfully',
                'data' => ProductResource::collection($products),
                'meta' => [
                    'total' => $total,
                    'offset' => $offset,
                    'limit' => $limit,
                    'has_more' => ($offset + $limit) < $total
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error fetching your products',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get marketplace messages for the authenticated user
     */
    public function getMarketplaceMessages(Request $request)
    {
        try {
            // This method would need to be implemented based on your messaging system
            // This is a placeholder implementation
            return response()->json([
                'status' => 200,
                'message' => 'Marketplace messages fetched successfully',
                'data' => []
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error fetching marketplace messages',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get all stores or filter by specific criteria
     */
    public function getStores(Request $request)
    {
        try {
            $query = Store::with('owner')
                ->where('status', 'active');

            // Apply search filter
            if ($request->filled('search')) {
                $search = $request->input('search');
                $query->where(function ($q) use ($search) {
                    $q->where('name', 'LIKE', "%{$search}%")
                        ->orWhere('description', 'LIKE', "%{$search}%");
                });
            }

            // Apply location filter
            if ($request->filled('location')) {
                $query->where('location', 'LIKE', "%{$request->location}%");
            }

            // Apply sorting
            $sortBy = $request->input('sort_by', 'created_at');
            $sortOrder = $request->input('sort_order', 'desc');

            switch ($sortBy) {
                case 'rating':
                    $query->orderBy('rating', $sortOrder);
                    break;
                case 'popularity':
                    $query->withCount('products')
                        ->orderBy('products_count', $sortOrder);
                    break;
                default:
                    $query->orderBy($sortBy, $sortOrder);
            }

            // Apply pagination
            $limit = $request->input('limit', 10);
            $offset = $request->input('offset', 0);

            $total = $query->count();
            $stores = $query->skip($offset)->take($limit)->get();

            return response()->json([
                'status' => 200,
                'message' => 'Stores fetched successfully',
                'data' => StoreResource::collection($stores),
                'meta' => [
                    'total' => $total,
                    'offset' => $offset,
                    'limit' => $limit,
                    'has_more' => ($offset + $limit) < $total
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error fetching stores',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get store detail with its products
     */
    public function getStoreDetail($id)
    {
        try {
            $store = Store::with(['owner', 'products' => function ($query) {
                $query->where('status', 'active')->with('media');
            }])->findOrFail($id);

            return response()->json([
                'status' => 200,
                'message' => 'Store details fetched successfully',
                'data' => [
                    'store' => new StoreResource($store),
                    'products' => ProductResource::collection($store->products)
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error fetching store details',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get user's orders
     */
    public function getUserOrders(Request $request)
    {
        try {
            $query = Order::with(['products.store', 'products.reviews'])
                ->where('user_id', Auth::id());

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

            // Apply sorting
            $sortBy = $request->input('sort_by', 'created_at');
            $sortOrder = $request->input('sort_order', 'desc');
            $query->orderBy($sortBy, $sortOrder);

            // Apply pagination
            $orders = $query->paginate($request->input('per_page', 10));

            return response()->json([
                'status' => 200,
                'message' => 'Orders fetched successfully',
                'data' => OrderResource::collection($orders),
                'meta' => [
                    'current_page' => $orders->currentPage(),
                    'last_page' => $orders->lastPage(),
                    'per_page' => $orders->perPage(),
                    'total' => $orders->total()
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error fetching orders',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Submit a product review
     */
    public function submitReview(Request $request)
    {
        $validated = $request->validate([
            'product_id' => 'required|exists:products,id',
            'order_id' => 'required|exists:orders,id',
            'rating' => 'required|integer|min:1|max:5',
            'comment' => 'required|string|max:500',
            'is_recommended' => 'boolean',
            'images.*' => 'nullable|image|max:5120',
        ]);

        try {
            // Verify that user purchased this product
            $orderProduct = OrderProduct::where('order_id', $validated['order_id'])
                ->where('product_id', $validated['product_id'])
                ->where('buyer_id', Auth::id())
                ->firstOrFail();

            // Check if already reviewed
            $existingReview = ProductReview::where('product_id', $validated['product_id'])
                ->where('user_id', Auth::id())
                ->where('order_id', $validated['order_id'])
                ->first();

            if ($existingReview) {
                return response()->json([
                    'status' => 400,
                    'message' => 'You have already reviewed this product'
                ], 400);
            }

            // Get product details
            $product = Product::findOrFail($validated['product_id']);

            $review = new ProductReview();
            $review->product_id = $validated['product_id'];
            $review->order_id = $validated['order_id'];
            $review->user_id = Auth::id();
            $review->store_id = $product->store_id;
            $review->rating = $validated['rating'];
            $review->comment = $validated['comment'];
            $review->is_recommended = $validated['is_recommended'] ?? true;
            $review->status = 'pending';

            // Handle image uploads
            if ($request->hasFile('images')) {
                $uploadedImages = [];
                foreach ($request->file('images') as $image) {
                    $path = $image->store('reviews', 'public');
                    $uploadedImages[] = $path;
                }
                $review->images = $uploadedImages;
            }

            $review->save();

            // Mark the order product as reviewed
            $orderProduct->is_reviewed = true;
            $orderProduct->save();

            return response()->json([
                'status' => 201,
                'message' => 'Review submitted successfully',
                'data' => $review
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error submitting review',
                'error' => $e->getMessage()
            ], 500);
        }
    }
    public function submitStoreReview(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'rating' => 'required',
            'comment' => 'nullable'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => 400,
                'message' => 'Validation error',
                'errors' => $validator->errors()
            ], 200);
        }
        $user  =  $request->user();
        $store = Store::find($request->store_id);
        if ($store->user_id == $user->id) {
            return response()->json([
                'status' => 400,
                'message' => 'can not store your own store',
            ],);
        }
        $storeReview = StoreReview::where('user_id', $user->id)->first();
        if (!empty($storeReview)) {
            return response()->json([
                'status' => 400,
                'message' => 'you already reviewd this store',
            ],);
        }

        $storeReview = new StoreReview();
        $storeReview->user_id = $user->id;
        $storeReview->user_id = $request->store_id;
        $storeReview->comment = $request->comment;
        $storeReview->save();
        return response()->json([
            'status' => 200,
            'message' => 'Store reviewed successfully',
        ],);
    }
    public function getStoreReviews(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => 400,
                'message' => 'Validation error',
                'errors' => $validator->errors()
            ], 200);
        }

        $limit = $request->limit ?? 10;
        $offset = $request->offset ?? 0;

        $storereviews = StoreReview::where('store_id', $request->store_id)->limit($limit)->offset($offset)->get();
        if (count($storereviews) > 0) {
            $userModel = new User();
            foreach ($storereviews as $review) {
                $review['user'] = $userModel->usershortInfo($review->user_id);
            }
            return response()->json([
                'status' => 200,
                'message' => 'review fetch successfully',
                'data' => $storereviews
            ],);
        }
    }

    /**
     * Create a post in the newsfeed for a newly created product
     */
    private function createProductPost(Product $product, Request $request): ?Post
    {
        // Prefer first product image as post media
        $firstMedia = $product->media()->orderBy('sort_order')->first();

        $post = Post::create([
            'post_type' => 'product',
            'user_id' => Auth::id(),
            'privacy_level' => 1, // Public by default for marketplace listings
            'post_text' => $this->generateProductPostText($product),
            'location' => $product->location,
            'media_type' => $firstMedia ? 1 : 0,
            'product_id' => $product->id,
            'post_category' => 'product',
            'status' => 1,
            'ip_address' => $request->ip(),
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now(),
        ]);

        if ($post && $firstMedia) {
            PostMedia::create([
                'post_id' => $post->id,
                'user_id' => Auth::id(),
                'image_or_video' => 1,
                'media_path' => $firstMedia->file_path,
            ]);
        }

        return $post;
    }

    /**
     * Generate the product announcement text for the post
     */
    private function generateProductPostText(Product $product): string
    {
        $pricePart = $product->price !== null ? number_format((float)$product->price, 2) . ' ' . ($product->currency ?? '') : '';
        $lines = [];
        $lines[] = "🛍️ New product listed: {$product->name}";
        if ($pricePart !== '') {
            $lines[] = "💵 Price: {$pricePart}";
        }
        if (!empty($product->location)) {
            $lines[] = "📍 Location: {$product->location}";
        }
        if (!empty($product->description)) {
            $lines[] = '';
            $lines[] = "📝 {$product->description}";
        }
        $lines[] = '';
        $lines[] = '#marketplace #product';
        return implode("\n", $lines);
    }

    /**
     * Create a new store
     */
    public function createStore(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:255|unique:stores',
                'description' => 'required|string',
                'logo' => 'nullable|image|max:2048',
                'banner' => 'nullable|image|max:2048',
                'email' => 'nullable|email',
                'phone' => 'nullable|string|max:20',
                'address' => 'nullable|string',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation error',
                    'errors' => $validator->errors()
                ], 422);
            }

            // Check if user already has a store
            $existingStore = Store::where('user_id', Auth::id())->first();
            if ($existingStore) {
                return response()->json([
                    'success' => false,
                    'message' => 'You already have a store'
                ], 400);
            }

            // Upload files if provided
            $logoPath = null;
            if ($request->hasFile('logo')) {
                $logoPath = storeMedia($request->file('logo'), 'logo');
            }

            $bannerPath = null;
            if ($request->hasFile('banner')) {
                $bannerPath = storeMedia($request->file('logo'), 'banners');
            }

            // Create store
            $store = Store::create([
                'user_id' => Auth::id(),
                'name' => $request->name,
                'description' => $request->description,
                'logo' => $logoPath,
                'banner' => $bannerPath,
                'email' => $request->email,
                'phone' => $request->phone,
                'address' => $request->address,
                'status' => 'active',
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Store created successfully',
                // 'data' => new StoreResource($store)
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create store: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Update existing store
     */
    public function updateStore(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:255|unique:stores,name,' . $request->id,
                'description' => 'required|string',
                'logo' => 'nullable|image|max:2048',
                'banner' => 'nullable|image|max:2048',
                'email' => 'nullable|email',
                'phone' => 'nullable|string|max:20',
                'address' => 'nullable|string',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation error',
                    'errors' => $validator->errors()
                ], 422);
            }

            // Find the store
            $store = Store::where('user_id', Auth::id())->first();

            if (!$store) {
                return response()->json([
                    'success' => false,
                    'message' => 'Store not found'
                ], 404);
            }

            // Upload files if provided
            if ($request->hasFile('logo')) {
                // Delete old logo if exists
                if ($store->logo && Storage::exists('public/' . $store->logo)) {
                    Storage::delete('public/' . $store->logo);
                }
                $store->logo = $request->file('logo')->store('marketplace/stores/logos', 'public');
            }

            if ($request->hasFile('banner')) {
                // Delete old banner if exists
                if ($store->banner && Storage::exists('public/' . $store->banner)) {
                    Storage::delete('public/' . $store->banner);
                }
                $store->banner = $request->file('banner')->store('marketplace/stores/banners', 'public');
            }

            // Update store data
            $store->name = $request->name;
            $store->description = $request->description;
            $store->email = $request->email;
            $store->phone = $request->phone;
            $store->address = $request->address;
            $store->save();

            return response()->json([
                'success' => true,
                'message' => 'Store updated successfully',
                'data' => new StoreResource($store)
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to update store: ' . $e->getMessage()
            ], 500);
        }
    }



    /**
     * Contact seller about a product
     */
    public function contactSeller(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'product_id' => 'required|exists:products,id',
                'message' => 'required|string|min:10',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation error',
                    'errors' => $validator->errors()
                ], 422);
            }

            $product = Product::findOrFail($request->product_id);

            // Check if user is trying to message themselves
            if ($product->user_id == Auth::id()) {
                return response()->json([
                    'success' => false,
                    'message' => 'You cannot message yourself'
                ], 400);
            }

            // Check if conversation already exists
            $conversation = MarketplaceConversation::where(function ($query) use ($product) {
                $query->where('seller_id', $product->user_id)
                    ->where('buyer_id', Auth::id())
                    ->where('product_id', $product->id);
            })->first();

            if (!$conversation) {
                // Create new conversation
                $conversation = MarketplaceConversation::create([
                    'seller_id' => $product->user_id,
                    'buyer_id' => Auth::id(),
                    'product_id' => $product->id,
                ]);
            }

            // Add message to conversation
            $message = MarketplaceMessage::create([
                'conversation_id' => $conversation->id,
                'sender_id' => Auth::id(),
                'message' => $request->message,
                'is_read' => false,
            ]);

            // Update conversation timestamp
            $conversation->touch();

            return response()->json([
                'success' => true,
                'message' => 'Message sent to seller',
                'data' => [
                    'conversation_id' => $conversation->id,
                    'message' => $message
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to contact seller: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get user conversations
     */
    public function getConversations()
    {
        try {
            $conversations = MarketplaceConversation::with(['lastMessage', 'product.media', 'seller', 'buyer'])
                ->where(function ($query) {
                    $query->where('buyer_id', Auth::id())
                        ->orWhere('seller_id', Auth::id());
                })
                ->orderBy('updated_at', 'desc')
                ->paginate(20);

            // Count unread messages
            foreach ($conversations as $conversation) {
                $conversation->unread_count = MarketplaceMessage::where('conversation_id', $conversation->id)
                    ->where('sender_id', '!=', Auth::id())
                    ->where('is_read', false)
                    ->count();
            }

            return response()->json([
                'success' => true,
                'data' => $conversations,
                'meta' => [
                    'current_page' => $conversations->currentPage(),
                    'last_page' => $conversations->lastPage(),
                    'per_page' => $conversations->perPage(),
                    'total' => $conversations->total()
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to get conversations: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get messages in a conversation
     */
    public function getMessages($conversationId)
    {
        try {
            // Ensure user is part of the conversation
            $conversation = MarketplaceConversation::where('id', $conversationId)
                ->where(function ($query) {
                    $query->where('buyer_id', Auth::id())
                        ->orWhere('seller_id', Auth::id());
                })
                ->firstOrFail();

            $messages = MarketplaceMessage::with('sender')
                ->where('conversation_id', $conversationId)
                ->orderBy('created_at', 'asc')
                ->get();

            // Mark messages as read
            MarketplaceMessage::where('conversation_id', $conversationId)
                ->where('sender_id', '!=', Auth::id())
                ->update(['is_read' => true]);

            return response()->json([
                'success' => true,
                'data' => [
                    'conversation' => $conversation,
                    'messages' => $messages
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to get messages: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Send a message in a conversation
     */
    public function sendMessage(Request $request, $conversationId)
    {
        try {
            $validator = Validator::make($request->all(), [
                'message' => 'required|string|min:1',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation error',
                    'errors' => $validator->errors()
                ], 422);
            }

            // Ensure user is part of the conversation
            $conversation = MarketplaceConversation::where('id', $conversationId)
                ->where(function ($query) {
                    $query->where('buyer_id', Auth::id())
                        ->orWhere('seller_id', Auth::id());
                })
                ->firstOrFail();

            // Create message
            $message = MarketplaceMessage::create([
                'conversation_id' => $conversationId,
                'sender_id' => Auth::id(),
                'message' => $request->message,
                'is_read' => false,
            ]);

            // Update conversation timestamp
            $conversation->touch();

            return response()->json([
                'success' => true,
                'message' => 'Message sent successfully',
                'data' => $message
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to send message: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Create a new order
     */
    public function createOrder(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'product_id' => 'required|exists:products,id',
                'quantity' => 'required|integer|min:1',
                'address' => 'required|array',
                'address.name' => 'required|string',
                'address.address_line_1' => 'required|string',
                'address.city' => 'required|string',
                'address.state' => 'required|string',
                'address.postal_status' => 'required|string',
                'address.country' => 'required|string',
                'address.phone' => 'required|string',
                'payment_method' => 'required|string|in:credit_card,paypal,wallet',
                'payment_details' => 'required_if:payment_method,credit_card,paypal',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation error',
                    'errors' => $validator->errors()
                ], 422);
            }

            // Get product details
            $product = Product::findOrFail($request->product_id);

            // Check if product is available
            if ($product->status !== 'active') {
                return response()->json([
                    'success' => false,
                    'message' => 'Product is not available for purchase'
                ], 400);
            }

            // Check if user is trying to buy their own product
            if ($product->user_id == Auth::id()) {
                return response()->json([
                    'success' => false,
                    'message' => 'You cannot purchase your own product'
                ], 400);
            }

            // Calculate total amount
            $totalAmount = $product->price * $request->quantity;

            // Create shipping address
            $shippingAddress = Address::create([
                'user_id' => Auth::id(),
                'name' => $request->address['name'],
                'address_line_1' => $request->address['address_line_1'],
                'address_line_2' => $request->address['address_line_2'] ?? null,
                'city' => $request->address['city'],
                'state' => $request->address['state'],
                'postal_status' => $request->address['postal_status'],
                'country' => $request->address['country'],
                'phone' => $request->address['phone'],
                'is_default' => false,
            ]);

            // Process payment (mock for now)
            $paymentStatus = 'paid'; // This would actually be verified with payment gateway

            // Create order
            $order = Order::create([
                'buyer_id' => Auth::id(),
                'seller_id' => $product->user_id,
                'order_number' => 'ORD-' . time() . '-' . Auth::id(),
                'total_amount' => $totalAmount,
                'payment_method' => $request->payment_method,
                'payment_status' => $paymentStatus,
                'status' => 'processing',
                'shipping_address_id' => $shippingAddress->id,
            ]);

            // Add product to order
            $orderProduct = OrderProduct::create([
                'order_id' => $order->id,
                'product_id' => $product->id,
                'quantity' => $request->quantity,
                'price' => $product->price,
                'subtotal' => $totalAmount,
            ]);

            // Update product status if it's a single item for sale
            if (!$product->is_multiple) {
                $product->status = 'sold';
                $product->save();
            }

            return response()->json([
                'success' => true,
                'message' => 'Order placed successfully',
                'data' => new OrderResource($order)
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create order: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get popular sellers
     */
    public function getPopularSellers()
    {
        try {
            $popularSellers = Product::select('user_id')
                ->where('status', 'active')
                ->groupBy('user_id')
                ->withCount('sellerProducts')
                ->orderByDesc('seller_products_count')
                ->take(10)
                ->with('user')
                ->get();

            return response()->json([
                'success' => true,
                'data' => $popularSellers
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to get popular sellers: ' . $e->getMessage()
            ], 500);
        }
    }
}
