<?php
namespace App\Http\Controllers\API\Customer;

use App\Http\Controllers\Controller;
use App\Models\Cart;
use App\Models\Coupon;
use App\Models\CouponUsage;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CustomerCheckoutController extends Controller
{
    public function process(Request $request): JsonResponse
    {
        $data = $request->validate([
            'address_id'     => 'nullable|exists:customer_addresses,id',
            'shipping_address' => 'nullable|array',
            'coupon_code'    => 'nullable|string',
            'payment_method' => 'required|in:card,paypal,stripe,cash_on_delivery',
            'notes'          => 'nullable|string',
        ]);

        $user = $request->user();
        $cartItems = Cart::with('product.vendor')->where('user_id', $user->id)->get();

        if ($cartItems->isEmpty()) {
            return response()->json(['message' => 'Cart is empty.'], 422);
        }

        // Group by vendor
        $grouped = $cartItems->groupBy(fn($item) => $item->product->vendor_id);
        $orders = [];

        DB::transaction(function () use ($data, $user, $grouped, &$orders) {
            $coupon = null;
            if (!empty($data['coupon_code'])) {
                $coupon = Coupon::where('code', strtoupper($data['coupon_code']))->first();
            }

            foreach ($grouped as $vendorId => $items) {
                $vendor = $items->first()->product->vendor;
                $subtotal = $items->sum(fn($i) => ($i->product->sale_price ?? $i->product->price) * $i->quantity);
                $discount = $coupon ? $coupon->calculateDiscount($subtotal) : 0;
                $total = $subtotal - $discount;
                $commissionRate = $vendor->commission_rate / 100;
                $commissionAmount = $total * $commissionRate;
                $vendorEarnings = $total - $commissionAmount;

                $order = Order::create([
                    'order_number'    => Order::generateOrderNumber(),
                    'user_id'         => $user->id,
                    'vendor_id'       => $vendorId,
                    'status'          => 'pending',
                    'payment_status'  => 'pending',
                    'payment_method'  => $data['payment_method'],
                    'subtotal'        => $subtotal,
                    'discount'        => $discount,
                    'shipping_cost'   => 0,
                    'tax'             => 0,
                    'total'           => $total,
                    'commission_amount' => $commissionAmount,
                    'vendor_earnings' => $vendorEarnings,
                    'coupon_id'       => $coupon?->id,
                    'address_id'      => $data['address_id'] ?? null,
                    'shipping_address' => $data['shipping_address'] ?? null,
                    'notes'           => $data['notes'] ?? null,
                ]);

                foreach ($items as $item) {
                    OrderItem::create([
                        'order_id'     => $order->id,
                        'product_id'   => $item->product_id,
                        'product_name' => $item->product->name,
                        'product_sku'  => $item->product->sku,
                        'quantity'     => $item->quantity,
                        'unit_price'   => $item->product->sale_price ?? $item->product->price,
                        'total_price'  => ($item->product->sale_price ?? $item->product->price) * $item->quantity,
                    ]);
                    if ($item->product->track_inventory) {
                        $item->product->decrement('stock_quantity', $item->quantity);
                    }
                    $item->product->increment('sales_count', $item->quantity);
                }

                if ($coupon) {
                    $coupon->increment('used_count');
                    CouponUsage::create(['coupon_id' => $coupon->id, 'user_id' => $user->id, 'order_id' => $order->id]);
                }

                $orders[] = $order->load('items');
            }

            Cart::where('user_id', $user->id)->delete();
        });

        return response()->json(['message' => 'Orders placed successfully.', 'orders' => $orders], 201);
    }

    public function payment(Request $request): JsonResponse
    {
        $data = $request->validate(['order_id' => 'required|exists:orders,id', 'payment_reference' => 'nullable|string']);
        $order = Order::where('user_id', $request->user()->id)->findOrFail($data['order_id']);
        // Dummy payment: mark as paid
        $order->update(['payment_status' => 'paid', 'payment_reference' => $data['payment_reference'] ?? 'DUMMY-' . uniqid(), 'status' => 'confirmed']);
        return response()->json(['message' => 'Payment processed.', 'order' => $order]);
    }
}
