<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\OrderDetails;
use App\Models\Product;
use App\Models\User;
use App\Models\Variant;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class OrderController extends Controller
{
    public function index()
    {
        $data['PageTitle'] = 'All Orders';
        $data['orders'] = Order::latest()->get();
        $data['parentOrderShowClass'] = 'show';
        $data['allOrderActiveClass'] = 'active';
        return view('backend.order.index')->with($data);
    }

    public function create()
    {
        return view('frontend.cart');
    }

    public function checkout(Request $request)
    {
        $user = Auth::user();
        $userId = $user ? $user->id : null;

        $userData = null;
        if ($userId) {
            $userData = User::where("id", $userId)->first();
        }

        $userName = $userData ? $userData->name : "Guest";

        return view('frontend.checkout')->with([
            'userId'   => $userId,
            'userName' => $userName
        ]);
    }

    public function store(Request $request)
    {
        Log::info('Order store request received', [
            'payload' => $request->all()
        ]);

        // 1) Strong validation
        $validated = $request->validate([
            'name'                     => 'required|string|max:255',
            'phone'                    => 'required|string|max:50',
            'address'                  => 'required|string',
            'orders'                   => 'required|array|min:1',
            'orders.*.id'              => 'required|integer|exists:products,id',
            'orders.*.quantity'        => 'required|integer|min:1',
            'orders.*.product_size'    => 'nullable|string|max:50',
            'orders.*.product_code'    => 'nullable|string|max:100',
        ]);

        DB::beginTransaction();

        try {
            $ordersData = $validated['orders'];
            $productIds = collect($ordersData)->pluck('id')->unique()->all();

            // 2) products load
            $products = Product::whereIn('id', $productIds)
                ->get()
                ->keyBy('id');

            $details = [];
            $calculatedSubtotal = 0;

            foreach ($ordersData as $item) {
                $product = $products->get($item['id']);

                if (!$product) {
                    throw new \RuntimeException('One of the products is no longer available.');
                }

                $qty = (int) $item['quantity'];
                if ($qty < 1) {
                    $qty = 1;
                }

                $size = $item['product_size'] ?? null;

                // Variant (size থাকলে)
                $variant = null;
                if (!empty($size)) {
                    $variant = Variant::where('product_id', $product->id)
                        ->where('size', $size)
                        ->first();

                    if (!$variant) {
                        throw new \RuntimeException("Selected size for {$product->name} is not available.");
                    }
                }

                // 3) Stock check (product + variant দুটোই)
                $productStock = (int) ($product->stock ?? 0);
                if ($productStock < $qty) {
                    throw new \RuntimeException("Not enough stock for {$product->name}. Available: {$productStock}");
                }

                if ($variant) {
                    $variantStock = (int) ($variant->stock ?? 0);
                    if ($variantStock < $qty) {
                        throw new \RuntimeException("Not enough stock for {$product->name} (size {$size}). Available: {$variantStock}");
                    }
                }

                // 4) Unit price শুধুই DB থেকে (client থেকে না)
                $unitPrice = $product->discount_price && $product->discount_price > 0
                    ? $product->discount_price
                    : $product->price;

                $unitPrice = (float) ($unitPrice ?? 0);
                $lineTotal = $unitPrice * $qty;

                $calculatedSubtotal += $lineTotal;

                $details[] = [
                    'product_id'   => $product->id,
                    'quantity'     => $qty,
                    'size'         => $size,
                    // DB তে থাকলে product_code ব্যবহার করি, না থাকলে request এরটা fallback
                    'product_code' => $product->product_code ?? ($item['product_code'] ?? null),
                    // NOTE: এখন price = LINE TOTAL (আগের behaviour রেখে দিলাম)
                    'price'        => $lineTotal,
                ];
            }

            // 5) Final total decide
            $clientTotal = (float) $request->input('totalAmount', 0);
            $finalTotal = $calculatedSubtotal;

            if ($clientTotal >= $calculatedSubtotal) {
                $finalTotal = $clientTotal;
            } else {
                Log::warning('Client total lower than calculated subtotal, using server subtotal', [
                    'client_total'     => $clientTotal,
                    'calculated_total' => $calculatedSubtotal,
                ]);
            }

            // 6) Order create
            $order = new Order();
            $order->user_id     = $request->userId;
            $order->phone       = $validated['phone'];
            $order->name        = $validated['name'];
            $order->address     = $validated['address'];
            $order->total_price = $finalTotal;
            $order->status      = "pending";
            $order->save();

            // 7) OrderDetails insert
            foreach ($details as &$detail) {
                $detail['order_id'] = $order->id;
            }
            unset($detail);

            OrderDetails::insert($details);

            // 8) Stock reduce (product + variant)
            foreach ($details as $detail) {
                $product = $products->get($detail['product_id']);

                if ($product) {
                    $product->stock = (int) ($product->stock ?? 0) - $detail['quantity'];
                    if ($product->stock < 0) {
                        $product->stock = 0;
                    }
                    $product->sold_count = (int) ($product->sold_count ?? 0) + $detail['quantity'];
                    $product->save();
                }

                if (!empty($detail['size'])) {
                    $variant = Variant::where('product_id', $detail['product_id'])
                        ->where('size', $detail['size'])
                        ->first();

                    if ($variant) {
                        $variant->stock = (int) ($variant->stock ?? 0) - $detail['quantity'];
                        if ($variant->stock < 0) {
                            $variant->stock = 0;
                        }
                        $variant->save();
                    }
                }
            }

            DB::commit();

            Log::info('Order created successfully', [
                'order_id' => $order->id,
                'total'    => $order->total_price,
            ]);

            return response()->json([
                'message'  => 'Order created successfully',
                'status'   => 'success',
                'order_id' => $order->id,
            ]);
        } catch (\RuntimeException $e) {
            DB::rollBack();

            Log::warning('Order validation/business error', [
                'message' => $e->getMessage(),
            ]);

            return response()->json([
                'message' => $e->getMessage(),
            ], 422);
        } catch (\Throwable $e) {
            DB::rollBack();

            Log::error('Order store failed', [
                'error'   => $e->getMessage(),
                'trace'   => $e->getTraceAsString(),
            ]);

            return response()->json([
                'message' => 'Something went wrong!',
                'error'   => config('app.debug') ? $e->getMessage() : null,
            ], 500);
        }
    }

    public function confirmOrder($id)
    {
        $orders = Order::where('id', $id)->with('orderDetails')->get();
        return view('frontend.confirm-order')->with('orders', $orders);
    }

    public function details($id)
    {
        $data['PageTitle'] = 'All Orders';
        $data['orders'] = Order::where('id', $id)->first();
        $data['parentOrderShowClass'] = 'show';
        $data['allOrderActiveClass'] = 'active';
        $data['orderDetails'] = OrderDetails::where('order_id', $id)->with('product')->get();
        return view('backend.order.details')->with($data);
    }

    public function updateStatus(Request $request, $id)
    {
        $order = Order::findOrFail($id);
        $order->status = $request->status;
        $order->save();
        return redirect()->route('admin.order-all')->with('success', 'Order status updated successfully');
    }

    public function destroy($id)
    {
        $order = Order::findOrFail($id);
        $order->orderDetails()->delete();
        $order->delete();
        return redirect()->route('admin.order-all')->with('success', 'Order deleted successfully');
    }
}
