<?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\AgentAppareil;
use App\Entity\Appareil;
use App\Entity\ContratTarif;
use App\Entity\EquipementFamille;
use App\Entity\EquipementPuissance;
use App\Entity\GroupeDroitPortail;
use App\Entity\Option;
use App\Entity\OptionTarif;
use App\Entity\ProduitPrestationTarif;
use App\Entity\ProduitType;
use App\Entity\SecteurTarif;
use App\Entity\TauxTva;
use App\Entity\TypeSav;
use App\Entity\Utilisateur;
use App\Form\UtilisateurType;
use App\Service\TarifManager;
use App\Utils\Functions;
use DateInterval;
use Produit;
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;

/**
 * @Route("/")
 * @IsGranted("ROLE_USER")
 *
 */
class TarifController extends ParentAdminController
{
    /**
     * attachements.
     * @Route("/configuration/tarifs", methods="GET", name="list_tarifs")
     */
    public function listTarifs(TarifManager $tarifManager): Response
    {

        $contratsTarifsFormatted = $tarifManager->getFormattedContratTarifs();
        $optionsTarifsFormatted = $tarifManager->getFormattedOptionTarifs();
        $prestationTarifsFormatted = $tarifManager->getFormattedPrestations();

        $prestationsContrats = $this->getDoctrine()->getRepository(\App\Entity\Produit::class)->findAllByIndexTypePrestationByType(ProduitType::TYPE_CONTRAT);
        $prestationsSecteurs = $this->getDoctrine()->getRepository(\App\Entity\Produit::class)->findAllByIndexTypePrestationByType(ProduitType::TYPE_SECTEUR);

        $fieldsContrat = ['type','puissance','mod 1','gt3-5ans','gt6-20ans'];
        $fieldsOption = ['option', 'type','mod 1','gt3-5ans','gt6-20ans'];

        $tabs = [
            ['name' => 'Contrat', 'entityName' => 'ContratTarif', 'columns' => [], 'rang_tri' => false, 'template' => 'tarif/contrat_tarif', 'datas' => $contratsTarifsFormatted, 'fieldsFile' => $fieldsContrat],
            ['name' => 'Option', 'entityName' => 'OptionTarif', 'template' => 'tarif/option_tarif', 'datas' => $optionsTarifsFormatted, 'fieldsFile' => $fieldsOption],
            ['name' => 'Prestation', 'template' => 'tarif/prestation_tarif', 'datas' => $prestationTarifsFormatted, 'prestationsContrat' => $prestationsContrats, 'prestationsSecteur' => $prestationsSecteurs],
            ['name' => 'Taux de TVA', 'entityName' => 'TauxTva', 'columns' => [
                ['dataField' => 'taux', 'caption' => 'Taux', 'sortOrder' => 'asc', 'alignment' => 'left', 'validationRules' => [["type" =>'required'], ['type' => 'numeric']]],
                ['dataField' => 'libelle', 'caption' => 'Libellé', 'validationRules' => [["type" =>'required']], 'editorOptions' => ['maxLength' => 20]],
                ['dataField' => 'date_application', 'caption' => 'Date application', 'dataType' => "date", 'format' => 'shortDate', 'validationRules' => [["type" =>'required']]],
                ['dataField' => 'date_fin_application', 'caption' => 'Date fin application', 'dataType' => "date", 'format' => 'shortDate'],
                ['dataField' =>'ancien_taux_tva',
                    'caption' => 'Ancien Taux',
                    'dataType' => 'number',
                    'lookup' => [
                        'dataSource'=>  "common.createCustomStore('TauxTva')",
                        'displayExpr'=> "libelle",
                        'valueExpr'=> "id",
                    ]
                ],
                ['dataField' => 'actif', 'caption' => 'Etat']
            ],
                'rang_tri' => false,
                'patch_path' => 'patch_taux_tva',
                'create_path' => 'post_taux_tva',
                'onRowValidation' => 'true',
            ]
        ];
        return $this->render('admin/list.html.twig', ['datagrid_style' => 'tab', 'tabs' => $tabs]);
    }

    /**
     * suppression période contratTarif.
     * @Route("/tarif/periode/{type}", methods="DELETE", name="delete_tarif_periode_type")
     */
    public function deleteTarifPeriodeType(Request $request, TarifManager $tarifManager, $type): Response {
        $periode = $request->request->get('periode');
        $periodeFormatted = $tarifManager->getFormattedPeriode(trim($periode));

        if ($type == 'contrat') {
            $this->getDoctrine()->getRepository(ContratTarif::class)->deleteByPeriode($periodeFormatted);
            $this->getDoctrine()->getRepository(ContratTarif::class)->updateLastPeriode($periodeFormatted);
        }
        if ($type == 'option') {
            $this->getDoctrine()->getRepository(OptionTarif::class)->deleteByPeriode($periodeFormatted);
            $this->getDoctrine()->getRepository(OptionTarif::class)->updateLastPeriode($periodeFormatted);
        }
        if ($type == 'prestation') {
            $this->getDoctrine()->getRepository(ProduitPrestationTarif::class)->deleteByPeriode($periodeFormatted);
            $this->getDoctrine()->getRepository(ProduitPrestationTarif::class)->updateLastPeriode($periodeFormatted);
            $this->getDoctrine()->getRepository(SecteurTarif::class)->deleteByPeriode($periodeFormatted);
            $this->getDoctrine()->getRepository(SecteurTarif::class)->updateLastPeriode($periodeFormatted);
        }

        return new JsonResponse(['messages' => ['success' => ['Période supprimée avec succès']], 'periode' => $periodeFormatted['date_debut_1_day']->format('d/m/Y')], Response::HTTP_OK);

    }

    /**
     * Ajout periode tarif
     * @Route("/tarif/periode/{type}", methods="POST", name="add_tarif_periode_type")
     */
    public function ajoutTarifPeriodeType(Request $request, TarifManager $tarifManager, $type) {
        $date_debut = $request->request->get('date_debut');

        if ($type == 'prestation') {
            $result = $tarifManager->addPrestations($request->request, $date_debut);
        } else {
            $fichier_tarif = $request->files->get('fichier_tarif')->getRealPath();
            $result = $tarifManager->parseFileTarif($fichier_tarif, $type, $date_debut);
        }
        $this->addFlash($result['type'], $result['message']);

        return $this->redirect($this->generateUrl('list_tarifs'));
    }

    /**
     * Ajout periode tarif
     * @Route("/tarif/periode/update/{type}", methods="POST", name="update_tarif_periode_type")
     */
    public function updateTarifPeriodeType(Request $request, TarifManager $tarifManager, $type) {
        $date_debut = $request->request->get('date_debut');
        $old_date = $request->request->get('old_date');

        if ($type == 'prestation') {
            $result = $tarifManager->addPrestations($request->request, $date_debut, $old_date);
        } else {
            $fichier_tarif = $request->files->get('fichier_tarif')->getRealPath();
            $result = $tarifManager->parseFileTarif($fichier_tarif, $type, $date_debut, $old_date);
        }

        $this->addFlash($result['type'], $result['message']);

        return $this->redirect($this->generateUrl('list_tarifs'));
    }

    /**
     * Ajout periode tarif
     * @Route("/tarif/periode/export/{type}", methods="GET", name="export_tarif_periode_type")
     */
    public function exportCsvTarifPeriodeType($type, TarifManager $tarifManager, Request $request) {

        $content = null;
        $periode = $request->query->get('periode');

        $periodeFormatted = $tarifManager->getFormattedPeriode(trim($periode));
        if ($periode) {
            $content = $tarifManager->getCsvData($type, $periodeFormatted);
        }

        $response = new Response($content);
        $response->headers->set('Content-Disposition', 'attachment; filename="'. $type . '_tarif_' .  $periode . '.csv"');
        $response->headers->set('Content-Type', 'text/csv;charset=UTF-8');

        return $response;
    }

    /**
     * create agent  qualification
     * @Route("/agent/{id}/appareil", methods="POST", name="post_agent_appareil")
     *  * @Route("/agent/{id}/appareil/{idappareil}", methods="PATCH", name="patch_agent_appareil")
     */
    public function createAgentAppareil(Utilisateur $agent, $idappareil = null,  Request $request) {
        $em = $this->getDoctrine()->getManager();
        $datas = $request->request->all();

        foreach($datas as $key => $value) {
            $datas[$key] = Functions::clearData($value);
        }

        if (isset($datas['appareil']) || $idappareil) {
            if (!$idappareil) {
                $appareil = $this->getDoctrine()->getRepository(Appareil::class)->find($datas['appareil']);
                $agentAppareil = null;
            }
            else {
                $appareil = $this->getDoctrine()->getRepository(Appareil::class)->find($idappareil);
                $agentAppareil = $this->getDoctrine()->getRepository(AgentAppareil::class)->findOneBy(['utilisateur_agent' => $agent, 'appareil' => $appareil]);
            }

            if ($appareil) {
                if (!$agentAppareil)$agentAppareil = new AgentAppareil();
                $agentAppareil->setAppareil($appareil);
                $agentAppareil->setUtilisateurAgent($agent);

                if (isset($datas['commentaire'])) $agentAppareil->setCommentaire($datas['commentaire']);
                if (isset($datas['reference'])) $agentAppareil->setReference($datas['reference']);
                if (isset($datas['date_delivrance'])) {
                    $date = Functions::getDateTimeFromString($datas['date_delivrance']);
                    $agentAppareil->setDateDelivrance($date);
                }
                if (isset($datas['date_limite']) && $appareil->getMetrologique()) {
                    $date = Functions::getDateTimeFromString($datas['date_limite']);
                    $agentAppareil->setDateLimiteRenouvellement($date);
                }
                if (isset($datas['date_restitution']) && !empty($datas['date_restitution'])) {
                    $date = Functions::getDateTimeFromString($datas['date_restitution']);
                    $agentAppareil->setDateRestitution($date);
                }

                $em->persist($agentAppareil);
                $em->flush();
            }
        }

        return new JsonResponse(['messages' => ['success' => ["Ajout effectué avec succès"]]], Response::HTTP_OK);
    }

    /**
     * create maj TAUX TVA
     * @Route("/tarif/taux_tva", methods="POST", name="post_taux_tva")
     * @Route("/tarif/taux_tva/{id}", methods="PATCH", name="patch_taux_tva")
     */
    public function createTauxTVA($id = null,  Request $request) {
        $em = $this->getDoctrine()->getManager();
        $datas = $request->request->all();

        foreach($datas as $key => $value) {
            $datas[$key] = Functions::clearData($value);
        }

        $tauxTva = (!$id) ? new TauxTva() : $this->getDoctrine()->getRepository(TauxTva::class)->find($id);

        if (isset($datas['actif'])) {
            if ($datas['actif'] == 'true' || empty($datas['actif'])) $tauxTva->setActif(true);
            else $tauxTva->setActif(false);
        }
        if (isset($datas['date_application'])) {
            $date = Functions::getDateTimeFromString($datas['date_application']);
            $tauxTva->setDateApplication($date);
        }
        if (isset($datas['date_fin_application'])) {
            if (empty($datas['date_fin_application'])) $tauxTva->setDateFinApplication(null);
            else {
                $date = Functions::getDateTimeFromString($datas['date_fin_application']);
                $tauxTva->setDateFinApplication($date);
            }

        }
        if (isset($datas['libelle']) && !empty($datas['libelle'])) $tauxTva->setLibelle($datas['libelle']);
        if (isset($datas['taux']) && !empty($datas['taux'])) $tauxTva->setTaux($datas['taux']);
        if (isset($datas['ancien_taux_tva']) && $tauxTva->getAncientTauxTvaId() != $datas['ancien_taux_tva']) {
            $ancienTauxTva = $this->getDoctrine()->getRepository(TauxTva::class)->find($datas['ancien_taux_tva']);
            $tauxTva->setAncienTauxTva($ancienTauxTva);
            $day =  new DateInterval('P1D');
            $now = new \DateTime();
            $dateFinApplication = $tauxTva->getDateApplication()->sub($day);
            $ancienTauxTva->setDateFinApplication($dateFinApplication);
            if ($dateFinApplication < $now) $ancienTauxTva->setActif(false);
            $em->persist($ancienTauxTva);
        }

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

        return new JsonResponse(['messages' => ['success' => ["Ajout/Modification effectué avec succès"]]], Response::HTTP_OK);
    }

}
