<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace App\Controller\Admin;

use App\Entity\Equipement;
use App\Entity\EquipementFamille;
use App\Entity\EquipementPuissance;
use App\Entity\EquipementType;
use App\Entity\GroupeDroitPortail;
use App\Entity\Option;
use App\Entity\Produit;
use App\Entity\ProduitPhoto;
use App\Entity\ProduitStockSite;
use App\Entity\Site;
use App\Entity\TypeSav;
use App\Entity\TypeUtilisateur;
use App\Entity\Utilisateur;
use App\Form\UtilisateurType;
use App\Service\TarifManager;
use App\Utils\Functions;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * @IsGranted("ROLE_USER")
 *
 */
class ProduitController extends ParentAdminController
{
    /**
     * @Route("/produits/{type}", methods="GET", name="get_produits_type")
     */
    public function getProduitsType(SerializerInterface $serializer, Request $request, $type) {

        $skip = $request->query->get('skip');
        $take = $request->query->get('take');
        $sort = json_decode($request->query->get('sort'), true);

        $filters = json_decode($request->query->get('filter'), true);
        $datasType = ['p_gu_etendue' => 'smallint', 'pt_visible_tablette' => 'boolean',  'pt_visible_tablette' => 'boolean', 'pt_gere_en_stock' => 'boolean', 'p_prix_ht' => 'number', 'pp_photo' => 'binary'];
        $filtersBDD = Functions::formatFiltersForBdd($filters, $datasType);

        if ($type == 'equipement_meaux') {
            $entities = $this->getDoctrine()->getManager()->getRepository(ProduitStockSite::class)->getEquipementMeaux($skip, $take, $filtersBDD, $sort);
            $total = $this->getDoctrine()->getManager()->getRepository(ProduitStockSite::class)->countEquipementsMeaux($filtersBDD);
        } else if ($type == 'consommables_meaux') {
            $entities = $this->getDoctrine()->getManager()->getRepository(ProduitStockSite::class)->getConsommablesMeaux($skip, $take, $filtersBDD, $sort);
            $total = $this->getDoctrine()->getManager()->getRepository(ProduitStockSite::class)->countConsommablesMeaux($filtersBDD);
        } else if ($type == 'consommables_site') {
            $entities = $this->getDoctrine()->getManager()->getRepository(Produit::class)->getConsommablesSite($skip, $take, $filtersBDD, $sort);
            $total = $this->getDoctrine()->getManager()->getRepository(Produit::class)->countConsommablesSite($filtersBDD);
        }

        $datas = Functions::getSerialisedEntities($entities, $serializer, 'site_list');
        $response = json_encode(['data' => $datas, 'totalCount' => $total]);

        return new Response(
            $response,
            Response::HTTP_OK,
            ['Content-type' => 'application/json']
        );
    }

    /**
     * @Route("/create/produit/{id}", methods={"POST", "PATCH"}, name="create_maj_produit")
     */
    public function createMajProduit($id= null, Request $request) {
        $em = $this->getDoctrine()->getManager();
        $datas = $request->request->all();
        $message = 'Création';
        if ($datas) {
            //  error_log
            if ($id) {
                $produit = $em->getRepository(Produit::class)->find($id);
                $message = 'Modification';
            }  else   $produit = new Produit();
            $produit = $this->assignDatasProduit($produit, $datas);

            $em->persist($produit);
            $em->flush();

        }

        return new JsonResponse(['messages' => ['success' => ["$message effectuée avec succès"]]], 200);
    }

    /**
     * Lists all entities.
     * @Route("/patch/produit_type/{id}", methods={"PATCH","POST"}, name="patch_produit_type")
     */
    public function patchProduitType($id = null, Request $request, SerializerInterface $serializer): Response
    {
        $em = $this->getDoctrine()->getManager();
        $datas = $request->request->all();
        $arrayKey = explode('-', $id);
        $idProduit =  $arrayKey[0];

        $produit = $em->getRepository(Produit::class)->find($idProduit);
        $site = $em->getRepository(Site::class)->find($arrayKey[1]);

        if (isset($datas['pt_gere_en_stock'])) {
            if ($produitStockSite = $em->getRepository(ProduitStockSite::class)->findOneBy(['produit' => $produit, 'site' => $site])) {
                $value = ($datas['pt_gere_en_stock'] == 'oui') ? true : false;
                $produitStockSite->setGereEnStock($value);
                $em->persist($produitStockSite);
            }
        }
        if ($_FILES) {
            $produitPhoto = new ProduitPhoto();
            $produitPhoto->setNom($_FILES['files']['name'][0]);
            $photo64 = 'data:' . $_FILES['files']['type'][0] . ';base64,' . base64_encode(file_get_contents($_FILES['files']['tmp_name'][0]));
            $produitPhoto->setPhoto($photo64);
            if ($produit->getProduitPhotos()->count() == 0) $produitPhoto->setPhotoPrincipale(true);
            $produit->addProduitPhoto($produitPhoto);
            $em->persist($produit);
            $em->flush();

            $message = 'Photos ajoutée(s) avec succès';

           return $this->render('produit/_produit_photos.html.twig', ['datas' => $produit->getProduitPhotos(), 'id' => $id, 'message' => $message]);
        }

        $em->flush();

        return new JsonResponse('', Response::HTTP_OK);
    }

    /**
     * @Route("/produit_photos/{id}", methods="GET", name="get_produit_photos")
     */
    public function getProduitPhotos($id, SerializerInterface $serializer, Request $request) {
        $em = $this->getDoctrine()->getManager();
        $arrayKey = explode('-', $id);
        $datas = [];

        if ($produit = $em->getRepository(Produit::class)->find($arrayKey[0])) {
            $datas = $produit->getProduitPhotos();
        }

        return $this->render('produit/_produit_photos.html.twig', ['datas' => $datas, 'id' => $id]);
    }

    /**
     * @Route("/produit_photos/photo/{id}", methods="GET", name="get_produit_photo")
     */
    public function getProduitPhoto($id, Request $request) {
        $em = $this->getDoctrine()->getManager();
        $produitPhoto = $em->getRepository(ProduitPhoto::class)->find($id);
        $photo64 = $produitPhoto->getPhoto();
        $infoSize = \getimagesize($photo64);
        $coeff = $infoSize['0'] / $infoSize['1'];
        $width = ($coeff > 2.4) ? 400 : 250;
        $height = ($infoSize['0'] > $infoSize['1']) ? $width / $coeff : $width;

        return $this->render('produit/_photo.html.twig', [
            'produitPhoto' => $produitPhoto,
            'photo64' => $photo64,
            'height' => $height,
            'width' => $width,
        ]);
    }

    /**
     * @Route("/produit_photos/{id}", methods="DELETE", name="delete_produit_photo")
     */
    public function deleteProduitPhoto($id) {
        $em = $this->getDoctrine()->getManager();
        if ($produitPhoto = $em->getRepository(ProduitPhoto::class)->find($id)) {
            $em->remove($produitPhoto);
            $em->flush();
            return new JsonResponse(['messages' => ['success' => ["Suppression effectuée avec succès"]]], Response::HTTP_OK);
        } else {
            return new JsonResponse('', Response::HTTP_NOT_FOUND);
        }

    }
    /**
     * @Route("/produit_photos/{id}", methods="PATCH", name="patch_produit_photo")
     */
    public function patchProduitPhoto($id) {
        $em = $this->getDoctrine()->getManager();
        if ($produitPhoto = $em->getRepository(ProduitPhoto::class)->find($id)) {
            foreach($produitPhoto->getProduit()->getProduitPhotos()  as $produitPhotoTmp) {
                if ($produitPhoto == $produitPhotoTmp) {
                    $produitPhotoTmp->setPhotoPrincipale(true);
                } else {
                    $produitPhotoTmp->setPhotoPrincipale(false);
                }
                $em->persist($produitPhotoTmp);
            }
            $em->flush();
            return new JsonResponse('', Response::HTTP_OK);
        } else {
            return new JsonResponse('', Response::HTTP_NOT_FOUND);
        }
    }

    private function assignDatasProduit($produit, $datas) {
        $em = $this->getDoctrine()->getManager();

        if (isset($datas['pt_gere_en_stock'])) {
            $valueGereStock = ($datas['pt_gere_en_stock'] == 'oui') ? true : false;
        }
        if (isset($datas['s_nom'])) $produit->setSite($em->getRepository(Site::class)->findOneBy(['nom' => $datas['s_nom']]));

        if (isset($datas['pt_emplacement']) || isset($valueGereStock)) {
            if ($produit->getId()) {
                $produitStockSite = $produit->getProduitStockSites()->first();
                $produit->setDateModification(new \DateTime());
            } else {
                $produitStockSite = new ProduitStockSite();
                $produit->setDateCreation(new \DateTime());
                $produit->addProduitStockSite($produitStockSite);
            }

            if (isset($datas['pt_emplacement'])) $produitStockSite->setEmplacement($datas['pt_emplacement']);
            if (isset($valueGereStock)) $produitStockSite->setGereEnStock($valueGereStock);
            $produitStockSite->setSite($produit->getSite());

            $em->persist($produitStockSite);
        }

        if (isset($datas['p_code'])) $produit->setCode($datas['p_code']);
        if (isset($datas['p_designation']))$produit->setDesignation($datas['p_designation']);
        if (isset($datas['p_gtin']))$produit->setGtin($datas['p_gtin']);
        if (isset($datas['p_prix_ht']))$produit->setPrixHt($datas['p_prix_ht']);

        return $produit;
    }

}
