<?php

namespace App\Controller\Api;

use App\Entity\Order;
use App\Enum\PaymentType;
use App\Entity\UserAddress;
use App\Request\Response200;
use App\Request\Response422;
use App\Traits\PaymentTrait;
use OpenApi\Annotations as OA;
use App\Request\Response200Json;
use App\Request\Response200Message;
use App\Controller\Api\ApiController;
use App\Request\Order\RequestAddOrder;
use Nelmio\ApiDocBundle\Annotation\Model;
use Nelmio\ApiDocBundle\Annotation\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\Controller\Annotations as Rest;
use Symfony\Component\Validator\Validator\ValidatorInterface;

class OrderController extends ApiController implements PaymentType
{
    use PaymentTrait;

    /**
     * Add order
     *
     * @Rest\Post("/api/order", name="api_order_add")
     * @Security(name="Bearer")
     * @OA\Tag(name="order")
     * @OA\Response(
     *     response=200,
     *     description="Ok response",
     *     @Model(type=Response200Message::class)
     * )
     * @OA\Response(
     *     response=422,
     *     description="Error response",
     *     @Model(type=Response422::class)
     * )
     * @OA\RequestBody(
     *       @OA\MediaType(
     *           mediaType="multipart/form-data",
     *           @OA\Schema(ref=@Model(type=RequestAddOrder::class))
     *      )
     * )
     *
     * @param Request $request
     * @param ValidatorInterface $validator
     *
     * @return Response
     */
    public function add(Request $request, ValidatorInterface $validator): Response
    {
        $errors = $validator->validate(
                new RequestAddOrder($request)
        );
        if (count($errors) > 0)
        {
            return $this->respondValidationError($errors);
        }

        $orderCode = uniqid();

        if ($request->get('paymentType') === self::MBWAY) {
            $payment = $this->createMBWAYPayment($request, $orderCode);
        } elseif ($request->get('paymentType') === self::MULTIBANCO) {
            $payment = $this->createMULTIBANCOPayment($request, $orderCode);
        } else {
            return new Response('Invalid Payment Type', Response::HTTP_NOT_FOUND);
        }
        dd('se creo el pago');

        $entity = new Order();
        $entity
            ->setSendNow($request->get('sendNow'))
            ->setDeliveryDate($request->get('deliveryDate'))
            ->setSubtotal($request->get('subtotal'))
            ->setFee($request->get('fee'))
            ->setTotal($request->get('total'))
            ->setPaymentType($request->get('paymentType'))
            ->setRestaurant($request->get('restauranteId'))
            ->setUserClient($request->get('userId'))
        ;

        $this->em->persist($entity);
        $this->em->flush();

        return $this->respondWithSuccess(sprintf($this->trans('general.successfullRegistration'), $entity->getId()));
    }

}
