<?php

namespace App\Http\Controllers;

use App\Models\Cart;
use App\Models\Order;
use App\Models\OrderItem;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $user  = $request->user();
        $query = Order::with(['items', 'user:id,name,email']);

        // Customers only see their own orders
        if ($user->isCustomer()) {
            $query->where('user_id', $user->id);
        }

        $orders = $query->latest()->paginate(20);

        return response()->json([
            'success' => true,
            'data'    => $orders,
        ]);
    }

    public function show(Request $request, int $id): JsonResponse
    {
        $user  = $request->user();
        $order = Order::with(['items.product', 'user:id,name,email'])->findOrFail($id);

        // Customers can only view their own orders
        if ($user->isCustomer() && $order->user_id !== $user->id) {
            return response()->json([
                'success' => false,
                'message' => 'Forbidden.',
            ], 403);
        }

        return response()->json([
            'success' => true,
            'data'    => $order,
        ]);
    }

    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'shipping_address'     => 'required|string',
            'shipping_city'        => 'required|string',
            'shipping_postal_code' => 'nullable|string',
            'shipping_phone'       => 'required|string',
            'notes'                => 'nullable|string',
            'coupon_code'          => 'nullable|string|max:50',
        ]);

        $cart = Cart::with(['items.product', 'items.variant'])->where('user_id', $request->user()->id)->first();

        if (!$cart || $cart->items->isEmpty()) {
            return response()->json([
                'success' => false,
                'message' => 'سبد خرید شما خالی است.',
            ], 422);
        }

        DB::beginTransaction();
        try {
            $total = 0;
            $orderItems = [];

            foreach ($cart->items as $cartItem) {
                $product = $cartItem->product;

                if (!$product || !$product->is_active) {
                    DB::rollBack();
                    return response()->json([
                        'success' => false,
                        'message' => "محصول '{$cartItem->product_id}' دیگر موجود نیست.",
                    ], 422);
                }

                // Check stock from variant or product
                $stock = $cartItem->variant_id ? $cartItem->variant->stock : $product->stock;
                $price = $cartItem->variant_id ? $cartItem->variant->final_price : $product->final_price;

                if ($stock < $cartItem->quantity) {
                    DB::rollBack();
                    return response()->json([
                        'success'         => false,
                        'message'         => "موجودی کافی برای '{$product->name}' وجود ندارد.",
                        'available_stock' => $stock,
                    ], 422);
                }

                $itemTotal    = $price * $cartItem->quantity;
                $total       += $itemTotal;
                $orderItems[] = [
                    'product_id'   => $product->id,
                    'product_name' => $product->name,
                    'quantity'     => $cartItem->quantity,
                    'price'        => $price,
                    'total'        => $itemTotal,
                ];

                // Reduce stock
                if ($cartItem->variant_id) {
                    $cartItem->variant->decrement('stock', $cartItem->quantity);
                } else {
                    $product->decrement('stock', $cartItem->quantity);
                }
            }

            // Apply coupon if provided
            $discountAmount = 0;
            $couponCode = null;
            
            if ($request->coupon_code) {
                $coupon = \App\Models\Coupon::where('code', strtoupper($request->coupon_code))->first();
                
                if ($coupon && $coupon->isValid()) {
                    $discountAmount = $coupon->calculateDiscount($total);
                    
                    if ($discountAmount > 0) {
                        $couponCode = $coupon->code;
                        // Increment used count
                        $coupon->increment('used_count');
                    }
                }
            }
            
            $finalTotal = max(0, $total - $discountAmount);

            $order = Order::create([
                'order_number'         => Order::generateOrderNumber(),
                'user_id'              => $request->user()->id,
                'status'               => Order::STATUS_PENDING,
                'total_amount'         => $finalTotal,
                'discount_amount'      => $discountAmount,
                'coupon_code'          => $couponCode,
                'shipping_address'     => strip_tags($request->shipping_address),
                'shipping_city'        => strip_tags($request->shipping_city),
                'shipping_postal_code' => $request->shipping_postal_code,
                'shipping_phone'       => $request->shipping_phone,
                'notes'                => $request->notes ? strip_tags($request->notes) : null,
            ]);

            foreach ($orderItems as $item) {
                OrderItem::create(array_merge($item, ['order_id' => $order->id]));
            }

            // Clear cart
            $cart->items()->delete();

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'سفارش با موفقیت ثبت شد.',
                'data'    => $order->load('items'),
            ], 201);
        } catch (\Throwable $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'خطا در ثبت سفارش. لطفاً دوباره تلاش کنید.',
            ], 500);
        }
    }

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

        $order = Order::findOrFail($id);
        $order->update([
            'status'            => $request->status,
            'status_changed_by' => $request->user()->id,
            'status_changed_at' => now(),
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Order status updated.',
            'data'    => $order,
        ]);
    }
}
