<?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\Client;
use App\Entity\Contrat;
use App\Entity\ContratType;
use App\Entity\Equipement;
use App\Entity\EquipementPuissance;
use App\Entity\EquipementType;
use App\Entity\Facture;
use App\Entity\FactureLigne;
use App\Entity\Intervention;
use App\Entity\InterventionTypeValidation;
use App\Entity\MomentPassage;
use App\Entity\MoyenPaiement;
use App\Entity\Option;
use App\Entity\Paiement;
use App\Entity\Planning;
use App\Entity\Produit;
use App\Entity\ProduitFactureAffectation;
use App\Entity\ProduitType;
use App\Entity\Site;
use App\Entity\TauxTva;
use App\Entity\TypePlanification;
use App\Entity\Utilisateur;
use App\Entity\UtilisateurRole;
use App\Service\EquipementManager;
use App\Utils\Functions;
use AppBundle\Entity\ModePaiement;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Monolog\Logger;
use Psr\Log\LoggerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;

/**
 * @Route("/intervention")
 * @IsGranted("ROLE_USER")
 *
 */
class InterventionController extends ParentAdminController
{
    private $entityManager;
    private $validator;

    public function __construct(EntityManagerInterface $entityManager, ValidatorInterface $validator)
    {
        $this->entityManager = $entityManager;
        $this->validator = $validator;
    }

    /**
     * @Route("/validation_technique", methods="POST", name="validation_technique")
     */
    public function validationTechnique(Intervention $intervention, InterventionTypeValidation $interventionTypeValidation, Utilisateur $utilisateur, Request $request) {
        //nécessite validation technique
        //observations, anomalies, commentaire client, modification type intervention, qté co > 10
        // mode paiement, devis, intervention_retour = 41, piece affectation S

        //set info validation technique
        $intervention->setDateValidationTechnique(date('d/m/Y'));
        $intervention->setTypeValidationTechnique($interventionTypeValidation);
        $intervention->setUtilisateurValidationTechnique($utilisateur);
        //si validation adm ok aussi : appel fonction validationGlobale
        if($intervention->getTypeValidationAdm() != null){
            return $this->validationGlobale($intervention, $utilisateur, $request);
        }
        return new JsonResponse(['messages' => ['success' => ["Validation technique effectuée avec succès"]]], Response::HTTP_OK);
    }
    /**
     * @Route("/validation_adm", methods="POST", name="validation_adm")
     */
    public function validationAdm(Intervention $intervention, InterventionTypeValidation $interventionTypeValidation, Utilisateur $utilisateur, Request $request) {
        //nécessite validation adm
        //modification type intervention, contrat, modification taux TVA, modification type equipement, modification puissance equipement, modification numéro equipement, local equipement = autre
        //mode paiement, devis, modification échéancier
        //Famille = 0 et date intervention > date fin de contrat
        //Intervention HORS CONTRAT et pas de mode de paiement
        //Intervention MES ou GARANTIE et Famille != 1
        //Intervention INTERNE et non lié
        //modification client : type, nom, prénom
        //num série équipement

        //set info validation Adm
        $intervention->setDateValidationAdm(date('d/m/Y'));
        $intervention->setTypeValidationAdm($interventionTypeValidation);
        $intervention->setUtilisateurValidationAdm($utilisateur);
        //si validation technique ok aussi : appel fonction validationGlobale
        if($intervention->getTypeValidationTechnique() != null){
            return $this->validationGlobale($intervention, $utilisateur, $request);
        }
        return new JsonResponse(['messages' => ['success' => ["Validation adm effectuée avec succès"]]], Response::HTTP_OK);
    }
    /**
     * @Route("/validation_globale", methods="POST", name="validation_globale")
     */
    public function validationGlobale(Intervention $intervention, Utilisateur $utilisateur, Request $request) {
//select encode(stack, 'escape') from sav.intervention WHERE id = 95754;
        //injection data en attente
        $stack = $intervention->getStack();
        return new JsonResponse(['messages' => ['success' => ["Validation intervention effectuée avec succès"]]], Response::HTTP_OK);
    }

    /**
     * Lists all entities.
     * @Route("/get/interventions", methods="GET", name="get_interventions")
     */
    public function getInterventions(SerializerInterface $serializer, Request $request) {
        $skip = $request->query->get('skip');
        $take = $request->query->get('take');
        $entities = null;
        $total = 0;

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

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

        if (!isset($skip)) {$skip= ($session->get('list_intervention_skip')) ? $session->get('list_intervention_skip') :  0;}
        else $session->set('list_intervention_skip', $skip);

        $filters = json_decode($request->query->get('filter'), true);
        $filtersBDD = Functions::formatFiltersForBdd($filters, $this->getDatasTypes());
        
        $entities = $this->getDoctrine()->getManager()->getRepository(Intervention::class)->getInterventionsView($skip, $take, $filtersBDD,null );
        
        if ($skip == 0) {
            $total = $this->getDoctrine()->getManager()->getRepository(Intervention::class)->countInterventions($filtersBDD);
            $session->set('list_intervention_total', $total);
        } else {
            $total = $session->get('list_intervention_total');
        }
        
        if ($entities) {
            $last = count($entities) -1;
            //on stock l'id du dernier intervention pour eviter d'utiliser OFFSET car plombe les perfs de POSTGRES
            $session->set('list_intervention_last_id_export', ($skip == 0 ? $skip :  $session->get('list_intervention_last_id')));
            $session->set('list_intervention_last_id', $skip);
        }

        $response = json_encode(['data' => $entities, 'totalCount' => $total]);

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

    /**
     * Lists all entities.
     * @Route("/liste_interventions", methods="GET", name="list_interventions")
     */
    public function listInterventions(): Response
    {
        $typePlanification = $this->getDoctrine()->getRepository(TypePlanification::class)->getAllIdNom();
        $avis_passage = [['text' => 'courrier', 'value' => 'courrier'],['text' => 'mail', 'value' => 'mail'],['text' => 'non', 'value' => 'non']];
        $momentPassage = $this->getDoctrine()->getRepository(MomentPassage::class)->getAllIdNom();
        $agentsIntervenu = $this->getDoctrine()->getRepository(Utilisateur::class)->getAgentIdNomByRole([UtilisateurRole::ID_AGENT,UtilisateurRole::ID_AGENT_PLANNING]);
        $agentsPlanning = $this->getDoctrine()->getRepository(Utilisateur::class)->getAgentIdNomByRole([UtilisateurRole::ID_AGENT_PLANNING, UtilisateurRole::ID_REPONSABLE_AGENT_PLANNING ]);
        $filterOperationsString = ["startswith","contains"];
        $filterOperationsInteger = ["="];
        $booleanChoix = [['text' => 'Oui', 'value' => 'oui'],['text' => 'Non', 'value' => 'non']];
        $filterOperationsDate = ['=','<','>', '<=', '>=','between'];

        $today = (new \DateTime())->format('Y-m-d');
        $datas = [
            'columns' => [
                ['dataField' => 'c_numero_client', 'width' => 110,'caption' => 'Numéro client', 'allowHeaderFiltering' => false,'allowSorting' => false, 'allowSearch' => false,  'filterOperations' => $filterOperationsString,'selectedFilterOperation' => 'contains'],
                ['dataField' => 'nom_client', 'visible' => false, 'showInColumnChooser' => false, 'allowExporting' => true],
                ['dataField' => 'adresse_client', 'visible' => false, 'showInColumnChooser' => false, 'allowExporting' => true],
                ['dataField' =>'i_id', 'caption' => 'Numéro intervention','width' => 150, 'allowSorting' => false, 'allowHeaderFiltering' => false, 'dataType' => 'number', 'filterOperations' => $filterOperationsInteger],
                ['dataField' =>'p_date', 'caption' => 'Date de l\'intervention','allowHeaderFiltering' => false,'allowSearch' => false ,'allowSorting' => false,  'dataType' => "date", 'format' => 'shortDate', 'filterValue' => $today, 'filterOperations' => $filterOperationsDate],
                //['dataField' =>'typep_code_court', 'caption' => 'Type' ,'allowSorting' => false, 'allowHeaderFiltering' => false, 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' =>'tpinit_code_court', 'caption' => 'Intervention planifiée','width' => 150, 'headerFilter' => [ 'allowSearch' => true,'dataSource' => $typePlanification], 'allowSearch' => false, 'allowSorting' => false,  'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' =>'tpreal_code_court', 'caption' => 'Intervention réalisée','width' => 150, 'headerFilter' => [ 'allowSearch' => true,'dataSource' => $typePlanification],'allowSearch' => false, 'allowSorting' => false,  'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' =>'agentint_nom', 'caption' => 'Agent intervenu' ,'allowSorting' => false, 'headerFilter' => [ 'allowSearch' => true,'dataSource' => $agentsIntervenu], 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' =>'agentplan_nom', 'caption' => 'Agent de planning',  'allowSorting' => false,'headerFilter' => [ 'allowSearch' => true,'dataSource' => $agentsPlanning], 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' =>'i_avis_passage', 'caption' => 'Avis de passage','search' => false,'allowSearch' => false, 'allowSorting' => false, 'filterOperations' => [],  'allowFiltering' => false,  'allowHeaderFiltering' => true, 'headerFilter' => [ 'allowSearch' => false, 'dataSource' => $avis_passage, 'searchEnabled' => false] ],
                ['dataField' =>'moment_libelle', 'caption' => 'Moment', 'allowSearch' => false ,'allowSorting' => false,'headerFilter' => [ 'allowSearch' => true,'dataSource' => $momentPassage], 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' =>'i_observations', 'caption' => 'Observations' ,'allowSorting' => false,'allowHeaderFiltering' => false, 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains', 'cssClass' => 'multi-line-ellipsis'],
                ['dataField' =>'ima_libelle', 'caption' => 'Motif absence', 'allowSearch' => false ,'allowSorting' => false,'allowHeaderFiltering' => false, 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
                ['dataField' =>'p_heure_debut', 'caption' => 'Heure de début', 'visible' => false, 'allowSorting' => false, 'dataType' => 'time', 'format' => 'HH:mm', 'allowSearch' => false ,'allowSorting' => false, 'allowHeaderFiltering' => false, 'allowFiltering' => false],
                ['dataField' =>'p_heure_fin', 'caption' => 'Heure de fin', 'visible' => false, 'allowSearch' => false ,'allowSorting' => false, 'allowHeaderFiltering' => false, 'allowFiltering' => false],
                ['dataField' =>'im_libelle', 'caption' => 'Motif appel client',  'visible' => false, 'allowSorting' => false, 'allowHeaderFiltering' => false, 'filterOperations' => $filterOperationsString, 'selectedFilterOperation' => 'contains'],
            ],
            'get_path' => $this->generateUrl('get_interventions'),
            'editing' => [ 'mode' => "row", 'allowUpdating' => false,  'allowDeleting' =>  false, 'allowAdding' => false], 'remoteOperations' => ['groupPaging' =>  true],
            'rang_tri' => false,
            'allowedPageSizes' => [10,100,1000],
            'rowDblClick' => 'i_id',
            'key' => ['id', 'i_id'],
            'export_fields' => ['nom_client', 'adresse_client'],
            'searchPanelPlaceholder' => 'Rechercher',
            'exportAllText' => 'Exporter la page',
        ];

        return $this->render('admin/list.html.twig', [
            'datagrid_style' => 'full',
            'page' => 'Intervention',
            'datas' => $datas,
            'show_path' => $this->generateUrl('show_intervention', ['id' => 1]),
        ]);
    }

    /**
     * Lists all entities.
     * @Route("/intervention/{id}", methods="GET", name="show_intervention")
     */
    public function showIntervention(Intervention $intervention): Response
    {
        //form client
        // $formView = $this->createForm(ClientType::class, $intervention, ['action' => $this->generateUrl('parent_createform', ['page' => 'Client'])])->createView();

        $actions = [
            ['name' => 'Editer', 'icon' => 'fa-edit', 'class' => 'btn-success', 'id' => ''],
            ['name' => 'Enregistrer', 'icon' => 'fa-save', 'id' => '', 'class' => 'btn-save', 'href' => ''],
            ['name' => 'Supprimer', 'icon' => 'fa-trash', 'class' => 'btn-danger', 'href' => ''],
        ];

        return $this->render('agent/intervention_show.html.twig', [
            'intervention' => $intervention,
            'page' => 'Intervention',
            'actions' => $actions,
        ]);
    }

    /**
     * show validation technique/administrative.
     * @Route("/validation/{type}", methods="GET", name="show_validation_intervention")
     */
    public function showValidationIntervention($type = 'adm') {
        $utilisateursResponsable = null;
        $sites = $this->getUser()->getSitesListeEntities();

        $utilisateursResponsable = $this->getDoctrine()->getRepository(Utilisateur::class)->getUtilisateursResponsable([$sites[0]] );

        // Récupération des statistiques d'interventions non validées par agent
        $interventionRepository = $this->getDoctrine()->getRepository(Intervention::class);
        
        // Calculer les statistiques par responsable (agrégation des agents sous leur responsabilité)
        $interventionStats = [];
        foreach ($utilisateursResponsable as $responsable) {
            // Récupérer les agents sous la responsabilité de ce responsable
            $agents = $this->getDoctrine()->getRepository(Utilisateur::class)->getAgentsSousResponsable($responsable);
            
            if (!empty($agents)) {
                // Calculer les stats pour ces agents
                $agentIds = array_map(function($agent) {
                    return $agent->getId();
                }, $agents);

                $agentStats = $interventionRepository->getCountInterventionValidationByAgents($agentIds, $type);
                
                // Agréger le total pour ce responsable
                $totalInterventions = array_sum($agentStats);
                $interventionStats[$responsable->getId()] = $totalInterventions;
            } else {
                $interventionStats[$responsable->getId()] = 0;
            }
        }

        return $this->render('intervention/validation_intervention.html.twig', [
            'utilisateursResponsable' => $utilisateursResponsable,
            'agents' => null,
            'type' => $type,
            'interventionStats' => $interventionStats,
        ]);
    }

    /**
     * maj des informations techniques equipement
     * @Route("/maj_intervention_recherche/{type}", methods="POST", name="maj_intervention_recherche")
     */
    public function maj_intervention_recherche(string $type = 'adm', Request $request) {
        $datas = $request->request->all();

        if (isset($datas['type_change']) && !empty($datas['type_change']))
        {
            $id = (int)$datas['data_value'];
            if ($datas['type_change'] == 'site') {
                $site = $this->getDoctrine()->getRepository(Site::class)->find($id);
                $utilisateursResponsable = $this->getDoctrine()->getRepository(Utilisateur::class)->getUtilisateursResponsable([$site]);

                // Calculer les statistiques pour les responsables
                $interventionRepository = $this->getDoctrine()->getRepository(Intervention::class);
                $agentIds = [];
                foreach ($utilisateursResponsable as $utilisateur) {
                    $agentIds[] = $utilisateur->getId();
                }
                $interventionStats = !empty($agentIds) ? $interventionRepository->getCountInterventionValidationByAgents($agentIds, $type) : [];

                $html = $this->renderView('intervention/_select_intervention_responsable.html.twig', [
                    'utilisateursResponsable' => $utilisateursResponsable,
                    'interventionStats' => $interventionStats,
                ]);
            } else {
                // Gestion du cas "inactif" ou ID = 0
                if ($id == 0) {
                    // Récupérer les agents inactifs
                    $agents = $this->getDoctrine()->getRepository(Utilisateur::class)->getAgentsInactifs();
                } else {
                    // Récupérer les agents sous la responsabilité du responsable sélectionné
                    $responsable = $this->getDoctrine()->getRepository(Utilisateur::class)->find($id);
                    $agents = $this->getDoctrine()->getRepository(Utilisateur::class)->getAgentsSousResponsable($responsable);
                }

                // Calculer les statistiques pour les agents
                $interventionRepository = $this->getDoctrine()->getRepository(Intervention::class);
                $agentIds = array_map(function($agent) {
                    return $agent->getId();
                }, $agents);
                $interventionStats = ($agentIds) ? $interventionRepository->getCountInterventionValidationByAgents($agentIds, $type) : [];

                $html = $this->renderView('intervention/_select_intervention_agent.html.twig', [
                    'agents' => $agents,
                    'interventionStats' => $interventionStats
                ]);
            }
        }
        return new JsonResponse(['html' => $html], Response::HTTP_OK);
    }

    /**
     * recherche interventions à valider
     * @Route("/search_intervention_a_valider/{type}", methods="POST", name="search_intervention_a_valider")
     */
    public function searchInterventionAValider(string $type = 'adm', Request $request, LoggerInterface $logger) {
        $datas = $request->request->all();
        $noSearch = false;
        $firstDate = null;

        if (isset($datas['intervention_agent']) && !empty($datas['intervention_agent']))
        {
            $agent = $this->getDoctrine()->getRepository(Utilisateur::class)->find((int)$datas['intervention_agent']);
            
            // Récupérer la date de la première intervention planifiée pour l'agent
            $firstInterventionDate = $this->getDoctrine()->getRepository(Intervention::class)->getFirstInterventionRealiseeAgent($agent);
            
            $date_debut = (isset($datas['a_partir_du']) && !empty($datas['a_partir_du'])) ?  DateTime::createFromFormat('Y-m-d',$datas['a_partir_du']) : null;
            //si pas de date demandé on prendre à partir de la premiere date ou on a pas de validation
            if ($date_debut == null) {
                $date = $this->getDoctrine()->getRepository(Intervention::class)->getFirstInterventionAdmAgent($agent, $type);
                if ($date) {
                    $date_debut = DateTime::createFromFormat('Y-m-d',$date);
                } else {
                    $noSearch = true;
                }
            }

            //récupérer les interventions de l'agent , groupé par jour, et savoir si déjà validé ou non
            $interventions = (!$noSearch) ? $this->getDoctrine()->getRepository(Intervention::class)->getInterventionsAgent($agent, $date_debut) : null;
            $groupedInterventions = [];
            $validationMethod = ($type == 'adm') ? 'getDateValidationAdm' : 'getDateValidationTechnique';
            if ($interventions) {
                foreach ($interventions as $intervention) {
                    $dateKey = $intervention->getPlanning()->getDate()->format('Y-m-d');;
                    if (!$firstDate) $firstDate = $dateKey;
                    // Vérifier si l'intervention nécessite une validation
                    if ($intervention->getTypePlanification()) {
                        $categorieLibelle = $intervention->getTypePlanification()->getCategoriePlanification()->getLibelle();
                        $needsValidation = in_array($categorieLibelle, ['Client', 'Interne']);

                        if ($needsValidation && is_null($intervention->$validationMethod())) {
                            $groupedInterventions[$dateKey]['warning'] = true;
                        }

                        $groupedInterventions[$dateKey]['interventions'][] = $intervention;
                    }

                }
            }
            $html = $this->renderView('intervention/_liste_interventions_a_valider.html.twig', [
                'interventions' => $groupedInterventions,
                'firstDate' => $firstDate,
                'type' => $type,
                'firstInterventionDate' => $firstInterventionDate
            ]);
        }
        return new JsonResponse(['html' => $html], Response::HTTP_OK);
    }

    /**
     * récupère le html d'une intervention à valider
     * @Route("/get_intervention_validation/{id}/{type}", methods="GET", name="get_intervention_validation")
     */
    public function getInterventionValidation(Intervention $intervention, string $type, Request $request,EquipementManager $equipementManager) {
        $typesContrat = $this->getDoctrine()->getRepository(ContratType::class)->findAll();
        $tauxTva = $this->getDoctrine()->getRepository(TauxTva::class)->findAll();
        $typesPlanification = $this->getDoctrine()->getRepository(TypePlanification::class)->findAll();
        $tauxTvaFormatted = $this->getDoctrine()->getRepository(TauxTva::class)->getIdTaux();
        $moyenPaiements = $this->getDoctrine()->getRepository(MoyenPaiement::class)->findAll();
        $typeValidations = $this->getDoctrine()->getRepository(InterventionTypeValidation::class)->findAll();
        $factureAffectations = $this->getDoctrine()->getRepository(ProduitFactureAffectation::class)->getIdLibelle();
        $produitTypePiece = $this->getDoctrine()->getRepository(ProduitType::class)->find(ProduitType::TYPE_PIECE);
        $produitsPiece = $this->getDoctrine()->getRepository(Produit::class)->getIdLibelle($produitTypePiece);
        $facturationGrid = [
            'columns' => [
                ['dataField' => 'reference', 'caption' => 'Référence', 'width' => 70,  'allowEditing' => false],
                ['dataField' =>'idproduit',
                    'caption' => 'Désignation',
                    'dataType' => 'number',
                    'validationRules' => [["type" =>'required']],
                    'lookup' => [
                        'dataSource'=>  ['store' => $produitsPiece, 'paginate' => true, 'pageSize' => 20],
                        'displayExpr'=> "designation",
                        'searchEnabled' => true,
                        'dropDownOptions' => ['height' => 300],
                        'valueExpr'=> "id",
                    ]
                ],
                ['dataField' => 'prix_ht', 'caption' => 'P.U. HT', 'width' => 70, 'allowEditing' => false],
                ['dataField' => 'quantite', 'caption' => 'Qté', 'width' => 30,  'validationRules' => [["type" =>'required']]],
                ['dataField' => 'total_ht', 'caption' => 'Total HT', 'width' => 70 , 'allowEditing' => false],
                ['dataField' =>'idproduit_facture_affectation',
                    'caption' => 'Aff.',
                    'dataType' => 'number',
                    'width' => 70,
                    'validationRules' => [["type" =>'required']],
                    'lookup' => [
                        'dataSource'=>  $factureAffectations,
                        'displayExpr'=> "libelle_court",
                        'valueExpr'=> "id",
                    ]
                ],
                ['dataField' =>'idtaux_tva',
                    'caption' => 'TVA',
                    'dataType' => 'number',
                    'width' => 70,
                    'validationRules' => [["type" =>'required']],
                    'lookup' => [
                        'dataSource'=>  $tauxTvaFormatted,//, '', '" . $this->generateUrl('get_qualifications_available', ['id' => $agent->getId()]) ."')",
                        'displayExpr'=> "taux",
                        'valueExpr'=> "id",
                    ]
                ],
                ['dataField' => 'conserve', 'dataType' => 'boolean', 'width' => 90, 'lookup' => ['valueExpr' => 'value', 'displayExpr' => 'text','dataSource' => [['value' => true, 'text' => 'oui'], ['value'=> false, 'text' => "non"]]]],
                ['dataField' => 'quantite_conserve', 'caption' => 'Qté conservée' , 'width' => 100],
                ['dataField' => 'motif_service', 'visible' => false],
                ['type' => "buttons", 'width'=> 70, 'buttons' => ['edit','delete']]
            ],
            'rang_tri' => false,
            'get_path' => $this->generateUrl('get_validation_facture', ['id' => $intervention->getId()]),
            'patch_path' => '/intervention/facture-ligne/update',
            'create_path' => $this->generateUrl('intervention_facture_ligne_create', ['id' => $intervention->getId()]),
            'delete_path' => '/intervention/facture-ligne/delete',
            'key_add' => $intervention->getId(),
            'editing' => [ 'mode' => "row", 'allowUpdating' => true,  'allowDeleting' =>  true, 'allowAdding' => true],
        ];

        // Calculer les options d'équipement formatées
        $equipementOptionsFormatted = $equipementManager->getEquipementOptionsFormatted($intervention->getEquipement());
        
        return  $this->render('intervention/_get_intervention_validation.html.twig', [
            'intervention' => $intervention,
            'typesContrat' => $typesContrat,
            'tauxTva' => $tauxTva,
            'typesPlanification' => $typesPlanification,
            'facturationGrid' => $facturationGrid,
            'moyenPaiements' => $moyenPaiements,
            'typeValidations' => $typeValidations,
            'equipementManager' => $equipementManager,
            'equipementOptionsFormatted' => $equipementOptionsFormatted,
            'type' => $type
        ]);
    }

    /**
     * getAgent Restrictions
     * @Route("/validation/facture/{id}", methods="GET", name="get_validation_facture")
     */
    public function getValidationFactureGrid(Intervention $intervention) {
        $result = [];
        foreach ($intervention->getFactures() as $facture) {
            foreach($facture->getFactureLignes() as $factureLigne) {
                if ($factureLigne->getProduit()->getProduitType()->getId() == ProduitType::TYPE_PIECE) {
                    $result[] = [
                        'id' => $factureLigne->getId(),
                        'reference' => $factureLigne->getProduit()->getCode(),
                        'idproduit' => $factureLigne->getProduit()->getId(),
                        'prix_ht' => $factureLigne->getPuHt() . '€',
                        'quantite' => $factureLigne->getQuantite(),
                        'total_ht' => $factureLigne->getPrixTotalHt() . '€',
                        'affectation' => $factureLigne->getProduitFactureAffectation()->getLibelleCourt(),
                        'idtaux_tva' => $factureLigne->getTauxTva()->getId(),
                        'taux_tva' => $factureLigne->getTauxTva()->getTaux() .'%',
                        'idproduit_facture_affectation' => $factureLigne->getProduitFactureAffectation()->getId(),
                        'conserve' => $factureLigne->getProduitConserveClient(),
                        'motif_service' => $factureLigne->getMotifService(),
                        'quantite_conserve' => $factureLigne->getQuantiteConserveClient(),
                    ];
                }
            }
        }

        $response = json_encode(['data' => $result, 'totalCount' => count($result)]);

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

    /**
     * @Route("/facture-ligne/create/{id}", name="intervention_facture_ligne_create", methods={"POST"})
     */
    public function createFactureLigne(Intervention $intervention,Request $request): JsonResponse
    {
        $data = $request->request->all();

        // Validation des données requises
        if (!isset($data['idproduit']) || !isset($data['idproduit_facture_affectation']) || !isset($data['quantite'])) {
            throw new \Exception('Données manquantes');
        }

        $produit = $this->entityManager->getRepository(Produit::class)->find((int)$data['idproduit']);
        $produitFactureAffectation = $this->entityManager->getRepository(ProduitFactureAffectation::class)->find((int)$data['idproduit_facture_affectation']);

        if (!$produit || !$produitFactureAffectation) {
            throw new \Exception('ProduitFactureAffectation ou Produit non trouvé');
        }

        // Récupération ou création de la facture
        $facture = $intervention->getFactures()->first();
        if (!$facture) {
            $facture = new Facture();
            $facture->setIntervention($intervention);
            $this->entityManager->persist($facture);
        }

        // Création de la ligne
        $factureLigne = new FactureLigne();
        $this->hydrateFactureLigne($factureLigne, $data, $produit, $facture, $produitFactureAffectation);

        // Calcul du prix total HT
        $this->calculatePrixTotalHt($factureLigne);

        $this->entityManager->persist($factureLigne);
        $this->entityManager->flush();

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

    /**
     * @Route("/facture-ligne/update/{id}", name="intervention_facture_ligne_update", methods={"PATCH"})
     */
    public function updateFactureLigne(Request $request, int $id): JsonResponse
    {
        try {
            $data = $request->request->all();

            $factureLigne = $this->entityManager->getRepository(FactureLigne::class)->find($id);

            // Si le produit change, on le récupère
            $produit = $factureLigne->getProduit();
            if (isset($data['idproduit']) && $data['idproduit'] !== $produit->getId()) {
                $produit = $this->entityManager->getRepository(Produit::class)->find((int)$data['idproduit']);
            }
            $produitFactureAffectation = $factureLigne->getProduitFactureAffectation();
            if (isset($data['idproduit_facture_affectation']) && $data['idproduit_facture_affectation'] !== $produitFactureAffectation->getId()) {
                $produitFactureAffectation = $this->entityManager->getRepository(ProduitFactureAffectation::class)->find((int)$data['idproduit_facture_affectation']);
            }

            $this->hydrateFactureLigne($factureLigne, $data, $produit, $factureLigne->getFacture(), $produitFactureAffectation);
            $this->calculatePrixTotalHt($factureLigne);

            $this->entityManager->flush();

            return new JsonResponse(['messages' => ['success' => ["Modification effectuée avec succès"]]], Response::HTTP_OK);
        } catch (\Exception $e) {
            return new JsonResponse([
                'success' => false,
                'message' => $e->getMessage()
            ], 400);
        }
    }

    /**
     * @Route("/facture-ligne/delete/{id}", name="intervention_facture_ligne_delete", methods={"DELETE"})
     */
    public function deleteFactureLigne(int $id): JsonResponse
    {
        try {
            $factureLigne = $this->entityManager->getRepository(FactureLigne::class)->find($id);
            if (!$factureLigne) {
                throw new \Exception('Ligne non trouvée');
            }

            $this->entityManager->remove($factureLigne);
            $this->entityManager->flush();

            return new JsonResponse(['success' => true]);
        } catch (\Exception $e) {
            return new JsonResponse([
                'success' => false,
                'message' => $e->getMessage()
            ], 400);
        }
    }

    /**
     * @Route("/intervention/validation", name="intervention_validation", methods={"POST"})
     */
    public function interventionValidation(Request $request, EntityManagerInterface $entityManager): JsonResponse
    {
        try {
            $data = $request->request->all();
            $intervention = $entityManager->getRepository(Intervention::class)->find((int)$data['id_intervention']);
            $planning = $intervention->getPlanning();
            $typeValidationAdm = $entityManager->getRepository(InterventionTypeValidation::class)->find(InterventionTypeValidation::ID_TYPE_RAS);
            $user = $this->getUser();

            // Mise à jour des champs de validation
            $intervention->setDateValidationAdm(new \DateTime());
            $intervention->setUtilisateurValidationAdm($user);
            $intervention->setIdtypeValidationAdm($typeValidationAdm);

            // Mise à jour des champs modifiables
            if (isset($data['mode_paiement']) && !empty($data['mode_paiement'])) {
                $modePaiement = $entityManager->getRepository(ModePaiement::class)->find((int)$data['mode_paiement']);
                $intervention->setModePaiement($modePaiement);
            }

            if (isset($data['mo_tva']) && !empty($data['mo_tva'])) {
                $factureLigneMo = $entityManager->getRepository(FactureLigne::class)->find((int)$data['id_facture_ligne_mo']);
                $tva = $entityManager->getRepository(TauxTva::class)->find((int)$data['mo_tva']);
                $factureLigneMo->setTauxTva($tva);
                $entityManager->persist($factureLigneMo);
            }

            if (isset($data['deplacement_tva']) && !empty($data['deplacement_tva'])) {
                $factureLigneDeplacement = $entityManager->getRepository(FactureLigne::class)->find((int)$data['id_facture_ligne_deplacement']);
                $tva = $entityManager->getRepository(TauxTva::class)->find((int)$data['deplacement_tva']);
                $factureLigneDeplacement->setTauxTva($tva);
                $entityManager->persist($factureLigneDeplacement);
            }

            if (isset($data['montant_acompte']) && !empty($data['montant_acompte'])) {
                if (!empty($data['id_paiement_acompte'])) {
                    $paiement = $entityManager->getRepository(Paiement::class)->find((int)$data['id_paiement_acompte']);
                } else {
                    $paiement = new Paiement();
                    $paiement->setDate(new \DateTime());
                    $paiement->setFacture($intervention->getFactures()->first());
                }
                $paiement->setMontantTtc(str_replace('€','',$data['montant_acompte']));
            }

            if (isset($data['contrat_type'])) {
                $contrat = $entityManager->getRepository(Contrat::class)->find((int)$data['id_contrat']);
                $contratType = $entityManager->getRepository(ContratType::class)->find((int)$data['contrat_type']);
                $contrat->setType($contratType);
                $entityManager->persist($contrat);
            }

            if (isset($data['intervention_heure_debut']) && !empty($data['intervention_heure_debut'])) {
                $heureDebut = \DateTime::createFromFormat('H:i', $data['intervention_heure_debut']);
                $planning->setHeureDebut($heureDebut);
            }

            if (isset($data['intervention_heure_fin']) && !empty($data['intervention_heure_fin'])) {
                $heureFin = \DateTime::createFromFormat('H:i', $data['intervention_heure_fin']);
                $planning->setHeureFin($heureFin);
            }
            $entityManager->persist($planning);

            // Persister les changements
            $entityManager->flush();

            return new JsonResponse([
                'success' => true,
                'message' => 'Intervention validée avec succès',
                'intervention_id' => $intervention->getId()
            ]);

        } catch (\Exception $e) {
            return new JsonResponse([
                'success' => false,
                'message' => 'Erreur lors de la validation : ' . $e->getMessage()
            ], 400);
        }
    }

    private function hydrateFactureLigne(FactureLigne $factureLigne, array $data, Produit $produit, Facture $facture, ProduitFactureAffectation $produitFactureAffectation): void
    {
        $factureLigne->setFacture($facture);
        $factureLigne->setProduit($produit);
        $factureLigne->setProduitFactureAffectation($produitFactureAffectation);
        $factureLigne->setCodeArticle($produit->getCode());
        $factureLigne->setDesignation($produit->getDesignation());
        if (isset($data['quantite']) && !empty($data['quantite']))
            $factureLigne->setQuantite($data['quantite']);
        $factureLigne->setPuHt($produit->getPrixHt());

        // Gestion de la TVA
        if (isset($data['idtaux_tva'])) {
            $tauxTva = $this->entityManager->getRepository(TauxTva::class)->find((int)$data['idtaux_tva']);
            if ($tauxTva) {
                $factureLigne->setTauxTva($tauxTva);
            }
        }

        if (isset($data['conserve'])) {
            $factureLigne->setProduitConserveClient($data['conserve'] == 'true' ? true : false);
        }
        if (isset($data['quantite_conserve'])) {
            $factureLigne->setQuantiteConserveClient($data['quantite_conserve']);
        }
        
        // Gestion du motif de service
        if (isset($data['motif_service'])) {
            $factureLigne->setMotifService($data['motif_service']);
        }
    }

    private function calculatePrixTotalHt(FactureLigne $factureLigne): void
    {
        $quantite = $factureLigne->getQuantite() ?? 0;
        $puHt = $factureLigne->getPuHt() ?? 0;
        $prixTotalHt = $quantite * $puHt;

        // Application de la remise si elle existe
        if ($factureLigne->getRemise()) {
            $prixTotalHt = $prixTotalHt * (1 - ($factureLigne->getRemise() / 100));
        }

        $factureLigne->setPrixTotalHt($prixTotalHt);
    }

    private function getDatasTypes() {
        return  [
            'p_date' => 'date', 'i_id' => 'integer'
        ];
    }
}
