<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\CartItem;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class CartController extends Controller
{
    public function index()
    {
        $user = auth()->user();
        $company = $user->company;

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

        $cartItems = CartItem::where('company_id', $company->id)
            ->with(['product.supplier:id,company_name,delivery_self,delivery_platform,delivery_collection', 'product.category:id,name'])
            ->get();

        $subtotal = $cartItems->sum(function ($item) {
            return $item->quantity * $item->product->price;
        });

        $itemsBySupplier = $cartItems->groupBy('product.supplier_id')->map(function ($items, $supplierId) {
            $supplier = $items->first()->product->supplier;
            return [
                'supplier_id' => $supplierId,
                'supplier_name' => $supplier->company_name,
                'delivery_options' => $supplier->delivery_options,
                'items' => $items,
                'subtotal' => $items->sum(function ($item) {
                    return $item->quantity * $item->product->price;
                }),
            ];
        })->values();

        return response()->json([
            'items' => $cartItems,
            'items_by_supplier' => $itemsBySupplier,
            'subtotal' => round($subtotal, 2),
            'tax_rate' => 15,
            'tax_amount' => round($subtotal * 0.15, 2),
            'total' => round($subtotal * 1.15, 2),
            'item_count' => $cartItems->sum('quantity'),
        ]);
    }

    public function add(Request $request)
    {
        $user = auth()->user();
        $company = $user->company;

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

        $validator = Validator::make($request->all(), [
            'product_id' => 'required|exists:products,id',
            'quantity' => 'required|integer|min:1',
        ]);

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

        $product = Product::where('id', $request->product_id)
            ->where('is_active', true)
            ->firstOrFail();

        if ($request->quantity < $product->min_order_quantity) {
            return response()->json([
                'error' => "Minimum order quantity is {$product->min_order_quantity}"
            ], 422);
        }

        if ($request->quantity > $product->stock_quantity) {
            return response()->json([
                'error' => "Only {$product->stock_quantity} items available in stock"
            ], 422);
        }

        $cartItem = CartItem::updateOrCreate(
            [
                'company_id' => $company->id,
                'product_id' => $request->product_id,
            ],
            [
                'quantity' => $request->quantity,
            ]
        );

        return response()->json([
            'message' => 'Product added to cart',
            'cart_item' => $cartItem->load('product'),
        ]);
    }

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

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

        $validator = Validator::make($request->all(), [
            'quantity' => 'required|integer|min:1',
        ]);

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

        $cartItem = CartItem::where('company_id', $company->id)
            ->where('id', $itemId)
            ->with('product')
            ->firstOrFail();

        if ($request->quantity < $cartItem->product->min_order_quantity) {
            return response()->json([
                'error' => "Minimum order quantity is {$cartItem->product->min_order_quantity}"
            ], 422);
        }

        if ($request->quantity > $cartItem->product->stock_quantity) {
            return response()->json([
                'error' => "Only {$cartItem->product->stock_quantity} items available in stock"
            ], 422);
        }

        $cartItem->update(['quantity' => $request->quantity]);

        return response()->json([
            'message' => 'Cart updated',
            'cart_item' => $cartItem,
        ]);
    }

    public function remove($itemId)
    {
        $user = auth()->user();
        $company = $user->company;

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

        $cartItem = CartItem::where('company_id', $company->id)
            ->where('id', $itemId)
            ->firstOrFail();

        $cartItem->delete();

        return response()->json(['message' => 'Item removed from cart']);
    }

    public function clear()
    {
        $user = auth()->user();
        $company = $user->company;

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

        CartItem::where('company_id', $company->id)->delete();

        return response()->json(['message' => 'Cart cleared']);
    }
}
