<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Cart;
use App\Models\CartItem;
use App\Models\Product;
use App\Models\ProductVariant;
use App\Models\Coupon;
use App\Models\CustomerAddress;

class CartController extends Controller
{
    /**
     * Display a listing of the resource.
     */

    /**
     * Store a newly created resource in storage.
     */
    public function add(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'product_variant_id' => 'nullable|exists:product_variants,id',
            'quantity' => 'required|integer|min:1',
        ]);

        $user = auth()->user();

        $cart = Cart::firstOrCreate([
            'user_id' => $user->id
        ]);

        $product = Product::findOrFail($request->product_id);

        $price = $product->sale_price ?: $product->price;

        if ($request->product_variant_id) {

            $variant = ProductVariant::findOrFail(
                $request->product_variant_id
            );

            $price = $variant->price;
        }

        $item = CartItem::where('cart_id', $cart->id)
            ->where('product_id', $request->product_id)
            ->where('product_variant_id', $request->product_variant_id)
            ->first();

        if ($item) {

            $item->quantity += $request->quantity;

            $item->save();
        } else {

            CartItem::create([
                'cart_id' => $cart->id,
                'product_id' => $request->product_id,
                'product_variant_id' => $request->product_variant_id,
                'quantity' => $request->quantity,
                'price' => $price,
            ]);
        }

        return response()->json([
            'status' => true,
            'message' => 'Product added to cart'
        ]);
    }
    /**
     * Display the specified resource.
     */
    public function listing()
    {
        $user = auth()->user();

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

        if (!$cart) {

            return response()->json([
                'status' => true,
                'cart_items' => [],
                'summary' => null
            ]);
        }

        $defaultAddress = CustomerAddress::where('user_id', $user->id)
            ->where('is_default', 1)
            ->first();

        $items = [];

        $itemTotal = 0;

        foreach ($cart->items as $item) {

            $subtotal = $item->price * $item->quantity;

            $itemTotal += $subtotal;

            $items[] = [
                'cart_item_id' => $item->id,
                'product_id' => $item->product_id,
                'name' => $item->product->name,
                'image' => optional(
                    $item->product->images->first()
                )->image,
                'variant' => optional(
                    $item->variant
                )->name,
                'quantity' => $item->quantity,
                'price' => $item->price,
                'subtotal' => $subtotal,
            ];
        }

        $deliveryFee = 190;
        $tax = 25;

        $discount = 0;
        $couponData = null;

        if ($cart->coupon) {

            if ($cart->coupon->discount_type == 'percentage') {

                $discount = ($itemTotal * $cart->coupon->discount_value) / 100;
            } elseif ($cart->coupon->discount_type == 'fixed') {

                $discount = $cart->coupon->discount_value;
            }

            $couponData = [
                'coupon_id' => $cart->coupon->id,
                'coupon_code' => $cart->coupon->code,
                'discount_type' => $cart->coupon->discount_type,
                'discount_value' => $cart->coupon->discount_value,
                'discount_amount' => round($discount, 2)
            ];
        }

        $grandTotal =
            $itemTotal +
            $deliveryFee +
            $tax -
            $discount;

        return response()->json([
            'status' => true,

            'deliver_to' => $defaultAddress ? [
                'address_id' => $defaultAddress->id,
                'name' => $defaultAddress->name,
                'phone' => $defaultAddress->phone,
                'address' => $defaultAddress->address,
                'landmark' => $defaultAddress->landmark,
                'city' => $defaultAddress->city,
                'state' => $defaultAddress->state,
                'country' => $defaultAddress->country,
                'pincode' => $defaultAddress->pincode,
            ] : null,

            'coupon' => $couponData,

            'cart_items_count' => count($items),

            'cart_items' => $items,

            'bill_summary' => [
                'item_total' => $itemTotal,
                'delivery_fee' => $deliveryFee,
                'discount' => round($discount, 2),
                'taxes' => $tax,
                'grand_total' => round($grandTotal, 2)
            ]
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function updateQuantity(Request $request)
    {

        $request->validate([
            'cart_item_id' => 'required|exists:cart_items,id',
            'quantity' => 'required|integer|min:1'
        ]);

        $item = CartItem::findOrFail(
            $request->cart_item_id
        );

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

        return response()->json([
            'status' => true,
            'message' => 'Quantity updated'
        ]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function remove($id)
    {

        $item = CartItem::findOrFail($id);

        $item->delete();

        return response()->json([
            'status' => true,
            'message' => 'Item removed'
        ]);
    }

    public function applyCoupon(Request $request)
    {

        $request->validate([
            'coupon_code' => 'required',
            'subtotal' => 'required|numeric|min:1'
        ]);

        $coupon = Coupon::where('code', $request->coupon_code)
            ->where('is_active', true)
            ->first();

        if (!$coupon) {
            return response()->json([
                'status' => false,
                'message' => 'Invalid coupon'
            ], 422);
        }

        if ($coupon->expires_at && now()->gt($coupon->expires_at)) {
            return response()->json([
                'status' => false,
                'message' => 'Coupon expired'
            ], 422);
        }

        if ($request->subtotal < $coupon->minimum_order_amount) {
            return response()->json([
                'status' => false,
                'message' => 'Minimum order amount not reached'
            ], 422);
        }

        $discount = 0;

        if ($coupon->discount_type == 'percentage') {
            $discount = ($request->subtotal * $coupon->discount_value) / 100;
        }

        if ($coupon->discount_type == 'fixed') {
            $discount = $coupon->discount_value;
        }
        $cart = Cart::where('user_id', auth()->id())->first();

        $cart->update([
            'coupon_id' => $coupon->id
        ]);
        return response()->json([
            'status' => true,
            'coupon_id' => $coupon->id,
            'discount' => round($discount, 2),
            'final_amount' => round($request->subtotal - $discount, 2)
        ]);
    }
    public function removeCoupon()
    {
        $cart = Cart::where('user_id', auth()->id())->first();

        if (!$cart) {
            return response()->json([
                'status' => false,
                'message' => 'Cart not found'
            ], 404);
        }

        if (!$cart->coupon_id) {
            return response()->json([
                'status' => false,
                'message' => 'No coupon applied'
            ], 422);
        }

        $cart->update([
            'coupon_id' => null
        ]);

        return response()->json([
            'status' => true,
            'message' => 'Coupon removed successfully'
        ]);
    }
}
