<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Supplier;
use App\Models\Product;
use App\Models\OrderItem;
use App\Models\SupplierTransaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;

class SupplierController extends Controller
{
    public function index(Request $request)
    {
        $query = Supplier::where('is_verified', true);

        if ($request->has('search')) {
            $query->where('company_name', 'like', '%' . $request->search . '%');
        }

        if ($request->has('featured')) {
            $query->where('is_featured', true);
        }

        $suppliers = $query->paginate($request->get('per_page', 20));

        return response()->json($suppliers);
    }

    public function show($id)
    {
        $supplier = Supplier::with(['products' => function ($query) {
            $query->where('is_active', true)->limit(12);
        }])->findOrFail($id);

        return response()->json($supplier);
    }

    public function profile()
    {
        $user = auth()->user();
        $supplier = $user->supplier;

        if (!$supplier) {
            return response()->json(['error' => 'Supplier profile not found'], 404);
        }

        return response()->json($supplier);
    }

    public function updateProfile(Request $request)
    {
        $user = auth()->user();
        $supplier = $user->supplier;

        if (!$supplier) {
            return response()->json(['error' => 'Supplier profile not found'], 404);
        }

        $validator = Validator::make($request->all(), [
            'company_name' => 'sometimes|string|max:255',
            'registration_number' => 'nullable|string|max:100',
            'vat_number' => 'nullable|string|max:50',
            'contact_name' => 'nullable|string|max:255',
            'contact_phone' => 'nullable|string|max:50',
            'contact_email' => 'nullable|email|max:255',
            'address' => 'nullable|string',
            'city' => 'nullable|string|max:100',
            'province' => 'nullable|string|max:100',
            'postal_code' => 'nullable|string|max:20',
            'description' => 'nullable|string',
            'logo_url' => 'nullable|url|max:500',
            'banner_url' => 'nullable|url|max:500',
            'delivery_self' => 'boolean',
            'delivery_platform' => 'boolean',
            'delivery_collection' => 'boolean',
        ]);

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

        $supplier->update($request->only([
            'company_name', 'registration_number', 'vat_number',
            'contact_name', 'contact_phone', 'contact_email',
            'address', 'city', 'province', 'postal_code',
            'description', 'logo_url', 'banner_url',
            'delivery_self', 'delivery_platform', 'delivery_collection',
        ]));

        return response()->json([
            'message' => 'Profile updated successfully',
            'supplier' => $supplier,
        ]);
    }

    public function products(Request $request)
    {
        $user = auth()->user();
        $supplier = $user->supplier;

        if (!$supplier) {
            return response()->json(['error' => 'Supplier profile not found'], 404);
        }

        $query = Product::where('supplier_id', $supplier->id);

        if ($request->has('search')) {
            $query->search($request->search);
        }

        if ($request->has('category_id')) {
            $query->where('category_id', $request->category_id);
        }

        if ($request->has('is_active')) {
            $query->where('is_active', $request->is_active);
        }

        $products = $query->with('category')
            ->orderBy('created_at', 'desc')
            ->paginate($request->get('per_page', 20));

        return response()->json($products);
    }

    public function orders(Request $request)
    {
        $user = auth()->user();
        $supplier = $user->supplier;

        if (!$supplier) {
            return response()->json(['error' => 'Supplier profile not found'], 404);
        }

        $query = OrderItem::where('supplier_id', $supplier->id)
            ->with(['order.company', 'product']);

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

        $orderItems = $query->orderBy('created_at', 'desc')
            ->paginate($request->get('per_page', 20));

        return response()->json($orderItems);
    }

    public function updateOrderItemStatus(Request $request, $itemId)
    {
        $user = auth()->user();
        $supplier = $user->supplier;

        if (!$supplier) {
            return response()->json(['error' => 'Supplier profile not found'], 404);
        }

        $orderItem = OrderItem::where('supplier_id', $supplier->id)
            ->where('id', $itemId)
            ->firstOrFail();

        $validator = Validator::make($request->all(), [
            'status' => 'required|in:pending,processing,shipped,delivered,cancelled',
        ]);

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

        $orderItem->update(['delivery_status' => $request->status]);

        return response()->json([
            'message' => 'Order item status updated',
            'order_item' => $orderItem,
        ]);
    }

    public function billing()
    {
        $user = auth()->user();
        $supplier = $user->supplier;

        if (!$supplier) {
            return response()->json(['error' => 'Supplier profile not found'], 404);
        }

        $stats = SupplierTransaction::where('supplier_id', $supplier->id)
            ->where('status', 'completed')
            ->selectRaw('
                SUM(amount) as total_sales,
                SUM(commission) as total_commission,
                SUM(net_amount) as net_earnings
            ')
            ->first();

        $pendingPayout = SupplierTransaction::where('supplier_id', $supplier->id)
            ->where('status', 'pending')
            ->sum('net_amount');

        $recentTransactions = SupplierTransaction::where('supplier_id', $supplier->id)
            ->with('order')
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();

        return response()->json([
            'supplier_id' => $supplier->id,
            'registration_fee_paid' => $supplier->registration_fee_paid,
            'registration_fee_amount' => $supplier->registration_fee_amount,
            'commission_rate' => $supplier->commission_rate,
            'total_sales' => $stats->total_sales ?? 0,
            'total_commission' => $stats->total_commission ?? 0,
            'net_earnings' => $stats->net_earnings ?? 0,
            'pending_payout' => $pendingPayout,
            'recent_transactions' => $recentTransactions,
        ]);
    }

    public function dashboard()
    {
        $user = auth()->user();
        $supplier = $user->supplier;

        if (!$supplier) {
            return response()->json(['error' => 'Supplier profile not found'], 404);
        }

        $totalProducts = Product::where('supplier_id', $supplier->id)->count();
        $activeProducts = Product::where('supplier_id', $supplier->id)->where('is_active', true)->count();
        $lowStockProducts = Product::where('supplier_id', $supplier->id)
            ->where('stock_quantity', '<', 10)
            ->where('is_active', true)
            ->count();

        $pendingOrders = OrderItem::where('supplier_id', $supplier->id)
            ->where('delivery_status', 'pending')
            ->count();

        $totalSales = SupplierTransaction::where('supplier_id', $supplier->id)
            ->where('status', 'completed')
            ->sum('amount');

        $monthlySales = SupplierTransaction::where('supplier_id', $supplier->id)
            ->where('status', 'completed')
            ->whereMonth('created_at', now()->month)
            ->sum('amount');

        $recentOrders = OrderItem::where('supplier_id', $supplier->id)
            ->with(['order.company', 'product'])
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get();

        return response()->json([
            'total_products' => $totalProducts,
            'active_products' => $activeProducts,
            'low_stock_products' => $lowStockProducts,
            'pending_orders' => $pendingOrders,
            'total_sales' => $totalSales,
            'monthly_sales' => $monthlySales,
            'recent_orders' => $recentOrders,
            'supplier' => $supplier,
        ]);
    }
}
