<?php

/*
 * kohinos_cooperatic
 * Copyright (C) 2019-2020  ADML63
 * Copyright (C) 2020- Cooperatic
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
 
namespace App\Controller;

use App\Entity\User;
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\HttpFoundation\StreamedResponse;
use Symfony\Component\Routing\Annotation\Route;
use Geocoder\Provider\Nominatim\Nominatim;
use Geocoder\Query\GeocodeQuery;

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';
                $this->get('session')->getFlashBag()->add(
                    'notice',
                    'Erreur : veuillez recharger la page et réessayer !'
                );
            }
        } catch (\Exception $e) {
            $status = 'error';
            $this->get('session')->getFlashBag()->add(
                'notice',
                'Erreur : veuillez recharger la page et réessayer !'
            );
        }
        return new JsonResponse(array('status' => $status, 'newvalue' => ($object->isEnabled()?'true':'false')));
    }

    /**
     * @Route("/admin/setreconverti/{id}", name="setreconverti")
     * @IsGranted({"ROLE_TRESORIER", "ROLE_ADMIN_TRANSFERT_GERER_VIEW"})
     */
    public function setReconvertiAction(TransfertPrestataireSiege $object, 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 {
            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')));
    }

    /**
     * @Route("/admin/getcsv", name="getcsv")
     * @IsGranted({"ROLE_SUPER_ADMIN", "ROLE_ADMIN_IMPORT_EDIT", "ROLE_ADMIN_IMPORT_LIST", "ROLE_ADMIN_IMPORT_CREATE", "ROLE_ADMIN_IMPORT_VIEW", "ROLE_ADMIN_IMPORT_DELETE", "ROLE_ADMIN_IMPORT_EXPORT", "ROLE_ADMIN_IMPORT_ALL"})
     */
    public function getCsvAction(Request $request)
    {
        $data = $request->get('data');
        $header = $request->get('header');
        $response = new StreamedResponse();
        $response->setCallback(function () use ($data, $header) {
            $handle = fopen('php://output', 'w+');
            // Nom des colonnes du CSV
            fputcsv($handle, explode(';', $header), ';');

            //Champs
            foreach ($data as $row) {
                // fwrite($handle, $row);
                fputcsv($handle, explode(';', $row), ';');
            }
            fclose($handle);
        });
        $response->setStatusCode(200);
        $response->headers->set('Content-Type', 'text/csv; charset=utf-8');
        $response->headers->set('Content-Disposition', 'attachment; filename="export.csv"');

        return $response;
    }
}
