<?php

namespace App\Handlers;

use App\Services\CartService;
use App\Support\Utf8Cleaner;
use Cart\Cart;
use Symfony\Component\HttpFoundation\JsonResponse;
use Openguru\OpenCartFramework\Http\Request;

class CartHandler
{
    private Cart $cart;
    private CartService $cartService;

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

    public function index(): JsonResponse
    {
        $items = $this->cartService->getCart();

        return new JsonResponse([
            'data' => Utf8Cleaner::clean($items),
        ]);
    }

    public function checkout(Request $request): JsonResponse
    {
        $items = $request->json();

        foreach ($items as $item) {
            $options = [];

            foreach ($item['options'] as $option) {
                if (! empty($option['value']) && ! empty($option['value']['product_option_value_id'])) {
                    $options[$option['product_option_id']] = $option['value']['product_option_value_id'];
                }
            }

            $this->cart->add(
                $item['productId'],
                $item['quantity'],
                $options,
            );
        }

        return new JsonResponse([
            'data' => Utf8Cleaner::clean($items),
        ]);
    }
}
