<?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\Adresse;
use App\Entity\CategoriePro;
use App\Entity\Client;
use App\Entity\Contrat;
use App\Entity\ContratMotifResiliation;
use App\Entity\ContratType;
use App\Entity\Equipement;
use App\Entity\EquipementAlimentation;
use App\Entity\EquipementFamille;
use App\Entity\EquipementFamilleContrat;
use App\Entity\EquipementFluide;
use App\Entity\EquipementGroupeType;
use App\Entity\EquipementLocal;
use App\Entity\EquipementMarque;
use App\Entity\EquipementPuissance;
use App\Entity\EquipementType;
use App\Entity\EtatCivil;
use App\Entity\Groupe;
use App\Entity\GroupeType;
use App\Entity\Intervention;
use App\Entity\Energie;
use App\Entity\MoyenPaiement;
use App\Entity\Option;
use App\Entity\HorairePassage;
use App\Entity\Produit;
use App\Entity\ProduitPrestationTarif;
use App\Entity\ProtectionSanitaire;
use App\Entity\Puissance;
use App\Entity\Raccordement;
use App\Entity\RobinetRemplissage;
use App\Entity\Secteur;
use App\Entity\SecteurTarif;
use App\Entity\Site;
use App\Entity\TauxTva;
use App\Entity\TypeClient;
use App\Entity\TypeComplement;
use App\Entity\TypeComplementAdresse;
use App\Entity\TypeEnergie;
use App\Entity\TypeInstallation;
use App\Entity\TypeLogement;
use App\Entity\TypeZone;
use App\Entity\Utilisateur;
use App\Form\ClientType;
use App\Repository\ContratRepository;
use App\Service\ClientManager;
use App\Service\FiltreManager;
use App\Service\LockManager;
use App\Utils\Functions;
use AppBundle\Entity\Parametres;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Security\Core\Security;

/**
 * Controller used to manage blog contents in the backend.
 *
 * Please note that the application backend is developed manually for learning
 * purposes. However, in your real Symfony application you should use any of the
 * existing bundles that let you generate ready-to-use backends without effort.
 *
 * See http://knpbundles.com/keyword/admin
 *
 * @Route("/clients")
 * @IsGranted("ROLE_USER")
 *
 */
use App\Entity\CommunicationClient;
use App\Entity\CommunicationCanal;
use App\Entity\CommunicationType;
class ClientController extends ParentAdminController
{
    /**
     * Nouveau Client
     * @Route("/nouveau_client", methods={"GET", "POST"}, name="nouveau_client")
     */
    public function nouveauClient(Request $request, ClientManager $clientManager): Response
    {
        $datas = $request->request->all();
        $em = $this->getDoctrine()->getManager();

        if (isset($datas['type_client'])) {
            $client = $clientManager->createClient($datas);
            $em->persist($client);
            $em->flush();
            $em->refresh($client);
        }

        return $this->redirect($this->generateUrl('show_client', ['id' => $client->getId()]) .'?id_equipement='.$client->getEquipements()[0]->getId());
    }

    /**
     * Lists all entities.
     * @Route("/verif_doublon", methods="POST", name="verif_doublon_client")
     */
    public function verifDoublonClient(Request $request) {
        $datas = $request->request->all();
        $message = 'Client ok';
        $type= 'success';

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

        if (((isset($datas['nom']) && !empty($datas['nom'])) || (isset($datas['entreprise']) && !empty($datas['entreprise']) && isset($datas['categorie_pro']) && !empty($datas['categorie_pro']))) &&
            isset($datas['adresse']) && !empty($datas['adresse']) &&
            isset($datas['code_postal']) && !empty($datas['code_postal']) &&
            isset($datas['ville']) && !empty($datas['ville']) &&
            isset($datas['type']) && !empty($datas['type']) ) {
            $clients = $this->getDoctrine()->getRepository(Client::class)->getDoublon($datas);
            if (count($clients)>0) {
                $message = 'Client déjà existant';
                $type = 'danger';
            }
        } else {
            $message = 'Champs non remplis';
            $type='danger';
        }

        return new JsonResponse(['type' => $type, 'message' => $message]);
    }

    /**
     * Lists all entities.
     * @Route("/liste_clients", methods="GET", name="list_clients")
     */
    public function listClients(FiltreManager $filtreManager): Response
    {
        $sitesNom = $this->getDoctrine()->getRepository(Site::class)->getAllIdNom();
        $typesClient= $this->getDoctrine()->getRepository(TypeClient::class)->getAllIdNom();
        $categoriesPro = $this->getDoctrine()->getRepository(CategoriePro::class)->findAll();
        $civilites = $this->getDoctrine()->getRepository(EtatCivil::class)->findAll();
        $typesClientAll = $this->getDoctrine()->getRepository(TypeClient::class)->findAll();
        $typesLogement = $this->getDoctrine()->getRepository(TypeLogement::class)->getAllIdNom();
        $typesEquipement =  $this->getDoctrine()->getRepository(EquipementType::class)->getAllIdNom();
        $famillesEquipement = $this->getDoctrine()->getRepository(EquipementFamille::class)->getAllIdNom();
        $typesContrat = $this->getDoctrine()->getRepository(ContratType::class)->getAllIdNom();
        $typesFamilleContrat = $this->getDoctrine()->getRepository(EquipementFamilleContrat::class)->getAllIdNom();
        $options = $this->getDoctrine()->getRepository(Option::class)->getAllIdNom();
        $equipementsLocal = $this->getDoctrine()->getRepository(EquipementLocal::class)->getAllIdNom();
        $raccordement = $this->getDoctrine()->getRepository(Raccordement::class)->getAllIdNom();
        $secteurs = $this->getDoctrine()->getRepository(Secteur::class)->getAllIdNom();
        $filterOperationsString = ["startswith","contains"];
        $filterOperationsInteger = ["="];
        $filterOperationsDate = ['=','<','>', '<=', '>=','between'];

        $booleanChoix = [['text' => 'Oui', 'value' => 'oui'],['text' => 'Non', 'value' => 'non']];

        $datas = [
            'columns' => [
                ['dataField' =>'csss_nom', 'caption' => 'Site Client',  'allowSearch' => false,'allowSorting' => false, 'headerFilter' => ['dataSource' => $sitesNom], 'filterOperations' => $filterOperationsString],
                ['dataField' =>'esite_nom', 'caption' => 'Site Equipement',  'allowSearch' => false ,'allowSorting' => false,'headerFilter' => ['dataSource' => $sitesNom], 'filterOperations' => $filterOperationsString, 'visible' => false, 'selectedFilterOperation' => 'contains'],
                ['dataField' => 'c_numero_client', 'caption' => 'Numéro client', 'allowHeaderFiltering' => false,'allowSorting' => false, 'allowSearch' => false,  'filterOperations' => $filterOperationsString,'selectedFilterOperation' => 'contains'],
                ['dataField' => 'c_nom', 'caption' => 'Nom', 'allowHeaderFiltering' => false,'allowSorting' => false, 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains' ],
                ['dataField' =>'c_nom_entreprise', 'caption' => 'Nom entreprise', 'allowHeaderFiltering' => false,'allowSorting' => false, 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' => 'ea_code_postal', 'caption' => 'CP','allowSearch' => false ,'allowHeaderFiltering' => false,'allowSorting' => false, 'headerFilter' => [ 'allowSearch' => true], 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'startswith'],
                ['dataField' =>'ea_ville', 'caption' => 'Ville','allowSearch' => false ,'allowSorting' => false, 'filterOperations' => $filterOperationsString, 'allowHeaderFiltering' => false, 'selectedFilterOperation' => 'contains'],
                ['dataField' =>'ea_adresse', 'caption' => 'Adresse', 'allowSearch' => false ,'allowSorting' => false, 'allowHeaderFiltering' => false, 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' =>'eac_complement', 'caption' => 'Complément d\'adresse', 'allowSearch' => false ,'allowSorting' => false, 'allowHeaderFiltering' => false, 'allowFiltering' => false],
                ['dataField' =>'tel_num_tel', 'caption' => 'Téléphone(s)', 'allowSearch' => false ,'allowSorting' => false,'allowHeaderFiltering' => false, 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' => 'efc_libelle', 'caption' => 'Famille contrat', 'allowSearch' => false , 'allowSorting' => false, 'headerFilter' => ['dataSource' => $typesFamilleContrat], 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' =>'c_prenom', 'caption' => 'Prénom', 'visible' => false,'allowSorting' => false, 'allowHeaderFiltering' => false, 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' =>'ec_libelle_court', 'caption' => 'Civilité', 'allowSearch' => false , 'allowSorting' => false,'visible' => false, 'allowHeaderFiltering' => false, 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' =>'tc_libelle', 'caption' => 'Type client', 'allowSearch' => false , 'allowSorting' => false,'visible' => false, 'headerFilter' => ['dataSource' => $typesClient], 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' =>'cp_libelle', 'caption' => 'Catégorie pro',  'allowSearch' => false ,'allowSorting' => false, 'visible' => false, 'allowHeaderFiltering' => false, 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' =>'cs_nom', 'caption' => 'Souscripteur', 'visible' => false,'allowSorting' => false, 'allowHeaderFiltering' => false,  'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' =>'mail_email', 'caption' => 'Email(s)', 'allowSearch' => false ,'allowSorting' => false, 'visible' => false, 'allowHeaderFiltering' => false, 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' =>'eat_libelle', 'caption' => 'Type Logement', 'allowSearch' => false ,'allowSorting' => false, 'visible' => false, 'headerFilter' => ['dataSource' => $typesLogement], 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' =>'e_num_serie_principal', 'caption' => 'N°Serie', 'visible' => false,'allowSorting' => false, 'allowHeaderFiltering' => false, 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'startswith'],
                //['dataField' =>'e_id', 'caption' => 'ID équipement', 'visible' => false,'allowSorting' => false, 'allowHeaderFiltering' => false, 'dataType' => 'number', 'filterOperations' => $filterOperationsInteger],
                ['dataField' => 'et_type', 'caption' => 'Type équip.', 'allowSearch' => false ,'allowSorting' => false, 'visible' => false, 'headerFilter' => ['dataSource' => $typesEquipement], 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' => 'ef_libelle', 'caption' => 'Famille équip.', 'allowSearch' => false ,'allowSorting' => false, 'visible' => false, 'headerFilter' => [ 'allowSearch' => true,'dataSource' => $famillesEquipement], 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' => 'ctct_libelle_court', 'caption' => 'Contrat', 'allowSearch' => false ,'allowSorting' => false, 'visible' => false,'headerFilter' => ['dataSource' => $typesContrat], 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' => 'ct_groupe', 'caption' => 'Groupe contrat', 'visible' => false,'allowSorting' => false, 'allowHeaderFiltering' => false, 'dataType' => 'number', 'filterOperations' => $filterOperationsInteger],
                ['dataField' => 'eoo_libelle_court', 'caption' => 'option', 'allowSearch' => false ,'allowSorting' => false, 'visible' => false,'headerFilter' => [ 'allowSearch' => true,'dataSource' => $options], 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' =>'ct_date_debut_contrat', 'caption' => 'Date début contrat','allowSorting' => false, 'visible' => false, 'dataType' => "date", 'format' => 'shortDate', 'allowHeaderFiltering' => false, 'filterOperations' => $filterOperationsDate],
                ['dataField' => 'ct_date_fin_contrat', 'caption' => 'Date fin contrat', 'allowSorting' => false,'visible' => false, 'dataType' => "date", 'format' => 'shortDate','allowHeaderFiltering' => false, 'filterOperations' => $filterOperationsDate],
                ['dataField' => 'e_date_fin_garantie', 'caption' => 'Date fin GU','allowSorting' => false, 'visible' => false, 'dataType' => "date", 'format' => 'shortDate','allowHeaderFiltering' => false, 'filterOperations' => $filterOperationsDate],
                ['dataField' => 'e_date_premier_allumage', 'caption' => 'Date allumage','allowSorting' => false, 'visible' => false, 'dataType' => "date", 'format' => 'shortDate','allowHeaderFiltering' => false, 'filterOperations' => $filterOperationsDate],
                ['dataField' => 'e_date_derniere_v1', 'caption' => 'Date dernière V1','allowSorting' => false, 'visible' => false, 'dataType' => "date", 'format' => 'shortDate','allowHeaderFiltering' => false, 'filterOperations' => $filterOperationsDate],
                ['dataField' => 'el_libelle', 'caption' => 'Local', 'allowSearch' => false ,'allowSorting' => false, 'visible' => false,'headerFilter' => ['dataSource' => $equipementsLocal], 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' => 'r_libelle', 'caption' => 'Raccordement', 'visible' => false,'allowSorting' => false, 'allowSearch' => false, 'headerFilter' => [ 'allowSearch' => true,'dataSource' => $raccordement], 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' => 'es_nom', 'caption' => 'Secteur', 'allowSearch' => false ,'allowSorting' => false, 'visible' => false,'headerFilter' => [ 'allowSearch' => true,'dataSource' => $secteurs], 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' =>'ua_nom', 'caption' => 'Agent principal', 'allowSearch' => false ,'allowSorting' => false, 'visible' => false, 'allowHeaderFiltering' => false, 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' => 'e_chantier', 'caption' => 'Chantier', 'visible' => false, 'allowSearch' => false,'allowHeaderFiltering' => false, 'allowSorting' => false, 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' => 'e_salarie_frisquet', 'caption' => 'Salarié Frisquet', 'allowSearch' => false,'allowSorting' => false, 'visible' => false,'headerFilter' => ['dataSource' => $booleanChoix], 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' => 'e_date_eligible_privilege', 'caption' => 'Privilège', 'visible' => false, 'allowSearch' => false,'allowSorting' => false,'dataType' => "date", 'format' => 'shortDate','allowHeaderFiltering' => false, 'filterOperations' => $filterOperationsDate],
                ['dataField' => 'cpo_date', 'caption' => 'Porte ouverte', 'visible' => false,'allowSorting' => false, 'dataType' => "date", 'format' => 'shortDate','allowHeaderFiltering' => false, 'filterOperations' => $filterOperationsDate],
                ['dataField' => 'e_actif', 'caption' => 'Equipement inactif', 'visible' => false, 'allowSearch' => false,'allowSorting' => false,'headerFilter' => ['dataSource' =>  [['text' => 'Oui', 'value' => 'non'],['text' => 'Non', 'value' => 'oui']]], 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' => 'e_numero_client_oracle', 'caption' => 'Ancien N° client','allowSorting' => false, 'visible' => false, 'allowHeaderFiltering' => false, 'dataType' => 'number', 'filterOperations' => $filterOperationsInteger],
            ],
            'get_path' => $this->generateUrl('get_clients'),
            'editing' => [ 'mode' => "row", 'allowUpdating' => false,  'allowDeleting' =>  false, 'allowAdding' => false], 'remoteOperations' => ['groupPaging' =>  true],
            'rang_tri' => false,
            'allowedPageSizes' => [10,100,1000],
            'rowDblClick' => 'e_id',
            'key' => ['id', 'e_id'],
            'searchPanelPlaceholder' => 'Rechercher par nom, prénom, nom d\'entreprise et numéro d\'équipement',
            'exportAllText' => 'Exporter la page',
            'filtreDefaut' => $filtreManager->getDefaultFilter($this->getUser(), 'Client'),
            'filtreDefautUtilisateur' => $filtreManager->getDefaultFilterUtilisateur($this->getUser(), 'Client'),
            ];

        $actions = [
            ['name' => 'Nouveau', 'icon' => 'fa-plus', 'class' => 'btn-success', 'datapopuptitle' => 'Nouveau client', 'data' => ' data-dxpopup data-popup-id=popup-add-client data-poppup-container=body'],
        ];
        $complementAdresseGrid = $this->getComplementAdresseGrid();

        return $this->render('admin/list.html.twig', [
            'datagrid_style' => 'full',
            'page' => 'Client',
            'datas' => $datas,
            'actions' => $actions,
            'popup' => 'clients/_popup_add_client.html.twig',
            'typesClientAll' => $typesClientAll,
            'civilites' => $civilites,
            'categoriesPro' => $categoriesPro,
            'complementAdresseGrid' => $complementAdresseGrid,
            'show_path' => $this->generateUrl('show_client', ['id' => 1]),
        ]);
    }

    /**
     * Lists all entities.
     * @Route("/client/{id}", methods="GET", name="show_client")
     */
    public function showClient(Client $client, LockManager $lockManager, Request $request): Response
    {
        $typesClient = $this->getDoctrine()->getRepository(TypeClient::class)->findAll();
        $civilites = $this->getDoctrine()->getRepository(EtatCivil::class)->findAll();
        $typesEquipement = $this->getDoctrine()->getRepository(EquipementType::class)->findAll();
        $famillesEquipement = $this->getDoctrine()->getRepository(EquipementFamille::class)->findBy([], ['code' => 'ASC']);
        $energies = $this->getDoctrine()->getRepository(Energie::class)->findAll();
        $puissances = $this->getDoctrine()->getRepository(EquipementPuissance::class)->findAll();
        $locaux = $this->getDoctrine()->getRepository(EquipementLocal::class)->findBy([], ['libelle' => 'ASC']);
        $famillesContrat = $this->getDoctrine()->getRepository(EquipementFamilleContrat::class)->findAll();
        $typesContrat = $this->getDoctrine()->getRepository(ContratType::class)->findAll();
        $typesLogement = $this->getDoctrine()->getRepository(TypeLogement::class)->findAll();
        $categoriesPro = $this->getDoctrine()->getRepository(CategoriePro::class)->findAll();
        $contratMotifsResiliation = $this->getDoctrine()->getRepository(ContratMotifResiliation::class)->findAll();
        $equipementFluides = $this->getDoctrine()->getRepository(EquipementFluide::class)->findAll();
        $equipementAlimentations = $this->getDoctrine()->getRepository(EquipementAlimentation::class)->findAll();
        $equipementMarques = $this->getDoctrine()->getRepository(EquipementMarque::class)->getIdLibelle();
        $typesZone = $this->getDoctrine()->getRepository(TypeZone::class)->findAll();
        $raccordements = $this->getDoctrine()->getRepository(Raccordement::class)->findBy([], ['libelle' => 'ASC']);
        $robinets = $this->getDoctrine()->getRepository(RobinetRemplissage::class)->findAll();
        $moyensPaiement = $this->getDoctrine()->getRepository(MoyenPaiement::class)->findAll();
        $protectionsSanitaire = $this->getDoctrine()->getRepository(ProtectionSanitaire::class)->findAll();
        $typesInstallation = $this->getDoctrine()->getRepository(TypeInstallation::class)->findAll();
        $groupeTypes = $this->getDoctrine()->getRepository(EquipementGroupeType::class)->findAll();
        $options = $this->getDoctrine()->getRepository(Option::class)->getIdLibelle();
        $typesComplement = $this->getDoctrine()->getRepository(TypeComplement::class)->getIdLibelle();
        $tauxTva = $this->getDoctrine()->getRepository(TauxTva::class)->findAll();
        $typeComplementAdresse = $this->getDoctrine()->getRepository(TypeComplementAdresse::class)->findBy([], ['libelle' => 'ASC']);
        $typesEnergie = $this->getDoctrine()->getRepository(TypeEnergie::class)->findAll();
        $mainOeuvreTarif = $this->getDoctrine()->getRepository(ProduitPrestationTarif::class)->findOneBy(['produit' => Produit::ID_PRODUIT_MO]);
        $equipement = $this->getDoctrine()->getRepository(Equipement::class)->find($request->get('id_equipement'));
        $secteurZone = $equipement->getSecteur() ? $equipement->getSecteur()->getSecteurZone() : null;
        $deplacementTarif = $this->getDoctrine()->getRepository(SecteurTarif::class)->findOneBy(['produit' => Produit::ID_PRODUIT_DEPL, 'secteur_zone' => $secteurZone]);

        usort($tauxTva, function ($a, $b) {
            return $a->getTaux() <=> $b->getTaux();
        });
        $checkLock = $lockManager->checkLock('Equipement', $request->get('id_equipement') , $this->getUser());

        $equipementComplementsGrid = [
            'columns' => [
                ['dataField' =>'type',
                    'caption' => 'Compléments',
                    'dataType' => 'number',
                    'validationRules' => [["type" =>'required']],
                    'lookup' => [
                        'dataSource'=>  $typesComplement,
                        'displayExpr'=> "libelle",
                        'valueExpr'=> "id",
                    ]
                ],
                ['dataField' =>'marque',
                    'caption' => 'Marque',
                    'dataType' => 'number',
                    'lookup' => [
                        'dataSource'=>  $equipementMarques,
                        'displayExpr'=> "libelle",
                        'valueExpr'=> "id",
                    ]
                ],
                ['dataField' =>'num_serie', 'caption' => 'N° Série si Frisquet',  'validationRules' => [["type" =>'stringLength', "max" => 14]]],
                ['type' => "buttons", 'width'=> 55, 'buttons' => ['edit','delete','add']]
            ],
            'rang_tri' => false,
            'editing' => [ 'mode' => "row", 'allowUpdating' => true, 'allowDeleting' => true, 'allowAdding' => true],
            'toolbarInvisible' => true,
            'delete_path' => $this->generateUrl('delete_equipement_complement'),
        ];

        //$complementAdresseGrid = $this->getComplementAdresseGrid();

        $equipementOptionGrid = [
            'columns' => [
                ['dataField' => 'option', 'caption' => 'Type',
                    'width' => 130,
                    'dataType' => 'number',
                    'validationRules' => [["type" =>'required']],
                    'lookup' => [
                        'dataSource'=>  $options,
                        'displayExpr'=> "libelle_court",
                        'valueExpr'=> "id",
                        'keyExpr' => "id",
                    ]],
                ['dataField' => 'etat', 'width' => 60, 'caption' => 'Etat','allowEditing' => false],
                ['dataField' => 'date_souscription', 'width' => 85,  'dataType' => 'date', 'caption' => 'Date', 'format' => 'shortDate', 'allowEditing' => false],
                ['dataField' => 'date_debut', 'width' => 85, 'dataType' => 'date', 'caption' => "Date d'effet", 'format' => 'shortDate', 'allowEditing' => false],
                ['dataField' => 'tva', 'width' => 38, 'caption' => 'TVA', 'allowEditing' => false],
                ['dataField' => 'prix_ht', 'width' => 65, 'caption' => 'Tarif HT', 'allowEditing' => false],
                ['type' => "buttons", 'width'=> 55, 'buttons' => ['edit','delete','add']]
            ],
            'column_autowidth' => false,
            'rang_tri' => false,
            'get_path' => '/equipement/option/',
            'create_path' => '/equipement/option/',
            'delete_path' => $this->generateUrl('delete_equipement_option'),
            'editing' => [ 'mode' => "row", 'allowUpdating' => false, 'allowDeleting' => true, 'allowAdding' => true],
        ];

//        $actions = [
//            ['name' => 'Annuler', 'icon' => 'fa-trash', 'class' => 'btn-danger', 'href' => '', 'type'=> 'button'],
//            ['name' => 'Enregistrer', 'icon' => 'fa-save', 'id' => 'btn-save-client', 'class' => 'btn-success', 'href' => '', 'form' => 'form_client_update', 'type'=> 'button'],
//
//        ];

        return $this->render('clients/client_show.html.twig', [
            'client' => $client,
            'page' => 'Client',
           // 'actions' => $actions,
            'typesClient' => $typesClient,
            'civilites' => $civilites,
            'typesEquipement' => $typesEquipement,
            'famillesEquipement' => $famillesEquipement,
            'puissances' => $puissances,
            'energies' => $energies,
            'locaux' => $locaux,
            'famillesContrat' => $famillesContrat,
            'typesContrat' => $typesContrat,
            'typesLogement' => $typesLogement,
            'categoriesPro' => $categoriesPro,
            //'complementAdresseGrid' => $complementAdresseGrid,
            'equipementOptionGrid' => $equipementOptionGrid,
            'equipementComplementsGrid' => $equipementComplementsGrid,
            'contratMotifsResiliation' => $contratMotifsResiliation,
            'equipementMarques' => $equipementMarques,
            'typesZone' => $typesZone,
            'raccordements' => $raccordements,
            'protectionsSanitaire' => $protectionsSanitaire,
            'robinets' => $robinets,
            'typesInstallation' => $typesInstallation,
            'groupeTypes' => $groupeTypes,
            'contratRepo' => $this->getDoctrine()->getRepository(Contrat::class),
            'options' => $options,
            'tauxTva' => $tauxTva,
            'typeComplementAdresse' => $typeComplementAdresse,
            'equipementFluides' => $equipementFluides,
            'equipementAlimentations' => $equipementAlimentations,
            'typesEnergie' => $typesEnergie,
            'moyensPaiement' => $moyensPaiement,
            'lock' => $checkLock,
            'mainOeuvreTarif' => $mainOeuvreTarif,
            'deplacementTarif' => $deplacementTarif
        ]);
    }

    /**
     * @Route("/get/clients", methods="GET", name="get_clients")
     */
    public function getClients(SerializerInterface $serializer, Request $request) {

        $skip = $request->query->get('skip');
        $take = $request->query->get('take');
        $entities = null;
        $total = 0;
        //$sort = json_decode($request->query->get('sort'), true);

        $session = $this->container->get('request_stack')->getSession();

        //on gère la limit si jamais on fait un export global, pas de global pour getclient car trop long
        if (!isset($take)) $take = $session->get('list_client_take');
        else  $session->set('list_client_take', $take);

        if (!isset($skip)) {$skip= ($session->get('list_client_last_id_export')) ? $session->get('list_client_last_id_export') :  0;}
        elseif ($skip != 0 && $session->get('list_client_last_id')) $skip = $session->get('list_client_last_id');

        $filters = json_decode($request->query->get('filter'), true);
        $filtersBDD = Functions::formatFiltersForBdd($filters, $this->getDatasTypes());

        $sites = '';
        if ($filters) {
            $entities = $this->getDoctrine()->getManager()->getRepository(Client::class)->getClientView($skip, $take, $filtersBDD, null, null);
            if ($skip == 0) {
                $total = $this->getDoctrine()->getManager()->getRepository(Client::class)->countClients2($filtersBDD);
                $session->set('list_client_total', $total);
            } else {
                $total = $session->get('list_client_total');
            }
            if ($entities) {
                $last = count($entities) -1;
                //on stock l'id du dernier client pour eviter d'utiliser OFFSET car plombe les perfs de POSTGRES
                $session->set('list_client_last_id_export', ($skip == 0 ? $skip :  $session->get('list_client_last_id')));
                $session->set('list_client_last_id', $entities[$last]['id']);
            }
        }


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

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

    /**
     * @Route("/get/clients/denombrement", methods="POST", name="get_clients_denombrement")
     */
    public function getClientsDenombrement(Request $request) {
        $filters = $request->request->get('filtres');
        $filtersBDD = Functions::formatFiltersForBdd($filters, $this->getDatasTypes());
        $total_unique = ($filters) ? $this->getDoctrine()->getManager()->getRepository(Client::class)->countClients2($filtersBDD, 'unique') : 0;
        $response = json_encode(['total_unique' => $total_unique]);

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

    /**
     * @Route("/search", methods="POST", name="search_client")
     */
    public function searchClient(Request $request) {
        $clients = null;
        $datas = $request->request->all();

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

        if (isset($datas['search_nom']) || isset($datas['search_prenom']) || isset($datas['search_numero_client'])) {
            $clients = $this->getDoctrine()->getRepository(Client::class)->searchClients($datas);
        }

        $datasTwig = ['clients' => $clients];
        if ($datas['type_form_search'] == 'souscripteur') {
            $datasTwig['select_name'] = 'new_client_souscripteur';
            $datasTwig['select_id'] = 'new_client_souscripteur';
            $datasTwig['form_id'] = 'form-change-souscripteur';
        } else {
            $datasTwig['select_name'] = 'new_client_utilisateur';
            $datasTwig['select_id'] = 'new_client_utilisateur-' . $datas['id_equipement'];
            $datasTwig['form_id'] = 'form-add-utilisateur-' . $datas['id_equipement'];
        }

        $html = $this->renderView('clients/_search_clients_result.html.twig',$datasTwig);

        return new JsonResponse(['html' => $html], Response::HTTP_OK);
    }

    /**
     * @Route("/detail_client/{id}", methods="GET", name="detail_client")
     */
    public function detailClient(Client $client, Request $request) {
        return $this->render('clients/_detail_client.html.twig',['client' => $client]);
    }

    /**
     * @Route("/recherche", methods="POST", name="recherche_clients")
     */
    public function rechercheClients(Request $request, SessionInterface $session) {
        //pour bloquer le traitement
        $clients = null;
        $datas = $request->request->all();
        $em =  $em = $this->getDoctrine()->getManager();
        $etatCivil = null;
        $categoriePro = null;
        $source = null;
        $repoClient = $em->getRepository(Client::class);

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

        $typeClient = $em->getRepository(TypeClient::class)->find((int)$datas['type_client']);

        $colonnes =  [
                ['dataField' =>'numero_client', 'caption' => 'N°Client',  'allowSearch' => false,'allowSorting' => false],
                ['dataField' =>'ancien_numero_client', 'caption' => 'Ancien N°Client',  'allowSearch' => false ,'allowSorting' => false],
                ['dataField' =>'categorie_pro', 'visible' =>(!$typeClient->isParticulier() ? true : false) ,'caption' => 'Catégorie', 'allowSearch' => false ,'allowSorting' => false],
                ['dataField' =>'nom_entreprise', 'caption' => 'Entreprise', 'visible'=>(!$typeClient->isParticulier() ? true : false) ,  'allowSearch' => false ,'allowSorting' => false],
                ['dataField' =>'civilite', 'caption' => 'Civilité', 'visible'=>($typeClient->isParticulier() ? true : false) , 'allowSearch' => false ,'allowSorting' => false],
                ['dataField' =>'nom', 'caption' => 'Nom',  'visible'=>($typeClient->isParticulier() ? true : false) , 'allowSearch' => false ,'allowSorting' => false],
                ['dataField' =>'prenom', 'caption' => 'Prenom', 'visible'=>($typeClient->isParticulier() ? true : false) ,  'allowSearch' => false ,'allowSorting' => false],
                ['dataField' =>'adresse', 'caption' => 'Adresse',  'allowSearch' => false ,'allowSorting' => false],
                ['dataField' =>'tel', 'caption' => 'Tel',  'allowSearch' => false ,'allowSorting' => false],
                ['dataField' =>'email', 'caption' => 'Email',  'allowSearch' => false ,'allowSorting' => false],
        ];


        if (isset($datas['numero_client']) && !empty($datas['numero_client'])) {
            $clients[] = $repoClient->findOneBy(['numero_client' => str_replace(' ', '',$datas['numero_client'])]);
        } else {
            if ($typeClient->isParticulier()) {
                $etatCivil = $em->getRepository(EtatCivil::class)->find((int)$datas['etat_civil']);
            } else {
                $categoriePro = $em->getRepository(CategoriePro::class)->find((int)$datas['categorie_pro']);
            }
            $clients =  $repoClient->searchClients($typeClient,$datas,$categoriePro, $etatCivil);
        }

        return new JsonResponse(['colonnes' => $colonnes, 'source' => $clients], Response::HTTP_OK);
    }

    /**
     * @Route("/verif_client_existant", methods="POST", name="verif_client_existant")
     */
    public function verifClientExistant(Request $request) {
        $clients = null;
        $datas = $request->request->all();

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

        if (isset($datas['search_nom']) || isset($datas['search_prenom']) || isset($datas['search_numero_client'])) {
            $clients = $this->getDoctrine()->getRepository(Client::class)->searchClients($datas);
        }

        $datasTwig = ['clients' => $clients];
        if ($datas['type_form_search'] == 'souscripteur') {
            $datasTwig['select_name'] = 'new_client_souscripteur';
            $datasTwig['select_id'] = 'new_client_souscripteur';
            $datasTwig['form_id'] = 'form-change-souscripteur';
        } else {
            $datasTwig['select_name'] = 'new_client_utilisateur';
            $datasTwig['select_id'] = 'new_client_utilisateur-' . $datas['id_equipement'];
            $datasTwig['form_id'] = 'form-add-utilisateur-' . $datas['id_equipement'];
        }

        $html = $this->renderView('clients/_search_clients_result.html.twig',$datasTwig);

        return new JsonResponse(['html' => $html], Response::HTTP_OK);
    }

    private function getComplementAdresseGrid() {
        $typesComplementAdresse = $this->getDoctrine()->getRepository(TypeComplementAdresse::class)->getIdLibelle();
        return $complementAdresseGrid = [
            'columns' => [
                ['dataField' => 'type_complement_adresse', 'caption' => 'Type',
                    'width' => '30%',
                    'dataType' => 'number',
                    'validationRules' => [["type" =>'required']],
                    'lookup' => [
                        'dataSource'=>  $typesComplementAdresse,
                        'displayExpr'=> "libelle",
                        'valueExpr'=> "id",
                    ]],
                ['dataField' => 'valeur', 'caption' => 'Information'],
                ['dataField' =>'commentaire_valeur', 'caption' => 'Commentaire'],

            ],
            'column_autowidth' => true,
            'rang_tri' => false,
            'get_path' => '/equipement/complement_adresse/',
            'create_path' => '/equipement/complement_adresse/',
        ];
    }

    private function getDatasTypes() {
        return  ['
            ct_groupe' => 'integer', 'e_chantier' => 'smallint', 'e_numero_client_oracle' => 'integer','id' => 'integer', 'e_id' => 'integer', 'ct_groupe' => 'integer',
            'e_salarie_frisquet' => 'boolean' , 'e_date_eligible_privilege' => 'date', 'e_actif' => 'boolean',
            'ct_date_debut_contrat' => 'date', 'ct_date_fin_contrat' => 'date', 'e_date_fin_garantie' => 'date', 'e_date_premier_allumage' => 'date','cpo_date' => 'date', 'e_date_derniere_v1' => 'date',
        ];
    }

    /**
     * @Route("/add_communication", methods="POST", name="add_communication")
     */
    public function addCommunication(Request $request, Security $security): JsonResponse
    {
        $clientId = $request->request->get('clientId');
        $equipementId = $request->request->get('equipementId');
        $canalId = $request->request->get('canalId', 4); // Par défaut 4 (Appel)
        $interventionId = $request->request->get('interventionId');
        $typeId = $request->request->get('typeId');

        if (!$clientId) {
            return new JsonResponse(['status' => 'error', 'message' => 'Paramètre clientId manquant'], Response::HTTP_BAD_REQUEST);
        }

        $em = $this->getDoctrine()->getManager();
        $client = $em->getRepository(Client::class)->find($clientId);
        $utilisateur = $security->getUser();

        if (!$client) {
            return new JsonResponse(['status' => 'error', 'message' => 'Client non trouvé'], Response::HTTP_NOT_FOUND);
        }

        $communication = new CommunicationClient();
        $communication->setClient($client);
        $communication->setUtilisateur($utilisateur);
        $communication->setDateHeureEnvoi(new \DateTime());

        if ($equipementId) {
            $equipement = $em->getRepository(Equipement::class)->find($equipementId);
            if ($equipement) {
                $communication->setEquipement($equipement);
            }
        }

        if ($interventionId) {
            $intervention = $em->getRepository(Intervention::class)->find($interventionId);
            if ($intervention) {
                $communication->setIntervention($intervention);
            }
        }

        if ($canalId) {
            $canal = $em->getRepository(CommunicationCanal::class)->find($canalId);
            if ($canal) {
                $communication->setCommunicationCanal($canal);
            }
        }

        if ($typeId) {
            $type = $em->getRepository(CommunicationType::class)->find($typeId);
            if ($type) {
                $communication->setCommunicationType($type);
            }
        }

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

        $responseData = ['status' => 'success'];
        if ($canalId == 4) {
            $date = $communication->getDateHeureEnvoi()->format('d/m/Y');
            $heure = $communication->getDateHeureEnvoi()->format('H:i');
            $agent = $utilisateur ? $utilisateur->getCodeAgent() . ' - ' . $utilisateur->getInitiales() . ' ' . mb_strtoupper(mb_substr($utilisateur->getPrenom(), 0, 1)) . '.' . $utilisateur->getNom() : 'Inconnu';
            
            $responseData['lastAppelHtml'] = 'le ' . $date . ' à ' . $heure . ' par ' . $agent;
        }

        return new JsonResponse($responseData);
    }
}