<?php

namespace App\Controller\Dashboard;

use App\Controller\EntityManagerInterface;
use App\Entity\Account;
use App\Entity\AccountResetPasswordRequest;
use App\Form\RequestPasswordConfirmType;
use App\Form\RequestPasswordRequestType;
use App\Repository\AccountRepository;
use App\Repository\ContratsRepository;
use App\Repository\CustomerRepository;
use App\Repository\OptionsRepository;
use App\Repository\PrestaireRepository;
use App\Repository\ProductRepository;
use App\Service\ResetPassword\Event\ResetPasswordConfirmEvent;
use App\Service\ResetPassword\Event\ResetPasswordEvent;
use App\Service\Search\Client;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Contracts\HttpClient\HttpClientInterface;


class SearchController extends AbstractController
{
    #[Route(path: '/crm/recherche', name: 'app_crm_search', options: ['sitemap' => false], methods: ['GET'])]
    public function crmSearch(
        AccountRepository $accountRepository,
        ProductRepository $productRepository,
        CustomerRepository $customerRepository,
        ContratsRepository $contratsRepository,
        OptionsRepository $optionsRepository,
        PrestaireRepository $prestaireRepository,
        Client $client,
        Request $request
    ): Response {
        $query = $request->query->get('q', '');
        $unifiedResults = [];

        if (!empty($query)) {
            // Recherche DB directe pour Prestataires
            $prestataires = $prestaireRepository->search($query);
            foreach ($prestataires as $prestataire) {
                $unifiedResults[] = [
                    'title' => $prestataire->getSurname() . " " . $prestataire->getName(),
                    'subtitle' => $prestataire->getEmail(),
                    'link'  => $this->generateUrl('app_crm_prestataire_view', ['id' => $prestataire->getId()]),
                    'type'  => 'Prestataire',
                    'id'    => $prestataire->getId(),
                    'initials' => strtoupper(substr($prestataire->getSurname(), 0, 1) . substr($prestataire->getName(), 0, 1))
                ];
            }

            $response = $client->searchGlobal($query, 20);

            foreach ($response['results'] as $resultGroup) {
                if (str_contains($resultGroup['indexUid'], 'intranet_ludikevent_options')) {
                    $ids = array_map(fn($h) => $h['id'], $resultGroup['hits']);
                    $accounts = $optionsRepository->findBy(['id' => $ids]);
                    foreach ($accounts as $account) {
                        $unifiedResults[] = [
                            'title' => $account->getName(),
                            'subtitle' => '',
                            'link'  => $this->generateUrl('app_crm_product_options_edit', ['id' => $account->getId()]),
                            'type'  => 'Options',
                            'id'    => $account->getId(),
                            'initials' => strtoupper(substr($account->getName(), 0, 2) )
                        ];
                    }
                }
                if (str_contains($resultGroup['indexUid'], 'intranet_ludikevent_customer')) {
                    // Extraction des IDs pour éviter les requêtes en boucle
                    $ids = array_map(fn($h) => $h['id'], $resultGroup['hits']);
                    $accounts = $customerRepository->findBy(['id' => $ids]);

                    foreach ($accounts as $account) {
                        $unifiedResults[] = [
                            'title' => $account->getName() . " " . $account->getSurname(),
                            'subtitle' => $account->getEmail(),
                            'link'  => $this->generateUrl('app_crm_customer_edit', ['id' => $account->getId()]),
                            'type'  => 'Client',
                            'id'    => $account->getId(),
                            'initials' => strtoupper(substr($account->getName(), 0, 1) . substr($account->getSurname(), 0, 1))
                        ];
                    }
                }
                if (str_contains($resultGroup['indexUid'], 'intranet_ludikevent_contrat')) {
                    // Extraction des IDs pour éviter les requêtes en boucle
                    $ids = array_map(fn($h) => $h['id'], $resultGroup['hits']);
                    $accounts = $contratsRepository->findBy(['id' => $ids]);

                    foreach ($accounts as $account) {
                        $unifiedResults[] = [
                            'title' => $account->getNumReservation(),
                            'subtitle' => '',
                            'link'  => $this->generateUrl('app_crm_contrats_view', ['id' => $account->getId()]),
                            'type'  => 'Contrat de location',
                            'id'    => $account->getId(),
                            'initials' => '',
                        ];
                    }
                }
                // On vérifie si l'index correspond aux administrateurs
                if (str_contains($resultGroup['indexUid'], 'intranet_ludikevent_admin')) {

                    // Extraction des IDs pour éviter les requêtes en boucle
                    $ids = array_map(fn($h) => $h['id'], $resultGroup['hits']);
                    $accounts = $accountRepository->findBy(['id' => $ids]);

                    foreach ($accounts as $account) {
                        $unifiedResults[] = [
                            'title' => $account->getName() . " " . $account->getFirstName(),
                            'subtitle' => $account->getEmail(),
                            'link'  => $this->generateUrl('app_crm_administrateur_view', ['id' => $account->getId()]),
                            'type'  => 'Administrateur',
                            'id'    => $account->getId(),
                            'initials' => strtoupper(substr($account->getName(), 0, 1) . substr($account->getFirstName(), 0, 1))
                        ];
                    }
                }
                if (str_contains($resultGroup['indexUid'], 'intranet_ludikevent_product')) {

                    // Extraction des IDs pour éviter les requêtes en boucle
                    $ids = array_map(fn($h) => $h['id'], $resultGroup['hits']);
                    $accounts = $productRepository->findBy(['id' => $ids]);

                    foreach ($accounts as $account) {
                        $unifiedResults[] = [
                            'title' => $account->getName() . " " . $account->getRef(),
                            'subtitle' => $account->getCategory(),
                            'link'  => $this->generateUrl('app_crm_product_edit', ['id' => $account->getId()]),
                            'type'  => 'Produit',
                            'id'    => $account->getId(),
                            'initials' => strtoupper(substr($account->getName(), 0, 1) . substr($account->getRef(), 0, 1))
                        ];
                    }
                }
            }
        }


        return $this->render('dashboard/search.twig', [
            'results' => $unifiedResults,
            'query'   => $query
        ]);
    }
}
