<?php

namespace App\Controller;

use Doctrine\ORM\EntityManagerInterface;
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;

/// @ Route ("/admina", name="admina_")
class AdminController extends Controller
{
    private $em;

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

    /**
     * @Route("/setenable/{type}/{id}", name="setenable")
     */
    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')));
    }

    // /**
    //  * Voir tous les dashboards
    //  * Route admin_index
    //  * @Route("/a", name="settings")
    //  */
    // public function settings()
    // {
    //     return $this->render('admin/settings.html.twig', [
    //         'controller_name' => 'AdminController',
    //     ]);
    // }
}
