<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Services\OrderService;
use Illuminate\Http\Request;
use Exception;

class OrderController extends Controller
{
    protected $orderService;

    public function __construct(OrderService $orderService)
    {
        $this->orderService = $orderService;
    }

    public function store(Request $request)
    {
        $rules = [
            'items' => 'required|array|min:1',
            'items.*.variant_id' => 'required|exists:product_variants,id',
            'items.*.quantity' => 'required|integer|min:1',
            'delivery_method' => 'required|in:ena_coach,wells_fargo',
            'delivery_location' => 'required|string',
            'coupon_code' => 'nullable|string',
        ];

        // If guest, guest name and phone are required
        if (!$request->user('sanctum')) {
            $rules['guest_name'] = 'required|string|max:255';
            $rules['guest_phone'] = 'required|string';
        }

        $request->validate($rules);

        $data = $request->only([
            'items',
            'delivery_method',
            'delivery_location',
            'coupon_code',
            'guest_name',
            'guest_phone'
        ]);

        if ($request->user('sanctum')) {
            $data['user_id'] = $request->user('sanctum')->id;
        }

        try {
            $order = $this->orderService->createOrder($data);
            return response()->json([
                'success' => true,
                'order' => $order->load('items.product', 'items.variant'),
                'message' => 'Order created successfully.'
            ], 201);
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 400);
        }
    }

    public function status($id)
    {
        $order = Order::with('items.product', 'items.variant')->findOrFail($id);
        return response()->json($order);
    }

    public function userOrders(Request $request)
    {
        $orders = $request->user()->orders()
            ->with('items.product', 'items.variant')
            ->orderBy('created_at', 'desc')
            ->get();

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

    public function applyCoupon(Request $request, $id)
    {
        $request->validate([
            'code' => 'required|string',
        ]);

        $order = Order::findOrFail($id);

        if ($order->status !== 'pending') {
            return response()->json([
                'success' => false,
                'message' => 'Coupons can only be applied to pending orders.'
            ], 400);
        }

        $coupon = \App\Models\Coupon::active()->where('code', $request->code)->first();

        if (!$coupon) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid or expired coupon code.'
            ], 422);
        }

        if (!$coupon->isValidForAmount($order->subtotal)) {
            return response()->json([
                'success' => false,
                'message' => 'Order requirements not met for this coupon.'
            ], 422);
        }

        // Apply coupon
        $discountAmount = $coupon->calculateDiscount($order->subtotal);
        $total = $order->subtotal + $order->delivery_fee - $discountAmount;
        if ($total < 0) {
            $total = 0;
        }

        $order->update([
            'coupon_code' => $coupon->code,
            'discount_amount' => $discountAmount,
            'total' => $total
        ]);

        // Increment coupon use
        $coupon->increment('used_count');

        return response()->json([
            'success' => true,
            'order' => $order->load('items.product', 'items.variant'),
            'message' => 'Coupon applied successfully.'
        ]);
    }
}
