<?php

namespace App\Controller;

use App\Entity\UserApp;
use App\Repository\AnnouncementRepository;
use App\Repository\CompanyRepository;
use App\Repository\InternApplicationRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\HttpClient\HttpClientInterface;

class IndexController extends AbstractController
{
    public function __construct(
        private HttpClientInterface $client,
        private readonly CompanyRepository $companyRepository,
    )
    {
    }

    #[Route('/', name: 'app_index')]
    public function index(): Response
    {
        $companies = $this->companyRepository->findAll();
        $companiescoord = [];
        foreach ($companies as $company) {
            $addresse = $company->getAddress();
            if ($this->client->request('GET', 'https://api-adresse.data.gouv.fr/search/?q='.$addresse)) {
                $response = $this->client->request('GET', 'https://api-adresse.data.gouv.fr/search/?q='.$addresse);
                $response = $response->toArray();

                $companyInfo = array(
                    "name" => $company->getName(),
                    "address" => $addresse,
                    "coord" => [
                        $response["features"][0]["geometry"]["coordinates"][1],
                        $response["features"][0]["geometry"]["coordinates"][0]
                    ],
                );
                $companiescoord[] = $companyInfo;
            }
        }
        return $this->render('index/index.html.twig', [
            'companies' => $companiescoord,
            'id' => $this->getUser()->getId(),
        ]);
    }

    #[Route('/test', name: 'app_test')]
    public function test(): Response
    {
        return $this->render('base.html.twig', []);
    }
}