<?php
namespace App\Controller;
use App\Entity\Product;
use App\Controller\OutputController;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\AcceptHeader;
use Doctrine\ORM\ORMException;
use Doctrine\DBAL\DBALException;

class ProductController extends AbstractController
{
    /**
     * @Route("/api/product", name="product_create", methods = {"OPTIONS","POST"})
     */
    public function create()
    {
        try
        {
            $params = json_decode(file_get_contents('php://input'), true);

            $request = Request::createFromGlobals();

            if ($request->isMethod('POST')) {
                //ENTITY MANAGER
                $entityManager = $this->getDoctrine()->getManager();
                $product = new Product();
                $product->setName($params['name']);
                $product->setPrice($params['price']);
                $product->setDescription($params['description']);

                $entityManager->persist($product);
                $entityManager->flush();

                //GET PRODUCT
                $product = $this->getDoctrine()->getRepository(Product::class)->find($product->getProductId());
                if (!$product) {
                    throw $this->createNotFoundException('error');
                }

                //OUTPUT
                $response = new Response(json_encode($product->toArray()));

            }else{
                $response = new Response();
                $response -> setStatusCode(Response::HTTP_OK);
            }


            $response -> setStatusCode(Response::HTTP_OK);

        }

        catch (\Exception $e) {
            $response = New Response(json_encode(array('error' => $e->getMessage())));
            $response -> setStatusCode(Response::HTTP_BAD_REQUEST);
        }

        return $this->setheaders($response, "POST");
    }



    /**
    * @Route("/api/product/update", name="product_udpate", methods = {"OPTIONS","POST"})
    */
    public function update()
    {
        try
        {
            //PARAMS
            $params = json_decode(file_get_contents('php://input'), true);

            //GET PRODUCT
            $request = Request::createFromGlobals();
            if ($request->isMethod('POST')) {
                $product = $this->getDoctrine()->getRepository(Product::class)->find($request->request->get('productId'));
                if (!$product) {
                    throw $this->createNotFoundException('product not found');
                }

                //ENTITY MANAGER
                $entityManager = $this->getDoctrine()->getManager();
                $product->setName($params['name']);
                $product->setPrice($params['price']);
                $product->setDescription($params['description']);
                $entityManager->merge($product);
                $entityManager->flush();

                //OUTPUT
                $response = new Response(json_encode($product->toArray()));
            } else{
                $response = new Response();
            }

            $response -> setStatusCode(Response::HTTP_OK);

        }
        catch (\Exception $e) {
            $response = New Response(json_encode(array('error' => $e->getMessage())));
            $response -> setStatusCode(Response::HTTP_BAD_REQUEST);
        }

       return $this->setheaders($response,"POST");

    }


    /**
     * @Route("/api/product/delete/{id}", name="product_delete", methods = {"OPTIONS","DELETE"})
     */
    public function delete($id)
    {

        try {
            $request = Request::createFromGlobals();

            if ($request->isMethod('DELETE')) {


                //GET PRODUCT
                $repository = $this->getDoctrine()->getRepository(Product::class);
                $product = $repository->find($id);
                if (!$product) {
                    throw $this->createNotFoundException('product not found');
                }

                //OUTPUT
                $response = new Response(json_encode($product->toArray()));

                //ENTITY MANAGER
                $entityManager = $this->getDoctrine()->getManager();
                $entityManager->remove($product);
                $entityManager->flush();

            }else{
                $response = new Response();
            }

            $response -> setStatusCode(Response::HTTP_OK);

        }
        catch (\Exception $e) {
            $response = New Response(json_encode(array('error' => $e->getMessage())));
            $response -> setStatusCode(Response::HTTP_BAD_REQUEST);
        }


        return $this->setheaders($response,"DELETE");
    }



    /**
     * @Route("/api/products", name="products", methods = {"OPTIONS", "GET"})
     */
    public function products()
    {

        $response = [];
        try
        {
            //GET PRODUCTS
            $repository = $this->getDoctrine()->getRepository(Product::class);
            $products = $repository->findAll();
            foreach ($products as $product) {
                $response[] = $product->toArray();
            }

            //OUTPUT
            $response = new Response(json_encode(array('items' => $response)));
            $response -> setStatusCode(Response::HTTP_OK);

        }
        catch (\Exception $e) {
            $response = New Response(json_encode(array('error' => $e->getMessage())));
            $response -> setStatusCode(Response::HTTP_BAD_REQUEST);
        }


        return $this->setheaders($response,"GET");
    }

    //CORS
    function setheaders($response,$method) {
        $response->headers->set('Content-Type', 'application/json');
        $response->headers->set('Access-Control-Allow-Origin', 'http://localhost:4200');
        $response->headers->set('Access-Control-Allow-Headers','Cache-Control,X-Requested-With,Content-Type');
        $response->headers->set('Access-Control-Allow-Credentials','true');
        $response->headers->set('Cache-Control','no-cache');
        $response->headers->set('Access-Control-Allow-Methods',$method);
        return $response;
    }
}
