<?php

namespace AppBundle\Controller\Admin;

use AppBundle\Entity\Company;
use AppBundle\Form\Type\CompanyType;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Translation\TranslatorInterface;

/**
 * @Route("/settings")
 */
class CompanyController extends Controller
{
    /**
     * @var EntityManagerInterface
     */
    private $em;

    /**
     * @var TranslatorInterface
     */
    private $translator;
    
    public function __construct(EntityManagerInterface $em, TranslatorInterface $translator)
    {
        $this->em = $em;
        $this->translator = $translator;
    }

    /**
     * Lists all company entities.
     *
     * @Route(
     *     "/company/{page}",
     *     requirements={"page": "\d+"},
     *     name="company_index"
     * )
     *
     * @Method("GET")
     *
     * @param Request $request
     * @param int $page
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \Exception
     */
    public function indexAction(Request $request, int $page = 1)
    {
        $resultsMaxPerPage = $this->getParameter('results.admin.max_per_page');
        $criteria = [];
        if (null !== $name = $request->query->get('name')) {
            $criteria['name'] = ['like', $name];
        }

        $companies = $this->em->getRepository(Company::class)->paginate(
            $criteria,
            ['name' => 'ASC'],
            $resultsMaxPerPage,
            ($page - 1) * $resultsMaxPerPage,
            ['users', 'peeOperations']
        );

        return $this->render('Admin/Settings/company/index.html.twig', [
            'companies' => $companies,
            'nb_pages' => ceil(count($companies) / $resultsMaxPerPage),
        ]);
    }

    /**
     * Creates a new company entity.
     *
     * @Route("/company/add", name="company_add")
     * @Method({"GET", "POST"})
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function addAction(Request $request)
    {
        $company = new Company();
        $form = $this->createForm(CompanyType::class, $company);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->em->persist($company);
            $this->em->flush();

            return $this->redirectToRoute('company_edit', ['id' => $company->getId()]);
        }

        return $this->render('Admin/Settings/company/add.html.twig', [
            'company' => $company,
            'form' => $form->createView(),
        ]);
    }

    /**
     * Displays a form to edit an existing company entity.
     *
     * @Route("/company/edit/{id}", name="company_edit")
     * @Method({"GET", "POST"})
     *
     * @param Request $request
     * @param Company $company The company entity
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function editAction(Request $request, Company $company)
    {
        $editForm = $this->createForm(CompanyType::class, $company);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $this->em->flush();

            $this->addFlash('success', $this->translator->trans('notice.company.updated', ['%name%' => $company->getName()], 'notice'));

            return $this->redirectToRoute('company_edit', ['id' => $company->getId()]);
        }

        return $this->render('Admin/Settings/company/edit.html.twig', [
            'company' => $company,
            'edit_form' => $editForm->createView(),
        ]);
    }

    /**
     * Enable or disable a company for the users.
     *
     * @Route("/company/enable/{id}", name="company_enable")
     * @Method({"GET", "POST"})
     *
     * @param Company $company The company entity
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function enableAction(Company $company)
    {
        $availableForUsers = $company->isAvailableForUsers();

        // Check if we could disable the given
        if ($availableForUsers && count($company->getUsers()) > 0) {
            throw $this->createAccessDeniedException($this->translator->trans('notice.company.disabled.failure', [], 'notice'));
        }

        $company->setAvailableForUsers(!$availableForUsers);

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

        return $this->redirectToRoute('company_index');
    }

    /**
     * Deletes a company entity.
     *
     * @Route("/company/delete/{id}", name="company_delete")
     * @Method({"GET"})
     *
     * @param Company $company The company entity
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function deleteAction(Company $company)
    {
        if (!$company->isDeletable()) {
            throw $this->createAccessDeniedException($this->translator->trans('notice.company.removed.failure', [], 'notice'));
        }

        $this->em->remove($company);
        $this->em->flush();

        return $this->redirectToRoute('company_index');
    }
}
