<?php

namespace App\Controller;

use App\Entity\TransfertPrestataireSiege;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class AdminController extends Controller
{
    private $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    /**
     * @Route("/admin/setenable/{type}/{id}", name="setenable")
     * @IsGranted("ROLE_ADMIN")
     */
    public function setEnableAction($type, $id, Request $request)
    {
        $referer = $request->headers->get('referer');
        if ($referer && !$request->isXmlHttpRequest()) {
            return $this->redirect($referer);
        } elseif (!$request->isXmlHttpRequest()) {
            return new Response('', Response::HTTP_BAD_REQUEST);
        }
        $status = 'success';
        try {
            $object = $this->em->getRepository(str_replace('.', ':', $type))->findOneById($id);
            if ($object && method_exists($object, 'setEnabled')) {
                $object->setEnabled(!$object->isEnabled());
                $this->em->persist($object);
                $this->em->flush();
            } else {
                $status = 'error';
            }
        } catch (\Exception $e) {
            $status = 'error';
        }
        return new JsonResponse(array('status' => $status, 'newvalue' => ($object->isEnabled()?'true':'false')));
    }

    /**
     * @Route("/admin/setreconverti/{id}", name="setreconverti")
     */
    public function setReconvertiAction($id, Request $request)
    {
        $referer = $request->headers->get('referer');
        if ($referer && !$request->isXmlHttpRequest()) {
            return $this->redirect($referer);
        } elseif (!$request->isXmlHttpRequest()) {
            return new Response('', Response::HTTP_BAD_REQUEST);
        }
        $status = 'success';
        try {
            $object = $this->em->getRepository(TransfertPrestataireSiege::class)->findOneById($id);
            if ($object && method_exists($object, 'setReconverti')) {
                $object->setReconverti(!$object->getReconverti());
                $this->em->persist($object);
                $this->em->flush();
            } else {
                $status = 'error';
            }
        } catch (\Exception $e) {
            $status = 'error';
        }
        return new JsonResponse(array('status' => $status, 'newvalue' => ($object->getReconverti()?'true':'false')));
    }
}
