<?php
namespace App\Controller;
use App\Entity\Car;
use App\Repository\InfoautoTokensRepository;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use App\Entity\InfoautoTokens;
/**
* @Route("/infoauto")
*/
class InfoautoController extends AbstractController
{
#[Route('/', name: 'infoauto_index')]
public function index(): Response
{
$dataJson = json_decode(file_get_contents( $this->getParameter('kernel.project_dir').'/public/brands-groups.json' ), true);
/*---- List brands [BEGIN] ----*/
$aBrands = [];
$aModels = [];
foreach ($dataJson as $brand) {
$aTemp = [];
$aTemp['brandId'] = $brand['id'];
$aTemp['brandName'] = $brand['name'];
$aTemp['brandListPrice'] = $brand['list_price'];
$aTemp['brandPrices'] = $brand['prices'];
$aTemp['brandPriceFrom'] = $brand['prices_from'];
$aTemp['brandPriceTo'] = $brand['prices_to'];
$aTemp['brandGroups'] = $brand['groups'];
/*foreach ($brand['groups'] as $group) {
}*/
$aBrands[] = $aTemp;
}
/*---- List brands [BEGIN] ----*/
//dump($aBrands); exit();
return $this->render('infoauto/index.html.twig', [
'currentMenu' => 'car',
'brands' => $aBrands,
]);
}
#[Route('/getModal', name: 'infoauto_get_modal')]
public function getModal(): Response
{
$dataJson = json_decode(file_get_contents( $this->getParameter('kernel.project_dir').'/public/brands-groups.json' ), true);
/*---- List brands [BEGIN] ----*/
$aBrands = [];
$aModels = [];
foreach ($dataJson as $brand) {
$aTemp = [];
$aTemp['brandId'] = $brand['id'];
$aTemp['brandName'] = $brand['name'];
$aTemp['brandListPrice'] = $brand['list_price'];
$aTemp['brandPrices'] = $brand['prices'];
$aTemp['brandPriceFrom'] = $brand['prices_from'];
$aTemp['brandPriceTo'] = $brand['prices_to'];
$aTemp['brandGroups'] = $brand['groups'];
/*foreach ($brand['groups'] as $group) {
}*/
$aBrands[] = $aTemp;
}
/*---- List brands [BEGIN] ----*/
//dump($aBrands); exit();
return $this->render('car/get_infoauto_modal.html.twig', [
'currentMenu' => 'car',
'brands' => $aBrands,
]);
}
/**
* @Route("/getVersions", name="infoauto_get_versions", methods={"GET"})
*/
public function getVersions(ManagerRegistry $doctrine, Request $request, InfoautoTokensRepository $infoautoTokens): JsonResponse
{
$data['brandId'] = $request->get('brandId');
$data['modelId'] = $request->get('modelId');
$data['modelYear'] = $request->get('modelYear');
$token = $this->getInfoautoToken($doctrine, $infoautoTokens);
// Define los encabezados necesarios
$headers = [
'Authorization: Bearer '.$token,
];
$url = 'https://api.infoauto.com.ar/cars/pub//brands/'.$data['brandId'].'/groups/'.$data['modelId'].'/models?&prices=true&prices_from='.$data['modelYear'].'&prices_to='.$data['modelYear'].'&page_size=100';
if ($data['modelYear'] == '0km') {
$url = 'https://api.infoauto.com.ar/cars/pub//brands/'.$data['brandId'].'/groups/'.$data['modelId'].'/models?&list_price=true&page_size=100';
}
/*---- Buscar modelos por año [BEGIN] ----*/
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => $headers, // Encabezados de la petición
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
));
$response = curl_exec($curl);
curl_close($curl);
// Verifica si ocurrió un error de cURL
if ($response === false) {
$error = curl_error($curl);
curl_close($curl);
die("Error en cURL: $error");
}
// Obtiene el código HTTP de la respuesta
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$modelsJson = json_decode($response, true);
/*---- Buscar modelos por año [END] ----*/
//dump($modelsJson); exit();
/*---- Buscar precios [BEGIN] ----*/
// Recopilar CODIA
$aCodia = null;
foreach ($modelsJson as $item) {
$aCodia[] = ['name' => $item['description'], 'codia' => $item['codia']];
}
if ($aCodia) {
// Buscar precios por CODIA
foreach ($aCodia as $key => $item) {
$url = 'https://api.infoauto.com.ar/cars/pub/models/'.$item['codia'].'/prices';
if ($data['modelYear'] == '0km') {
$url = 'https://api.infoauto.com.ar/cars/pub/models/'.$item['codia'].'/list_price';
}
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => $headers, // Encabezados de la petición
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
));
$response = curl_exec($curl);
curl_close($curl);
// Verifica si ocurrió un error de cURL
if ($response === false) {
$error = curl_error($curl);
curl_close($curl);
die("Error en cURL: $error");
}
$aPrices = json_decode($response, true);
$price = 0;
foreach ($aPrices as $item2) {
if ($data['modelYear'] == '0km') {
$price = number_format($item2, 0, '', '.');
break;
} else if ($item2['year'] == $data['modelYear']) {
$price = number_format($item2['price'], 0, '', '.');
break;
}
}
$aCodia[$key]['price'] = $price;
}
/*---- Buscar precios [END] ----*/
} else {
$data['status'] = 'error';
$data['type'] = 'version';
$data['message'] = 'No se encontró versión para el modelo';
echo '<h3>'.$data['message'].'</h3>';
exit();
}
//dump($aCodia); exit();
return $this->json($aCodia);
}
/**
* @Route("/getFeatures", name="infoauto_get_features", methods={"GET"})
*/
public function getFeatures(ManagerRegistry $doctrine, Request $request, InfoautoTokensRepository $infoautoTokens): JsonResponse
{
$data['codia'] = $request->get('codia');
$token = $this->getInfoautoToken($doctrine, $infoautoTokens);
// Define los encabezados necesarios
$headers = [
'Authorization: Bearer '.$token,
];
/*---- Buscar modelos por año [BEGIN] ----*/
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.infoauto.com.ar/cars/pub/models/'.$data['codia'].'/features/',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => $headers, // Encabezados de la petición
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
));
$response = curl_exec($curl);
curl_close($curl);
// Verifica si ocurrió un error de cURL
if ($response === false) {
$error = curl_error($curl);
curl_close($curl);
die("Error en cURL: $error");
}
// Obtiene el código HTTP de la respuesta
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
//$featuresJson = json_decode($response, true);
$featuresJson = $response;
/*---- Buscar modelos por año [END] ----*/
//dump($featuresJson); exit();
return $this->json($featuresJson);
}
private function getInfoautoToken(ManagerRegistry $doctrine, InfoautoTokensRepository $infoautoTokens)
{
$tokenTmp = $infoautoTokens->findOneBy([], ['id' => 'DESC'], 1);
if ($tokenTmp) {
$hourMore = clone $tokenTmp->getCreatedAt();
$hourMore = ($hourMore)->add(new \DateInterval('PT1H'));
if (new \DateTime() > $hourMore) {
$tokenOk = false;
} else {
$tokenOk = true;
}
} else {
$tokenOk = false;
}
if ($tokenOk) {
return $tokenTmp->getAccessToken();
} else {
$headers = [
'Content-Type: application/json',
'Authorization: Basic '. base64_encode('rwaybar@yahoo.com.ar:NQlv38cCxODlq42f'),
'Content-Length: 0'
];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.infoauto.com.ar/cars/auth/login',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => $headers, // Encabezados de la petición
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
));
$response = curl_exec($curl);
curl_close($curl);
// Verifica si ocurrió un error de cURL
if ($response === false) {
$error = curl_error($curl);
curl_close($curl);
die("Error en cURL: $error");
}
$json = json_decode($response);
$tokens = new InfoautoTokens();
$tokens->setAccessToken($json->access_token);
$tokens->setRefreshToken($json->refresh_token);
$tokens->setCreatedAt(new \DateTime);
$doctrine->getManager()->persist($tokens);
$doctrine->getManager()->flush();
return $json->access_token;
}
}
}