<?php

namespace App\Http\Controllers;

use App\Models\Marketplace\Product;
use App\Models\Marketplace\ProductCategory;
use App\Models\Marketplace\SavedProduct;
use App\Models\Marketplace\Store;
use App\Models\Marketplace\ProductReview;
use App\Models\Marketplace\Order;
use App\Models\Marketplace\MarketplaceMessage;
use App\Models\Marketplace\MarketplaceConversation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class PublicMarketplaceController extends Controller
{
    /**
     * Display marketplace listing page
     */
    public function index()
    {
        // Get categories for filters
        $categories = ProductCategory::select('id', 'name')
            ->withCount(['products' => function($query) {
                $query->where('status', 'active');
            }])
            ->having('products_count', '>', 0)
            ->get();

        // Get featured products
        $featuredProducts = Product::with(['category', 'media', 'user'])
            ->where('status', 'active')
            ->where('is_featured', true)
            ->latest()
            ->take(6)
            ->get();

        // Get popular sellers
        $popularSellers = Product::select('user_id')
            ->where('status', 'active')
            ->groupBy('user_id')
            ->withCount('sellerProducts')
            ->orderByDesc('seller_products_count')
            ->take(3)
            ->with('user')
            ->get();

        return view('front_end.pages.marketplace.marketplace_main', compact(
            'categories',
            'featuredProducts',
            'popularSellers'
        ));
    }

    /**
     * Display product creation page
     */
    public function create()
    {
        if (!Auth::check()) {
            return redirect()->route('login')->with('error', 'Please login to create a product listing');
        }

        $categories = ProductCategory::select('id', 'name')->get();
        $currencies = config('constants.currencies');
        
        // Check if user has a store, if not, suggest creating one
        $userStore = Store::where('user_id', Auth::id())->first();

        return view('front_end.pages.marketplace.create_product', compact(
            'categories',
            'currencies',
            'userStore'
        ));
    }

    /**
     * Display product details page
     */
    public function show($id)
    {
        $product = Product::with(['category', 'media', 'user', 'reviews.user', 'store'])
            ->where('status', 'active')
            ->findOrFail($id);

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

        // Check if product is saved
        $isSaved = false;
        if (Auth::check()) {
            $isSaved = SavedProduct::where('user_id', Auth::id())
                ->where('product_id', $id)
                ->exists();
        }

        // Get similar products
        $similarProducts = Product::with(['category', 'media'])
            ->where('id', '!=', $id)
            ->where('status', 'active')
            ->where(function($query) use ($product) {
                $query->where('category_id', $product->category_id)
                    ->orWhere('price', '>=', $product->price * 0.8)
                    ->orWhere('price', '<=', $product->price * 1.2);
            })
            ->limit(3)
            ->get();

        // Get more from seller
        $sellerProducts = Product::with(['category', 'media'])
            ->where('user_id', $product->user_id)
            ->where('id', '!=', $id)
            ->where('status', 'active')
            ->limit(3)
            ->get();

        // Get reviews
        $reviews = ProductReview::with('user')
            ->where('product_id', $id)
            ->orderBy('created_at', 'desc')
            ->paginate(5);

        // Calculate average rating
        $averageRating = $product->reviews->avg('rating') ?? 0;
        $ratingCount = $product->reviews->count();

        return view('front_end.pages.marketplace.show', compact(
            'product',
            'isSaved',
            'similarProducts',
            'sellerProducts',
            'reviews',
            'averageRating',
            'ratingCount'
        ));
    }

    /**
     * Display saved products page
     */
    public function savedProducts()
    {
        if (!Auth::check()) {
            return redirect()->route('login')->with('error', 'Please login to view saved products');
        }

        $savedProducts = SavedProduct::with(['product.category', 'product.media'])
            ->where('user_id', Auth::id())
            ->whereHas('product', function($query) {
                $query->where('status', 'active');
            })
            ->latest()
            ->paginate(12);

        return view('front_end.pages.marketplace.saved', compact('savedProducts'));
    }

    /**
     * Display my listings page
     */
    public function myListings()
    {
        if (!Auth::check()) {
            return redirect()->route('login')->with('error', 'Please login to view your listings');
        }
        
        $listings = Product::with(['category', 'media'])
            ->where('user_id', Auth::id())
            ->latest()
            ->paginate(12);

        // Get listing statistics
        $stats = [
            'total_listings' => $listings->total(),
            'active_listings' => $listings->where('status', 'active')->count(),
            'total_views' => $listings->sum('views'),
            'total_saves' => SavedProduct::whereIn('product_id', $listings->pluck('id'))
                ->count()
        ];

        return view('front_end.pages.marketplace.my-listings', compact(
            'listings',
            'stats'
        ));
    }

    /**
     * Display marketplace messages
     */
    public function messages()
    {
        if (!Auth::check()) {
            return redirect()->route('login')->with('error', 'Please login to view your messages');
        }
        
        $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);

        // Get active conversation if any
        $activeConversation = null;
        $messages = collect();
        
        if ($conversations->count() > 0 && request()->has('conversation')) {
            $activeConversation = $conversations->where('id', request()->conversation)->first();
        } elseif ($conversations->count() > 0) {
            $activeConversation = $conversations->first();
        }
        
        if ($activeConversation) {
            $messages = MarketplaceMessage::where('conversation_id', $activeConversation->id)
                ->with('sender')
                ->orderBy('created_at', 'asc')
                ->get();
                
            // Mark messages as read
            if (Auth::id() == $activeConversation->buyer_id) {
                MarketplaceMessage::where('conversation_id', $activeConversation->id)
                    ->where('sender_id', '!=', Auth::id())
                    ->update(['is_read' => true]);
            } else {
                MarketplaceMessage::where('conversation_id', $activeConversation->id)
                    ->where('sender_id', '!=', Auth::id())
                    ->update(['is_read' => true]);
            }
        }

        return view('front_end.pages.marketplace.messages', compact(
            'conversations',
            'activeConversation',
            'messages'
        ));
    }

    /**
     * Display store details page
     */
    public function storeDetail($id)
    {
        $store = Store::with(['owner', 'products.media', 'products.category'])
            ->findOrFail($id);
            
        // Get store stats
        $stats = [
            'total_products' => $store->products->where('status', 'active')->count(),
            'avg_rating' => ProductReview::whereIn('product_id', $store->products->pluck('id'))->avg('rating') ?? 0,
            'total_reviews' => ProductReview::whereIn('product_id', $store->products->pluck('id'))->count(),
            'member_since' => $store->created_at->format('M Y')
        ];
        
        // Get products with filters
        $query = Product::with(['category', 'media'])
            ->where('store_id', $id)
            ->where('status', 'active');
            
        // Apply category filter if specified
        if (request()->has('category')) {
            $query->where('category_id', request()->category);
        }
        
        // Apply price filter if specified
        if (request()->has('min_price')) {
            $query->where('price', '>=', request()->min_price);
        }
        
        if (request()->has('max_price')) {
            $query->where('price', '<=', request()->max_price);
        }
        
        // Apply sorting
        if (request()->has('sort')) {
            switch (request()->sort) {
                case 'price_low':
                    $query->orderBy('price', 'asc');
                    break;
                case 'price_high':
                    $query->orderBy('price', 'desc');
                    break;
                case 'newest':
                    $query->orderBy('created_at', 'desc');
                    break;
                case 'popular':
                    $query->orderBy('views', 'desc');
                    break;
                default:
                    $query->orderBy('created_at', 'desc');
            }
        } else {
            $query->orderBy('created_at', 'desc');
        }
        
        $products = $query->paginate(12);
        
        return view('front_end.pages.marketplace.store', compact(
            'store',
            'stats',
            'products'
        ));
    }

    /**
     * Display user orders page
     */
    public function myOrders()
    {
        if (!Auth::check()) {
            return redirect()->route('login')->with('error', 'Please login to view your orders');
        }
        
        $orders = Order::with(['products.media', 'seller', 'address'])
            ->where('buyer_id', Auth::id())
            ->latest()
            ->paginate(10);
            
        return view('front_end.pages.marketplace.orders', compact('orders'));
    }

    /**
     * Display order details page
     */
    public function orderDetail($id)
    {
        if (!Auth::check()) {
            return redirect()->route('login');
        }
        
        $order = Order::with(['products.media', 'seller', 'address'])
            ->where('id', $id)
            ->where(function($query) {
                $query->where('buyer_id', Auth::id())
                    ->orWhereHas('products', function($q) {
                        $q->where('user_id', Auth::id());
                    });
            })
            ->firstOrFail();
            
        return view('front_end.pages.marketplace.order-detail', compact('order'));
    }

    /**
     * Display create store page
     */
    public function createStore()
    {
        if (!Auth::check()) {
            return redirect()->route('login');
        }
        
        // Check if user already has a store
        $existingStore = Store::where('user_id', Auth::id())->first();
        if ($existingStore) {
            return redirect()->route('marketplace.store.edit');
        }
        
        return view('front_end.pages.marketplace.create-store');
    }

    /**
     * Display edit store page
     */
    public function editStore()
    {
        if (!Auth::check()) {
            return redirect()->route('login');
        }
        
        $store = Store::where('user_id', Auth::id())->firstOrFail();
        
        return view('front_end.pages.marketplace.edit-store', compact('store'));
    }

    /**
     * Display checkout page
     */
    public function checkout($productId)
    {
        if (!Auth::check()) {
            return redirect()->route('login');
        }
        
        $product = Product::with(['category', 'media', 'user'])
            ->where('status', 'active')
            ->findOrFail($productId);
            
        // Ensure user isn't buying their own product
        if ($product->user_id == Auth::id()) {
            return redirect()->route('marketplace.show', $productId)
                ->with('error', 'You cannot purchase your own product');
        }
        
        return view('front_end.pages.marketplace.checkout', compact('product'));
    }
}