<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Item;
use App\Models\Category;

class MarketplaceController extends Controller
{
    public function index(Request $request)
    {
        $categories = Category::where('is_active', true)
            ->withCount(['items as items_count' => function ($query) {
                $query->whereIn('status', ['active', 'sale_pending'])
                    ->whereIn('listing_type', ['sale', 'inventory_open'])
                    ->whereHas('user', function($q) {
                        $q->where('is_active', true);
                    });
                // Exclude flagged items unless user is admin
                if (!auth()->check() || !auth()->user()->is_admin) {
                    $query->where('status', '!=', 'flagged');
                }
            }])
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get();

        $featuredQuery = Item::with(['user', 'category', 'primaryPhoto'])
            ->whereIn('status', ['active', 'sale_pending'])
            ->whereIn('listing_type', ['sale', 'inventory_open'])
            ->whereNotNull('featured_until')
            ->where('featured_until', '>', now())
            ->whereHas('user', function($q) {
                $q->where('is_active', true);
            })
            ->withCount('watchlists as watchers_count');

        $recentQuery = Item::with(['user', 'category', 'primaryPhoto', 'manufacturer'])
            ->whereIn('status', ['active', 'sale_pending'])
            ->whereIn('listing_type', ['sale', 'inventory_open'])
            ->whereHas('user', function($q) {
                $q->where('is_active', true);
            })
            ->withCount('watchlists as watchers_count');

        // Exclude flagged items unless user is admin
        if (!auth()->check() || !auth()->user()->is_admin) {
            $featuredQuery->where('status', '!=', 'flagged');
            $recentQuery->where('status', '!=', 'flagged');
        }

        $featuredItems = $featuredQuery->latest()->take(6)->get();
        $recentItems = $recentQuery->latest()->take(24)->get();

        // Get popular categories for quick browse
        $popularCategories = $categories->sortByDesc('items_count')->take(6);

        $stats = [
            'total_items' => Item::whereIn('status', ['active', 'sale_pending'])->whereIn('listing_type', ['sale', 'inventory_open'])->count(),
            'total_categories' => $categories->count(),
            'items_sold' => Item::where('status', 'sold')->count(),
        ];

        return view('marketplace.index', compact('categories', 'featuredItems', 'recentItems', 'stats', 'popularCategories'));
    }

    public function feed(Request $request)
    {
        $categories = Category::where('is_active', true)
            ->withCount(['items as items_count' => function ($query) {
                $query->whereIn('status', ['active', 'sale_pending'])
                    ->whereIn('listing_type', ['sale', 'inventory_open'])
                    ->whereHas('user', function($q) {
                        $q->where('is_active', true);
                    });
                // Exclude flagged items unless user is admin
                if (!auth()->check() || !auth()->user()->is_admin) {
                    $query->where('status', '!=', 'flagged');
                }
            }])
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get();

        $featuredQuery = Item::with(['user', 'category', 'primaryPhoto'])
            ->whereIn('status', ['active', 'sale_pending'])
            ->whereIn('listing_type', ['sale', 'inventory_open'])
            ->whereNotNull('featured_until')
            ->where('featured_until', '>', now())
            ->whereHas('user', function($q) {
                $q->where('is_active', true);
            })
            ->withCount('watchlists as watchers_count');

        $recentQuery = Item::with(['user', 'category', 'primaryPhoto'])
            ->whereIn('status', ['active', 'sale_pending'])
            ->whereIn('listing_type', ['sale', 'inventory_open'])
            ->whereHas('user', function($q) {
                $q->where('is_active', true);
            })
            ->withCount('watchlists as watchers_count');

        // Exclude flagged items unless user is admin
        if (!auth()->check() || !auth()->user()->is_admin) {
            $featuredQuery->where('status', '!=', 'flagged');
            $recentQuery->where('status', '!=', 'flagged');
        }

        $featuredItems = $featuredQuery->latest()->take(8)->get();
        $recentItems = $recentQuery->latest()->take(12)->get();

        $stats = [
            'total_items' => Item::whereIn('status', ['active', 'sale_pending'])->whereIn('listing_type', ['sale', 'inventory_open'])->count(),
            'total_categories' => $categories->count(),
            'items_sold' => Item::where('status', 'sold')->count(),
        ];

        return view('marketplace.feed', compact('categories', 'featuredItems', 'recentItems', 'stats'));
    }
}
