<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\SupplierTransaction;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class SupplierController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware(function ($request, $next) {
            if (auth()->user()->user_type !== 'supplier') {
                return redirect()->route('home')->with('error', 'Access denied.');
            }
            return $next($request);
        });
    }

    public function dashboard()
    {
        $supplier = auth()->user()->supplier;
        
        $stats = [
            'total_products' => Product::where('supplier_id', $supplier->id)->count(),
            'active_products' => Product::where('supplier_id', $supplier->id)->where('is_active', true)->count(),
            'total_orders' => OrderItem::where('supplier_id', $supplier->id)->distinct('order_id')->count('order_id'),
            'pending_orders' => OrderItem::where('supplier_id', $supplier->id)->where('status', 'pending')->count(),
            'total_revenue' => SupplierTransaction::where('supplier_id', $supplier->id)
                ->where('type', 'sale')
                ->sum('net_amount'),
        ];
        
        $recentOrders = OrderItem::with('order.user')
            ->where('supplier_id', $supplier->id)
            ->orderBy('created_at', 'desc')
            ->take(5)
            ->get();

        return view('supplier.dashboard', compact('supplier', 'stats', 'recentOrders'));
    }

    public function products()
    {
        $supplier = auth()->user()->supplier;
        
        $products = Product::where('supplier_id', $supplier->id)
            ->with('category')
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        return view('supplier.products.index', compact('products'));
    }

    public function createProduct()
    {
        $categories = Category::with('children')
            ->whereNull('parent_id')
            ->orderBy('name')
            ->get();

        return view('supplier.products.create', compact('categories'));
    }

    public function storeProduct(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'required|string',
            'price' => 'required|numeric|min:0',
            'compare_price' => 'nullable|numeric|min:0',
            'category_id' => 'required|exists:categories,id',
            'stock_quantity' => 'required|integer|min:0',
            'unit' => 'required|string|max:50',
            'min_order_quantity' => 'integer|min:1',
        ]);

        $supplier = auth()->user()->supplier;

        Product::create([
            'supplier_id' => $supplier->id,
            'category_id' => $request->category_id,
            'name' => $request->name,
            'slug' => Str::slug($request->name) . '-' . Str::random(5),
            'description' => $request->description,
            'price' => $request->price,
            'compare_price' => $request->compare_price,
            'sku' => 'SKU-' . strtoupper(Str::random(8)),
            'stock_quantity' => $request->stock_quantity,
            'unit' => $request->unit,
            'min_order_quantity' => $request->min_order_quantity ?? 1,
            'is_active' => $request->boolean('is_active', true),
            'is_featured' => false,
            'rating' => 4.0,
        ]);

        return redirect()->route('supplier.products')
            ->with('success', 'Product created successfully!');
    }

    public function editProduct($id)
    {
        $supplier = auth()->user()->supplier;
        $product = Product::where('supplier_id', $supplier->id)->findOrFail($id);
        
        $categories = Category::with('children')
            ->whereNull('parent_id')
            ->orderBy('name')
            ->get();

        return view('supplier.products.edit', compact('product', 'categories'));
    }

    public function updateProduct(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'required|string',
            'price' => 'required|numeric|min:0',
            'compare_price' => 'nullable|numeric|min:0',
            'category_id' => 'required|exists:categories,id',
            'stock_quantity' => 'required|integer|min:0',
            'unit' => 'required|string|max:50',
        ]);

        $supplier = auth()->user()->supplier;
        $product = Product::where('supplier_id', $supplier->id)->findOrFail($id);

        $product->update([
            'name' => $request->name,
            'description' => $request->description,
            'price' => $request->price,
            'compare_price' => $request->compare_price,
            'category_id' => $request->category_id,
            'stock_quantity' => $request->stock_quantity,
            'unit' => $request->unit,
            'min_order_quantity' => $request->min_order_quantity ?? 1,
            'is_active' => $request->boolean('is_active', true),
        ]);

        return redirect()->route('supplier.products')
            ->with('success', 'Product updated successfully!');
    }

    public function deleteProduct($id)
    {
        $supplier = auth()->user()->supplier;
        $product = Product::where('supplier_id', $supplier->id)->findOrFail($id);
        
        $product->delete();

        return redirect()->route('supplier.products')
            ->with('success', 'Product deleted successfully!');
    }

    public function orders()
    {
        $supplier = auth()->user()->supplier;
        
        $orders = OrderItem::with(['order.user', 'order.company', 'product'])
            ->where('supplier_id', $supplier->id)
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        return view('supplier.orders', compact('orders'));
    }

    public function updateOrderStatus(Request $request, $id)
    {
        $request->validate([
            'status' => 'required|in:pending,processing,shipped,delivered,cancelled',
        ]);

        $supplier = auth()->user()->supplier;
        $orderItem = OrderItem::where('supplier_id', $supplier->id)->findOrFail($id);
        
        $orderItem->update(['status' => $request->status]);

        return back()->with('success', 'Order status updated successfully!');
    }

    public function billing()
    {
        $supplier = auth()->user()->supplier;
        
        $transactions = SupplierTransaction::where('supplier_id', $supplier->id)
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        $stats = [
            'total_sales' => SupplierTransaction::where('supplier_id', $supplier->id)
                ->where('type', 'sale')
                ->sum('amount'),
            'total_commission' => SupplierTransaction::where('supplier_id', $supplier->id)
                ->where('type', 'sale')
                ->sum('commission_amount'),
            'net_earnings' => SupplierTransaction::where('supplier_id', $supplier->id)
                ->where('type', 'sale')
                ->sum('net_amount'),
            'pending_payout' => SupplierTransaction::where('supplier_id', $supplier->id)
                ->where('status', 'pending')
                ->sum('net_amount'),
        ];

        $payouts = \App\Models\SupplierPayout::where('supplier_id', $supplier->id)
            ->orderBy('created_at', 'desc')
            ->take(5)
            ->get();

        return view('supplier.billing', compact('supplier', 'transactions', 'stats', 'payouts'));
    }

    public function profile()
    {
        $supplier = auth()->user()->supplier;
        return view('supplier.profile', compact('supplier'));
    }

    public function updateProfile(Request $request)
    {
        $request->validate([
            'company_name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'contact_phone' => 'nullable|string|max:20',
            'address' => 'nullable|string|max:255',
            'city' => 'nullable|string|max:100',
            'postal_code' => 'nullable|string|max:20',
        ]);

        $supplier = auth()->user()->supplier;
        
        $supplier->update([
            'company_name' => $request->company_name,
            'description' => $request->description,
            'contact_phone' => $request->contact_phone,
            'address' => $request->address,
            'city' => $request->city,
            'postal_code' => $request->postal_code,
            'delivery_self' => $request->boolean('delivery_self'),
            'delivery_collection' => $request->boolean('delivery_collection'),
            'delivery_platform' => $request->boolean('delivery_platform'),
        ]);

        return back()->with('success', 'Profile updated successfully!');
    }
}
