<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Marketplace\Product;
use App\Models\Marketplace\Store;
use App\Models\Marketplace\Order;
use App\Models\Marketplace\ProductReview;
use App\Models\Marketplace\ProductCategory;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;

class MarketplaceManagementController extends Controller
{
    /**
     * Display a dashboard with marketplace statistics.
     *
     * @return \Illuminate\Http\Response
     */
    public function dashboard()
    {
        // Get basic stats
        $totalProducts = Product::count();
        $totalStores = Store::count();
        $totalOrders = Order::count();
        $totalRevenue = Order::where('status', 'completed')->sum('total_amount');
        $totalReviews = ProductReview::count();
        
        // Get recent orders
        $recentOrders = Order::with(['user', 'products'])
            ->latest()
            ->take(5)
            ->get();
            
        // Get top selling products
        $topSellingProducts = Product::withCount('orders')
            ->orderBy('orders_count', 'desc')
            ->take(5)
            ->get();
            
        // Get top rated products
        $topRatedProducts = Product::withCount('reviews')
            ->withAvg('reviews', 'rating')
            ->orderBy('reviews_avg_rating', 'desc')
            ->take(5)
            ->get();
            
        // Get monthly sales data for the last 12 months
        $monthlySalesData = [];
        $monthlyOrdersData = [];
        
        for ($i = 11; $i >= 0; $i--) {
            $date = Carbon::now()->subMonths($i);
            $month = $date->format('M Y');
            
            $sales = Order::where('status', 'completed')
                ->whereYear('created_at', $date->year)
                ->whereMonth('created_at', $date->month)
                ->sum('total_amount');
                
            $orders = Order::whereYear('created_at', $date->year)
                ->whereMonth('created_at', $date->month)
                ->count();
                
            $monthlySalesData[$month] = $sales;
            $monthlyOrdersData[$month] = $orders;
        }
        
        return view('admin.pages.marketplace.dashboard', compact(
            'totalProducts',
            'totalStores',
            'totalOrders',
            'totalRevenue',
            'totalReviews',
            'recentOrders',
            'topSellingProducts',
            'topRatedProducts',
            'monthlySalesData',
            'monthlyOrdersData'
        ));
    }

    /**
     * Display a listing of products.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function products(Request $request)
    {
        $query = Product::with(['store', 'category']);

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

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

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

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

        // Apply ordering
        if ($request->filled('order_by')) {
            $direction = $request->filled('order_direction') ? $request->order_direction : 'desc';
            $query->orderBy($request->order_by, $direction);
        } else {
            $query->latest();
        }

        $products = $query->paginate(15);
        $categories = ProductCategory::all();
        $stores = Store::all();

        return view('admin.pages.marketplace.products', compact('products', 'categories', 'stores'));
    }

    /**
     * Display the specified product.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function showProduct($id)
    {
        $product = Product::with(['store', 'category', 'reviews.user'])
            ->withCount('orders')
            ->findOrFail($id);
            
        // Get related products
        $relatedProducts = Product::where('category_id', $product->category_id)
            ->where('id', '!=', $product->id)
            ->take(4)
            ->get();
            
        return view('admin.pages.marketplace.product_detail', compact('product', 'relatedProducts'));
    }

    /**
     * Update the status of the specified product.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function updateProductStatus(Request $request, $id)
    {
        $product = Product::findOrFail($id);
        $product->status = $request->status;
        $product->save();
        
        return back()->with('success', "Product status has been updated to {$request->status}");
    }

    /**
     * Remove the specified product from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroyProduct($id)
    {
        $product = Product::findOrFail($id);
        
        // Delete product images if exists
        if ($product->images) {
            foreach (json_decode($product->images) as $image) {
                if (Storage::exists('public/' . $image)) {
                    Storage::delete('public/' . $image);
                }
            }
        }
        
        $product->delete();
        
        return redirect()->route('admin.marketplace.products')
            ->with('success', 'Product deleted successfully');
    }

    /**
     * Display a listing of stores.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function stores(Request $request)
    {
        $query = Store::with(['owner']);

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

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

        // Apply ordering
        if ($request->filled('order_by')) {
            $direction = $request->filled('order_direction') ? $request->order_direction : 'desc';
            $query->orderBy($request->order_by, $direction);
        } else {
            $query->latest();
        }

        $stores = $query->paginate(15);

        return view('admin.pages.marketplace.stores', compact('stores'));
    }

    /**
     * Display the specified store.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function showStore($id)
    {
        $store = Store::with(['owner', 'products'])
            ->withCount('products')
            ->findOrFail($id);
            
        // Get store statistics
        $totalSales = Order::whereHas('products', function($query) use ($id) {
                $query->where('store_id', $id);
            })
            ->where('status', 'completed')
            ->sum('total_amount');
            
        $totalOrders = Order::whereHas('products', function($query) use ($id) {
                $query->where('store_id', $id);
            })
            ->count();
            
        $averageRating = ProductReview::whereHas('product', function($query) use ($id) {
                $query->where('store_id', $id);
            })
            ->avg('rating');
            
        return view('admin.pages.marketplace.store_detail', compact(
            'store', 
            'totalSales', 
            'totalOrders', 
            'averageRating'
        ));
    }

    /**
     * Update the status of the specified store.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function updateStoreStatus(Request $request, $id)
    {
        $store = Store::findOrFail($id);
        $store->status = $request->status;
        $store->save();
        
        return back()->with('success', "Store status has been updated to {$request->status}");
    }

    /**
     * Display a listing of orders.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function orders(Request $request)
    {
        $query = Order::with(['user', 'products.store']);

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

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

        // Apply date range filter
        if ($request->filled('date_from') && $request->filled('date_to')) {
            $query->whereBetween('created_at', [
                Carbon::parse($request->date_from)->startOfDay(),
                Carbon::parse($request->date_to)->endOfDay()
            ]);
        }

        // Apply ordering
        if ($request->filled('order_by')) {
            $direction = $request->filled('order_direction') ? $request->order_direction : 'desc';
            $query->orderBy($request->order_by, $direction);
        } else {
            $query->latest();
        }

        $orders = $query->paginate(15);

        return view('admin.pages.marketplace.orders', compact('orders'));
    }

    /**
     * Display the specified order.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function showOrder($id)
    {
        $order = Order::with(['user', 'products.store', 'address'])
            ->findOrFail($id);
            
        return view('admin.pages.marketplace.order_detail', compact('order'));
    }

    /**
     * Update the status of the specified order.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function updateOrderStatus(Request $request, $id)
    {
        $order = Order::findOrFail($id);
        $order->status = $request->status;
        $order->save();
        
        return back()->with('success', "Order status has been updated to {$request->status}");
    }

    /**
     * Display a listing of reviews.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function reviews(Request $request)
    {
        $query = ProductReview::with(['product', 'user']);

        // Apply filters
        if ($request->filled('rating')) {
            $query->where('rating', $request->rating);
        }

        if ($request->filled('product')) {
            $query->where('product_id', $request->product);
        }

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('review', 'like', "%{$search}%")
                  ->orWhereHas('product', function($productQuery) use ($search) {
                      $productQuery->where('name', 'like', "%{$search}%");
                  })
                  ->orWhereHas('user', function($userQuery) use ($search) {
                      $userQuery->where('name', 'like', "%{$search}%");
                  });
            });
        }

        // Apply ordering
        if ($request->filled('order_by')) {
            $direction = $request->filled('order_direction') ? $request->order_direction : 'desc';
            $query->orderBy($request->order_by, $direction);
        } else {
            $query->latest();
        }

        $reviews = $query->paginate(15);
        $products = Product::all();

        return view('admin.pages.marketplace.reviews', compact('reviews', 'products'));
    }

    /**
     * Remove the specified review from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroyReview($id)
    {
        $review = ProductReview::findOrFail($id);
        $review->delete();
        
        return redirect()->route('admin.marketplace.reviews')
            ->with('success', 'Review deleted successfully');
    }

    /**
     * Display a listing of product categories.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function categories(Request $request)
    {
        $categories = ProductCategory::withCount('products')->get();
        
        return view('admin.pages.marketplace.categories', compact('categories'));
    }

    /**
     * Store a newly created category in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function storeCategory(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:product_categories,name',
            'description' => 'nullable|string',
            'icon' => 'nullable|string|max:50',
        ]);

        ProductCategory::create([
            'name' => $request->name,
            'description' => $request->description,
            'icon' => $request->icon,
        ]);

        return redirect()->route('admin.marketplace.categories')
            ->with('success', 'Category created successfully');
    }

    /**
     * Update the specified category in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function updateCategory(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:product_categories,name,' . $id,
            'description' => 'nullable|string',
            'icon' => 'nullable|string|max:50',
        ]);

        $category = ProductCategory::findOrFail($id);
        $category->update([
            'name' => $request->name,
            'description' => $request->description,
            'icon' => $request->icon,
        ]);

        return redirect()->route('admin.marketplace.categories')
            ->with('success', 'Category updated successfully');
    }

    /**
     * Remove the specified category from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroyCategory($id)
    {
        $category = ProductCategory::findOrFail($id);
        
        // Check if category has products
        if ($category->products()->count() > 0) {
            return redirect()->route('admin.marketplace.categories')
                ->with('error', 'Cannot delete category with associated products');
        }
        
        $category->delete();
        
        return redirect()->route('admin.marketplace.categories')
            ->with('success', 'Category deleted successfully');
    }

    /**
     * Display marketplace settings.
     *
     * @return \Illuminate\Http\Response
     */
    public function settings()
    {
        // Get marketplace settings from config or database
        $settings = [
            'commission_rate' => config('marketplace.commission_rate', 5),
            'allow_new_stores' => config('marketplace.allow_new_stores', true),
            'auto_approve_products' => config('marketplace.auto_approve_products', false),
            'min_order_amount' => config('marketplace.min_order_amount', 0),
            'max_products_per_store' => config('marketplace.max_products_per_store', 100),
            'allowed_payment_methods' => config('marketplace.allowed_payment_methods', ['credit_card', 'paypal']),
        ];
        
        return view('admin.pages.marketplace.settings', compact('settings'));
    }

    /**
     * Update marketplace settings.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function updateSettings(Request $request)
    {
        $request->validate([
            'commission_rate' => 'required|numeric|min:0|max:100',
            'allow_new_stores' => 'boolean',
            'auto_approve_products' => 'boolean',
            'min_order_amount' => 'required|numeric|min:0',
            'max_products_per_store' => 'required|numeric|min:1',
            'allowed_payment_methods' => 'required|array',
        ]);

        // Update settings in config or database
        // This is a placeholder - actual implementation would depend on how settings are stored
        
        return redirect()->route('admin.marketplace.settings')
            ->with('success', 'Marketplace settings updated successfully');
    }
} 