<?php

namespace App\Http\Controllers\Api\V1\Customer;

use App\Http\Controllers\Controller;
use App\Services\CartService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CartController extends Controller
{
    protected $cartService;

    public function __construct(CartService $cartService)
    {
        $this->cartService = $cartService;
    }

    public function index()
    {
        $userId = auth()->id();
        if (!$userId) {
            return response()->json(['error' => 'Unauthenticated'], 401);
        }

        return response()->json([
            'cart' => $this->cartService->getCartDetails($userId),
            'totals' => $this->cartService->calculateTotals($userId)
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'variant_id' => 'nullable|exists:product_variants,id',
            'qty' => 'integer|min:1',
            'is_flash_sale' => 'nullable|boolean'
        ]);

        $userId = auth()->id();
        if (!$userId) {
            return response()->json(['error' => 'Unauthenticated'], 401);
        }

        try {
            $item = $this->cartService->addItem(
                $userId,
                $request->product_id,
                $request->variant_id,
                $request->qty ?? 1,
                (bool)$request->input('is_flash_sale', false)
            );

            return response()->json([
                'success' => true,
                'message' => 'Item added to cart successfully.',
                'item' => $item,
                'totals' => $this->cartService->calculateTotals($userId)
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 422);
        }
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'qty' => 'nullable|integer|min:0',
            'variant_id' => 'nullable|exists:product_variants,id'
        ]);

        $userId = auth()->id();
        if (!$userId) {
            return response()->json(['error' => 'Unauthenticated'], 401);
        }

        try {
            $item = null;
            if ($request->has('variant_id')) {
                $item = $this->cartService->updateItemVariant($userId, $id, $request->variant_id);
            }
            if ($request->has('qty')) {
                $item = $this->cartService->updateItemQty($userId, $id, $request->qty);
            }
            return response()->json([
                'success' => true,
                'message' => 'Cart updated successfully.',
                'item' => $item,
                'totals' => $this->cartService->calculateTotals($userId)
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 422);
        }
    }

    public function destroy($id)
    {
        $userId = auth()->id();
        if (!$userId) {
            return response()->json(['error' => 'Unauthenticated'], 401);
        }

        try {
            $this->cartService->removeItem($userId, $id);
            return response()->json([
                'success' => true,
                'message' => 'Item removed from cart.',
                'totals' => $this->cartService->calculateTotals($userId)
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 422);
        }
    }

    public function clear()
    {
        $userId = auth()->id();
        if (!$userId) {
            return response()->json(['error' => 'Unauthenticated'], 401);
        }

        $this->cartService->clearCart($userId);
        return response()->json([
            'success' => true,
            'message' => 'Cart cleared.',
            'totals' => ['subtotal' => 0, 'total_weight' => 0, 'item_count' => 0]
        ]);
    }
}
