<?php
namespace App\MDS\ApiBundle\Controller;
use App\Entity\Card;
use App\MDS\ApiBundle\Auth;
use App\MDS\EventsBundle\Entity\Proposal;
use App\MDS\EventsBundle\Entity\ProposalAgents;
use App\MDS\EventsBundle\Entity\ProposalDocument;
use App\Service\ProposalSupplierServicesService;
use Doctrine\ORM\EntityManagerInterface;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use FOS\RestBundle\Controller\Annotations as Rest;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class ApiProposalController extends AbstractFOSRestController
{
/**
* Devuelve una lista de todos los proposals del usuario conectado
*
* @param Request $request (Debe recibirse el token de usuario en el header)
*
* @Rest\Get("/api/proposal/list/user")
*/
function listProposalUser(Request $request): JsonResponse
{
$token = $request->headers->get('token');
try {
Auth::check($token);
} catch (\Throwable $th) {
return new JsonResponse($th, JsonResponse::HTTP_BAD_REQUEST);
}
$em = $this->getDoctrine()->getManager();
// $tokenData = Auth::getData($token);
//Coger los proposals del usuario
// $proposalsAgent = $em->getRepository(ProposalAgents::class)->findByAgOne($tokenData->uid);
// $proposalsAgent = array_merge($proposalsAgent, $em->getRepository(ProposalAgents::class)->findByAgTwo($tokenData->uid));
// $proposalsAgent = array_merge($proposalsAgent, $em->getRepository(ProposalAgents::class)->findByAgThree($tokenData->uid));
// $proposalsAgent = array_merge($proposalsAgent, $em->getRepository(ProposalAgents::class)->findByAgFour($tokenData->uid));
// Ordenar el array por el ID del Proposal de manera descendente
// usort($proposalsAgent, function ($a, $b) {
// // Asumiendo que tus objetos tienen un método getId() para obtener el ID
// return $b->getId() <=> $a->getId();
// });
$proposals = [];
// foreach ($proposalsAgent as $proposalAgent) {
// $proposal = $em->getRepository(Proposal::class)->findOneBy(['id' => $proposalAgent->getIdProp()]);
// //Si no hay proposals para el agente pasamos al siguiente
// if (empty($proposal)) {
// continue;
// }
// $proposals[] = [
// 'id' => $proposal->getId(),
// 'name' => $proposal->getName(),
// 'title' => $proposal->getTitle(),
// 'commission' => $proposal->getCommission(),
// 'pax' => $proposal->getPax(),
// 'bedrooms' => $proposal->getBedrooms(),
// 'briefing' => $proposal->getBriefing(),
// 'observation' => $proposal->getObservation(),
// 'category' => $proposal->getCategory(),
// 'status' => $proposal->getStatus()
// ];
// }
$proposalsFind = $em->getRepository(Proposal::class)->findAll();
foreach ($proposalsFind as $proposal) {
$proposals[] = [
'id' => $proposal->getId(),
'name' => $proposal->getName(),
'title' => $proposal->getTitle(),
'commission' => $proposal->getCommission(),
'pax' => $proposal->getPax(),
'bedrooms' => $proposal->getBedrooms(),
'briefing' => $proposal->getBriefing(),
'observation' => $proposal->getObservation(),
'category' => $proposal->getCategory(),
'status' => $proposal->getStatus()
];
}
return new JsonResponse($proposals, JsonResponse::HTTP_OK);
}
/**
* Guarda el documento (imagen o PDF) relacionado al proposal indicado.
*
* @param Request $request (Recibe el token y los datos a guardar)
*
* @Rest\Post("/api/proposal/save/document/img")
*/
function saveDocumentImg(Request $request, EntityManagerInterface $em, ProposalSupplierServicesService $proposalSupplierServicesService): JsonResponse
{
$token = $request->headers->get('token');
try {
Auth::check($token);
} catch (\Throwable $th) {
return new JsonResponse(['error' => $th->getMessage()], JsonResponse::HTTP_BAD_REQUEST);
}
$tokenData = Auth::getData($token);
$idProposal = $request->get('idProposal');
$title = $request->get('title');
$cardId = $request->get('card');
$description = $request->get('description');
$price = $request->get('price');
$buyDate = $request->get('buyDate') ? new \DateTime($request->get('buyDate')) : new \DateTime();
// Verifica si se ha proporcionado el archivo
if ($request->files->has('document')) {
/** @var UploadedFile $uploadedFile */
$uploadedFile = $request->files->get('document');
// Permitimos imágenes (jpg, jpeg, png, pdf) y también pdf
$allowedExtensions = ['jpg', 'jpeg', 'png', 'pdf'];
$extension = strtolower($uploadedFile->getClientOriginalExtension());
if ($uploadedFile instanceof UploadedFile && in_array($extension, $allowedExtensions)) {
try {
// Generar nombre único y mover el archivo
$fileName = $idProposal . '-' . uniqid() . '.' . $extension;
$uploadedFile->move(
$this->getParameter('proposal_document'), // Directorio de destino
$fileName
);
} catch (\Throwable $th) {
return new JsonResponse(['error' => 'Error al guardar el archivo.'], JsonResponse::HTTP_BAD_REQUEST);
}
// Buscar la tarjeta
$card = $em->getRepository(Card::class)->findOneBy(['id' => $cardId]);
// Crear ProposalDocument
$proposalDocument = new ProposalDocument();
$proposalDocument->setProposalId($idProposal);
$proposalDocument->setFile($fileName);
$proposalDocument->setExtension($extension);
$proposalDocument->setTitle($title);
$proposalDocument->setCreatedId($tokenData->uid);
$proposalDocument->setUpdatedId($tokenData->uid);
$proposalDocument->setCategory('DOCUMENTO DE ADMINISTRACIÓN');
$proposalDocument->setCard($card);
$proposalDocument->setDescription($description);
$proposalDocument->setPrice(0.0);
$proposalDocument->setBuyDate($buyDate);
// Comprobamos si el precio viene vacío o no
if (!empty($price)) {
$proposalDocument->setPrice($price);
$data_costs = [
'supplierId' => 0,
'proposalId' => $idProposal,
'name' => $title,
'commission' => 0,
'total' => $price,
'opIva' => 1,
'iva' => 0,
'datePayment' => '',
'waytopay' => 'VISA',
];
$proposalSupplierServicesService->supplierServicesCostAdd($data_costs, $tokenData->uid, $em);
}
$em->persist($proposalDocument);
$em->flush();
return new JsonResponse(['msg' => 'Documento guardado correctamente.'], JsonResponse::HTTP_OK);
} else {
return new JsonResponse(['error' => 'El archivo no es válido (solo se permiten imágenes jpg, jpeg, png y archivos PDF).'], JsonResponse::HTTP_BAD_REQUEST);
}
} else {
return new JsonResponse(['error' => 'No se ha proporcionado un archivo válido.'], JsonResponse::HTTP_BAD_REQUEST);
}
}
/**
* Devuelve los documentos asociados al proposal que recibe
*
* @param Request $request
*
* @Rest\Post("/api/proposal/get/documents")
*/
function getProposalDocuments(Request $request): JsonResponse
{
$token = $token = $request->headers->get('token');
try {
Auth::check($token);
} catch (\Throwable $th) {
return new JsonResponse($th, JsonResponse::HTTP_BAD_REQUEST);
}
$em = $this->getDoctrine()->getManager();
$tokenData = Auth::getData($token);
$documents = $em->getRepository(ProposalDocument::class)->findBy(['proposalId' => $request->get('idProposal')]);
$documentsArray = [];
foreach ($documents as $document) {
$documentsArray[] = [
'id' => $document->getId(),
'file' => $_SERVER['HTTP_HOST'] . "/assets/document/proposals/" . $document->getFile(),
'extension' => $document->getExtension(),
'title' => $document->getTitle(),
'category' => $document->getCategory(),
'disabled' => $document->getDisabled(),
];
}
return new JsonResponse($documentsArray, JsonResponse::HTTP_OK);
}
}