<?php
namespace App\Controller;
use App\Entity\Accounting;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use App\Repository\UserRepository;
use App\Repository\PropertyListRepository;
use App\Repository\PropertyDetailsRepository;
use App\Repository\PotentialClientsRepository;
use App\Entity\PropertyList;
use App\Entity\Broker;
use App\Entity\Landlords;
use App\Entity\PotentialClients;
use App\Entity\PropertyDetails;
use App\Entity\User;
use App\Entity\Tenants;
use App\Form\NewUserType;
use App\Form\NewPropertyType;
use App\Form\NewPropertyDetailsType;
use App\Form\PotentialClientsType;
use App\Form\PropertyFilterType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Vich\UploaderBundle\Handler\UploadHandler;
use App\Repository\AccountingRepository;
use App\Repository\BrokerRepository;
use App\Repository\InterestsRepository;
use App\Repository\LandlordsRepository;
use App\Repository\TenantsRepository;
use App\Service\OperacionesCPPoblacionesYProvincias;
use Flasher\Prime\Flasher;
use Flasher\Symfony\FlasherSymfonyBundle;
use Flasher\Toastr\Symfony\FlasherToastrSymfonyBundle;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Security\Core\Security;
use Pagerfanta\Pagerfanta;
use Pagerfanta\Adapter\ArrayAdapter;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class MainController extends AbstractController
{
#[Route(path:'/', name:'app_start_page')]
public function startPage(): Response
{
return $this->render('immobiliaria.html.twig');
}
#[Route(path:'/politicaDePrivacidad', name: "app_politica_privacidad_immo")]
public function politicaPrivacidadImmo():response
{
return $this->render('politicaDePrivacidadImmo.html.twig');
}
#[Route('/immobiliaria', name:"app_homepage")]
public function homepage(): Response
{
return $this->render('homepage.html.twig', [
"name"=>"HomepageController",
]);
}
#[Route('/loggedout', name:"logout")]
public function logout(): Response
{
return $this->render('logout.html.twig', [
"name"=>"LogoutController",
]);
}
#[Route('/about', name:"app_about")]
public function about(): Response
{
return $this->render('about.html.twig', [
"name"=>"AboutUsController",
]);
}
#[Route('/contact', name: 'app_contact')]
public function contact(Request $request, ): Response
{
$form = $this->createFormBuilder()
->add('name',TextType::class,[
'label'=>'Nombre'
])
->add('email', EmailType::class)
->add('message', TextareaType::class)
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data=$form->getData();
/*
$email= (new Email())
->from($data['email'])
->to('your-email@example.com')
->subject('New Contact Form Submission')
->text('From: ' . $data['name'] . ' (' . $data['email'] . ")\n\n" . $data['message']);
$mailer->send($email);
*/
// Redirect or show a success message
$this->addFlash('success', 'Tu mensaje ha sido enviado!');
return $this->redirectToRoute('contact');
}
return $this->render('contact.html.twig', [
'controller_name' => 'ContactController',
'form'=>$form->createView(),
]);
}
#[Route('/properties/{idp}/info', name: 'app_info')]
public function info(Request $request,
PropertyListRepository $plr,
PotentialClientsRepository $ptr,
int $idp
): Response
{
$property=$plr->find($idp);
if (!$property) {
return $this->render('errors/notfound.html.twig',[
'property'=>$property,
]);
}
$user=$this->getUser();
$email=$user->getEmail();
$name=$user->getFirstName();
$surname=$user->getLastName();
$number=$user->getPhoneNumber();
$buildingNumber=$user->getPropertyNumber();
/*
$data=[
'name'=>$name,
'surname'=>$surname,
'email'=>$email,
'number'=>$number,
'buildingNumber'=>$buildingNumber,
];
*/
$potential = $ptr->findOneBy(['potentialEmail' => $email]);
if ($potential) {
$form = $this->createForm(PotentialClientsType::class, $potential,[
//'data'=>$data,
]);
} else {
$potential = new PotentialClients();
$data=$this->setPotentialData($potential,$user);
$form = $this->createForm(PotentialClientsType::class, $potential,[
//'data'=>$data,
]);
}
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$potential->addProperty($property);
$ptr->save($potential,true);
$this->addFlash(
'success',
'Mensaje Enviado Correctamente.'
);
}
return $this->render('info.html.twig',[
'form'=>$form->createView(),
'property'=>$property,
]);
}
#[Route('/user', name: 'app_user')]
public function index(): Response
{
return $this->render('user/index.html.twig', [
'name' => 'UserController',
]);
}
public function __construct(UrlGeneratorInterface $urlGenerator, Security $security)
{
}
/*
#[Route('/userbyadmin', name: 'admin_newuser')]
public function newUserByAdmin(UserPasswordHasherInterface $userPasswordHasherInterface, UserRepository $userRepository,
AccountingRepository $accountingRepository,
BrokerRepository $brokerRepository,
LandlordsRepository $landlordsRepository,
TenantsRepository $tenantsRepository,
Request $request)
{
if (!$this->isGranted('ROLE_BROKER')) {
throw $this->createAccessDeniedException('No access for you! Check your credentials with the ADMIN. Thank you.');
}
$user=new User();
$form = $this->createForm(NewUserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
}
}
*/
private function setLandlordData(Landlords $landlord, User $user)
{
$landlord
->setLandlordName($user->getFirstName() ?? '')
->setLandlordSurname($user->getLastName() ?? '')
->setLandlordPhone($user->getPhoneNumber() ?? '')
->setLandlordEmail($user->getEmail() ?? '')
->setLandlordAddress($user->getUserAddress() ?? '')
->setLandlordCity($user->getUserCity() ?? '')
->setLandlordPostcode($user->getUserPostcode() ?? '')
->setCreatedAt(new \DateTimeImmutable());
}
private function setAccountantData(Accounting $accountant, User $user)
{
$accountant->setAccountingName($user->getFirstName() ?? '');
$accountant->setAccountingSurname($user->getLastName() ?? '');
$accountant->setAccountingEmail($user->getEmail() ?? '');
$accountant->setAccountingPhone($user->getPhoneNumber() ?? '');
}
private function setBrokerData(Broker $broker, User $user)
{
$broker
->setBrokerName($user->getFirstName() ?? '')
->setBrokerSurname($user->getLastName() ?? '')
->setBrokerPhone($user->getPhoneNumber() ?? '')
->setBrokerEmail($user->getEmail() ?? '');
}
private function setTenantData(Tenants $tenant, User $user)
{
$tenant
->setTenantName($user->getFirstName() ?? '')
->setTenantSurname($user->getLastName() ?? '')
->setTenantPhone($user->getPhoneNumber() ?? "")
->setTenantEmail($user->getEmail() ?? '')
->setTenantAddress($user->getUserAddress() ?? '')
->setBuildingNumber($user->getPropertyNumber() ?? '')
->setProvince($user->getProvince() ?? '')
->setFloor($user->getFloor() ?? '')
->setBloque($user->getBloque() ?? '')
->setEscalera($user->getEscalera() ?? '')
->setApartmentNumber($user->getFlatNumber()?? '')
->setTenantCity($user->getUserCity() ?? '')
->setTenantPostcode($user->getUserPostcode() ?? '')
->setStatus(true)
->setCreatedAt(new \DateTimeImmutable());
}
private function setPotentialData(PotentialClients $potentialClient, User $user)
{
/*
$potentialClient
->setUsers($user)
->setPotentialName($user->getFirstName() ?: ' ')
->setPotentialSurname($user->getLastName() ?: ' ')
->setPotentialNumber($user->getPhoneNumber() ?: ' ')
->setPotentialEmail($user->getEmail() ?: '')
->setPotentialAddress($user->getUserAddress() ?: ' VACÍO')
->setBuildingNumber($user->getPropertyNumber() ?: ' ')
->setProvince($user->getProvince() ?: ' ')
->setFloor($user->getFloor() ?: ' ')
->setBloque($user->getBloque() ?: ' ')
->setEscalera($user->getEscalera() ?: ' ')
->setApartmentNumber($user->getFlatNumber() ?: ' ')
->setPotentialCity($user->getUserCity() ?: ' ')
->setPotentialPostcode($user->getUserPostcode() ?: ' ');
//->setPotentialIban('VACÍO');
*/
$potentialClient
->setStatus(true)
->setCreatedAt(new \DateTimeImmutable());
$properties = [
'potentialName' => $user->getFirstName(),
'potentialSurname' => $user->getLastName(),
'potentialNumber' => $user->getPhoneNumber(),
'potentialEmail' => $user->getEmail(),
'potentialAddress' => $user->getUserAddress(),
'buildingNumber'=> $user->getPropertyNumber(),
'province'=> $user->getProvince(),
'floor'=> $user->getFloor(),
'bloque'=> $user->getBloque(),
'escalera'=> $user->getEscalera(),
'apartmentNumber'=> $user->getFlatNumber(),
'potentialCity'=> $user->getUserCity(),
'potentialPostcode'=> $user->getUserPostcode(),
// Add more properties as needed
];
foreach ($properties as $property => $value) {
if ($value !== null && $value !== '') {
$potentialClient->{'set' . ucfirst($property)}($value);
}
}
}
private function processUserRoles(User $user,
array $roles,
LandlordsRepository $landlordsRepository,
AccountingRepository $accountingRepository,
BrokerRepository $brokerRepository,
TenantsRepository $tenantsRepository)
{
foreach ($roles as $role) {
switch ($role) {
case 'ROLE_LANDLORD':
$landlord = new Landlords();
$this->setLandlordData($landlord, $user);
$user->setLandlord($landlord);
$landlordsRepository->save($landlord, true);
break;
case 'ROLE_ACCOUNTANT':
$accountant = new Accounting();
$this->setAccountantData($accountant, $user);
$user->setAccountant($accountant);
$accountingRepository->save($accountant, true);
break;
case 'ROLE_BROKER':
$broker = new Broker();
$this->setBrokerData($broker, $user);
$user->setBroker($broker);
$brokerRepository->save($broker, true);
break;
case 'ROLE_TENANT':
$tenant = new Tenants();
$this->setTenantData($tenant, $user);
$user->setTenant($tenant);
$tenantsRepository->save($tenant, true);
break;
}
}
}
private function processUserType(User $user,
?array $userTypes,
LandlordsRepository $landlordsRepository,
AccountingRepository $accountingRepository,
BrokerRepository $brokerRepository,
TenantsRepository $tenantsRepository)
{
if (!is_array($userTypes)) {
return;
}
foreach ($userTypes as $userType) {
switch ($userType) {
case 'ROLE_LANDLORD':
$landlord = new Landlords();
$this->setLandlordData($landlord, $user);
$user->setLandlord($landlord);
$landlordsRepository->save($landlord, true);
break;
case 'ROLE_ACCOUNTANT':
$accountant = new Accounting();
$this->setAccountantData($accountant, $user);
$user->setAccountant($accountant);
$accountingRepository->save($accountant, true);
break;
case 'ROLE_BROKER':
$broker = new Broker();
$this->setBrokerData($broker, $user);
$user->setBroker($broker);
$brokerRepository->save($broker, true);
break;
case 'ROLE_TENANT':
$tenant = new Tenants();
$this->setTenantData($tenant, $user);
$user->setTenant($tenant);
$tenantsRepository->save($tenant, true);
break;
}
}
}
#[Route('/newpotential', name: 'app_newpotential')]
public function newPotential(
UserPasswordHasherInterface $userPasswordHasherInterface,
UserRepository $userRepository,
AccountingRepository $accountingRepository,
BrokerRepository $brokerRepository,
LandlordsRepository $landlordsRepository,
TenantsRepository $tenantsRepository,
Request $request,
PotentialClientsRepository $ptr
) {
$user = new User();
$userForm = $this->createForm(NewUserType::class,$user);
$userForm->handleRequest($request);
if ($userForm->isSubmitted() && $userForm->isValid()) {
//$user = $userForm->getData();
$password = $userForm->get('password')->getData();
if ($password === null) {
return;
}
$hash = $userPasswordHasherInterface->hashPassword($user, $password);
$user->setPassword($hash);
$potential= new PotentialClients();
$potential->setUsers($user);
$this->setPotentialData($potential, $user);
$potential->setCreatedAt(new \DateTimeImmutable('now'));
$potential->setStatus(true);
//$user->setPotentialClient($potential);
$ptr->save($potential,true);
$user->setCreatedAt(new \DateTime('now'));
$userType = $userForm->get('userType')->getData();
if (!$userType) {
$user->setUserType(null);
} else {
$this->processUserType($user, $userType, $landlordsRepository, $accountingRepository, $brokerRepository, $tenantsRepository);
}
$userRepository->save($user, true);
$this->addFlash(
'success',
'Usuario Creado Correctamente.'
);
return $this->redirectToRoute("app_properties");
}
return $this->render("/user/newuser.html.twig", [
"user_form" => $userForm->createView()
]);
}
#[Route('/newuser', name: 'app_newuser')]
public function newUser(
UserPasswordHasherInterface $userPasswordHasherInterface,
UserRepository $userRepository,
AccountingRepository $accountingRepository,
BrokerRepository $brokerRepository,
LandlordsRepository $landlordsRepository,
TenantsRepository $tenantsRepository,
Request $request,
PotentialClientsRepository $ptr,
SessionInterface $session
) {
$referer=$request->headers->get('referer');
$refererPath=parse_url($referer,PHP_URL_PATH);
if ($refererPath==="/properties") {
$user = new User();
$userForm = $this->createForm(NewUserType::class,$user);
$userForm->handleRequest($request);
if ($userForm->isSubmitted() && $userForm->isValid()) {
//$user = $userForm->getData();
$password = $userForm->get('password')->getData();
if ($password === null) {
return;
}
$hash = $userPasswordHasherInterface->hashPassword($user, $password);
$user->setPassword($hash);
$potential= new PotentialClients();
$potential->setUsers($user);
$this->setPotentialData($potential, $user);
$potential->setCreatedAt(new \DateTimeImmutable('now'));
$potential->setStatus(true);
//$user->setPotentialClient($potential);
//$ptr->save($potential,true);
$user->setCreatedAt(new \DateTime('now'));
$userType = $userForm->get('userType')->getData();
if (!$userType) {
$user->setUserType(null);
} else {
$this->processUserType($user, $userType, $landlordsRepository, $accountingRepository, $brokerRepository, $tenantsRepository);
}
$userRepository->save($user, true);
$this->addFlash(
'success',
'Usuario Creado Correctamente.'
);
return $this->redirectToRoute("app_properties");
}
} else {
$userForm = $this->createForm(NewUserType::class);
/*$userForm->add('broker',BrokerType::class,[
'label'=>'Comercial',
]);
*/
$userForm->handleRequest($request);
if ($userForm->isSubmitted() && $userForm->isValid()) {
$user = $userForm->getData();
$password = $userForm->get('password')->getData();
if ($password === null) {
return;
}
$hash = $userPasswordHasherInterface->hashPassword($user, $password);
$user->setPassword($hash);
$user->setCreatedAt(new \DateTime('now'));
$userType = $userForm->get('userType')->getData();
if ($userForm->has('roles')) {
$roles = $userForm->get('roles')->getData();
$this->processUserRoles($user, $roles, $landlordsRepository, $accountingRepository, $brokerRepository, $tenantsRepository);
} else {
$this->processUserType($user, $userType, $landlordsRepository, $accountingRepository, $brokerRepository, $tenantsRepository);
}
if (in_array('ROLE_BROKER', $user->getRoles())) {
$broker = $user->getBroker();
//$manager = $userForm->get('broker')->get('manager')->getData();
$manager = $userForm->get('broker')->getData();
//dd($manager);
//die;
if ($manager) {
$managerId=$manager->getId();
$manager1 = $brokerRepository->find($managerId);
$broker->setManager($manager1);
$brokerRepository->save($broker,true);
}
}
if ($userType) {
$userId=$user->getId();
$userRepository->save($user, true);
/*
if ($userType ==='ROLE_LANDLORD') {
return $this->redirectToRoute('landlord_profile',['idl'=>$userId]);
} elseif ($userType==='ROLE_TENANT') {
return $this->redirectToRoute('tenant_profile',['idt'=>$userId]);
} elseif ($userType==='ROLE_POTENTIAL') {
return $this->redirectToRoute('potential_profile',['idp'=>$userId]);
} else {
return $this->redirectToRoute("app_homepage");
}
$this->addFlash(
'success',
'Usuario Creado Correctamente.'
);
*/
$userRepository->save($user, true);
return $this->redirectToRoute("app_homepage");
//$this->addFlash('success', 'Usuario Creado Correctamente.');
} else {
$user->setUserType(null);
$userRepository->save($user, true);
return $this->redirectToRoute("app_homepage");
//$this->addFlash('success', 'Usuario Creado Correctamente.');
}
}
}
return $this->render("/user/newuser.html.twig", [
"user_form" => $userForm->createView()
]);
}
/*
#[Route('/newuser', name: 'app_newuser')]
public function newUser(UserPasswordHasherInterface $userPasswordHasherInterface, UserRepository $userRepository,
AccountingRepository $accountingRepository,
BrokerRepository $brokerRepository,
LandlordsRepository $landlordsRepository,
TenantsRepository $tenantsRepository,
Request $request)
{
$user_form=$this->createForm(NewUserType::class);
$user_form->handleRequest($request);
if($user_form->isSubmitted() && $user_form->isValid()){
$user=$user_form->getData();
$password = $user_form->get('password')->getData();
if ($password === null)
{
return;
}
$hash = $userPasswordHasherInterface->hashPassword($user, $password);
$user->setPassword($hash);
//$user->setRoles(['ROLE_USER']);
$user->setCreatedAt(new \DateTime('now'));
//$userRepository->save($user, true);
if ($user_form->has('roles')) {
$roles=$user_form->get('roles')->getData();
//$otherRoles = array_diff($roles, ['ROLE_USER']);
if (!empty($roles)) {
foreach ($roles as $role) {
if ($role === 'ROLE_LANDLORD') {
$landlord = new Landlords();
$landlord->setLandlordName($user->getFirstName() ?? '');
$landlord->setLandlordSurname($user->getLastName()?? '');
$landlord->setLandlordPhone($user->getPhoneNumber()?? '');
$landlord->setLandlordEmail($user->getEmail()?? '');
$landlord->setLandlordAddress($user->getUserAddress()?? '');
$landlord->setLandlordCity($user->getUserCity()?? '');
$landlord->setLandlordPostcode($user->getUserPostcode()?? '');
// Associate the Landlord entity with the user
$user->setLandlord($landlord);
$landlordsRepository->save($landlord,true);
} elseif ($role === 'ROLE_ACCOUNTANT') {
$accountant = new Accounting();
$accountant->setAccountingName($user->getFirstName()?? '');
$accountant->setAccountingSurname($user->getLastName()?? '');
$accountant->setAccountingEmail($user->getEmail()?? '');
$accountant->setAccountingPhone($user->getPhoneNumber()?? '');
$user->setAccountant($accountant);
$accountingRepository->save($accountant,true) ;
} elseif ($role === 'ROLE_BROKER') {
$broker = new Broker();
$broker->setBrokerName($user->getFirstName()?? '');
$broker->setBrokerSurname($user->getLastName()?? '');
$broker->setBrokerPhone($user->getPhoneNumber()?? '');
$broker->setBrokerEmail($user->getEmail()?? '');
$user->setBroker($broker);
$brokerRepository->save($broker,true);
} elseif ($role === 'ROLE_TENANT') {
$tenant = new Tenants();
$tenant->setTenantName($user->getFirstName());
$tenant->setTenantSurname($user->getLastName());
$tenant->setTenantPhone($user->getPhoneNumber());
$tenant->setTenantEmail($user->getEmail());
$user->setTenant($tenant);
$tenantsRepository->save($tenant,true);
}
}
}
} else {
// Retrieve the user's selected userType from the form data
$userType = $user_form->get('userType')->getData();
if ($userType === 'ROLE_LANDLORD') {
$landlord = new Landlords();
$landlord->setLandlordName($user->getFirstName() ?? '');
$landlord->setLandlordSurname($user->getLastName()?? '');
$landlord->setLandlordPhone($user->getPhoneNumber()?? '');
$landlord->setLandlordEmail($user->getEmail()?? '');
$landlord->setLandlordAddress($user->getUserAddress()?? '');
$landlord->setLandlordCity($user->getUserCity()?? '');
$landlord->setLandlordPostcode($user->getUserAddressPostcode()?? '');
// Associate the Landlord entity with the user
$user->setLandlord($landlord);
$landlordsRepository->save($landlord,true);
} else if ($userType === 'ROLE_BROKER') {
// Create a new Broker entity object
$broker = new Broker();
$broker->setBrokerName($user->getFirstName()?? '');
$broker->setBrokerSurname($user->getLastName()?? '');
$broker->setBrokerPhone($user->getPhoneNumber()?? '');
$broker->setBrokerEmail($user->getEmail()?? '');
$user->setBroker($broker);
$brokerRepository->save($broker,true);
} else if ($userType === 'ROLE_ACCOUNTANT') {
$accountant = new Accounting();
$accountant->setAccountingName($user->getFirstName()?? '');
$accountant->setAccountingSurname($user->getLastName()?? '');
$accountant->setAccountingEmail($user->getEmail()?? '');
$accountant->setAccountingPhone($user->getPhoneNumber()?? '');
$user->setAccounting($accountant);
$accountingRepository->save($accountant,true) ;
} else if ($userType === 'ROLE_TENANT') {
$tenant = new Tenants();
$tenant->setTenantName($user->getFirstName());
$tenant->setTenantSurname($user->getLastName());
$tenant->setTenantPhone($user->getPhoneNumber());
$tenant->setTenantEmail($user->getEmail());
$user->setTenant($tenant);
$tenantsRepository->save($tenant,true);
}
if (!$userType) {
$user->setUserType(null);
}
}
$userRepository->save($user, true);
return $this->redirectToRoute("app_login");
}
return $this->render("/user/newuser.html.twig",[
"user_form" => $user_form->createView()
])
;
}
*/
/*
public function filterProperties(UrlGeneratorInterface $urlGenerator, Request $request, PropertyListRepository $plr,)
{
$queryBuilder = $this->$plr->createQueryBuilder('p');
if ($this->isGranted('ROLE_BROKER')) {
// Add filters based on form fields
if ($request->query->get('reference')) {
$queryBuilder->andWhere('p.reference = :reference')
->setParameter('reference', $request->query->get('reference'));
}
if ($request->query->get('propertyAddress')) {
$queryBuilder->andWhere('p.propertyAddress = :propertyAddress')
->setParameter('propertyAddress', $request->query->get('propertyAddress'));
}
} else {
if ($request->query->get('property_city')) {
$queryBuilder->andWhere('p.property_city = :property_city')
->setParameter('property_city', $request->query->get('property_city'));
}
if ($request->query->get('propertyType')) {
$queryBuilder->andWhere('p.propertyType = :propertyType')
->setParameter('propertyType', $request->query->get('propertyType'));
}
if ($request->query->get('subType')) {
$queryBuilder->andWhere('p.subType = :subType')
->setParameter('subType', $request->query->get('subType'));
}
if ($request->query->get('property_price')) {
$queryBuilder->andWhere('p.property_price <= :property_price')
->setParameter('property_price', $request->query->get('property_price'));
}
if ($request->query->get('furnished')) {
$queryBuilder->andWhere('p.furnished = :furnished')
->setParameter('furnished', $request->query->get('furnished') === 'true');
}
if ($request->query->get('size')) {
$queryBuilder->andWhere('p.size >= :min_size')
->setParameter('min_size', $request->query->get('size'));
}
if ($request->query->get('rentalType')) {
$queryBuilder->andWhere('p.rentalType = :rentalType')
->setParameter('rentalType', $request->query->get('rentalType'));
}
if ($request->query->get('deliveryType')) {
$queryBuilder->andWhere('p.deliveryType = :deliveryType')
->setParameter('deliveryType', $request->query->get('deliveryType'));
}
if ($request->query->get('precioAlquiler')) {
$queryBuilder->andWhere('p.precioAlquiler <= :precioAlquiler')
->setParameter('precioAlquiler', $request->query->get('precioAlquiler'));
}
if ($request->query->get('precioTraspaso')) {
$queryBuilder->andWhere('p.precioTraspaso <= :precioTraspaso')
->setParameter('precioTraspaso', $request->query->get('precioTraspaso'));
}
if ($request->query->get('broker')) {
$queryBuilder
->join('p.managingAgent', 'b')
->andWhere('b.brokerid = :broker')
->setParameter('broker', $request->query->get('broker'));
}
}
$properties = $queryBuilder->getQuery()->getResult();
$filters = $request->query->all(); // Get all query parameters as filters
$url = $urlGenerator->generate('app_properties', $filters);
// The generated URL will include the filter values as query parameters
echo $url; // Outputs something like: /properties?type=rent&price_min=1000&price_max=2000&city=London
}
*/
#[Route('/properties/inactive', name:'app_properties_inactive')]
public function inactiveProperties(PropertyListRepository $pl): Response
{
$inactive=$pl->findBy(['status'=>'Inactivo']);
return $this->render('property_list/inactive.html.twig', [
'properties' => $inactive,
]);
}
#[Route('/properties', name: 'app_properties', methods: ['GET', 'POST'])]
public function properties(PropertyListRepository $propertyListRepository, Request $request, SessionInterface $session): Response
{
if(!$this->isGranted('ROLE_USER')){ return $this->redirectToRoute('app_login'); }
//$isBroker = $this->security->isGranted('ROLE_BROKER');
$isBroker = $this->isGranted('ROLE_BROKER');
//$brokers=$propertyListRepository->getAllBrokers();
$form = $this->createForm(PropertyFilterType::class, ["status"=>"Activo"]);
$form->handleRequest($request);
// Retrieve the filters from the session
$filters = $session->get('property_filters', []);
$propertyList = $propertyListRepository->createQueryBuilder('p')
->where('LOWER(p.status) LIKE :status')
->setParameter('status', strtolower('activo'))
->getQuery()
->getResult();
$totalCount = count($propertyList);
/*
if ($isBroker) {
$propertyList = $propertyListRepository->createQueryBuilder('p')
->where('LOWER(p.status) LIKE :status')
->setParameter('status', strtolower('activo'))
->getQuery()
->getResult();
$totalCount = count($propertyList);
} else {
$propertyList = $propertyListRepository->createQueryBuilder('p')
->where('LOWER(p.status) LIKE :status')
->setParameter('status', strtolower('activo'))
->getQuery()
->getResult();
$totalCount = count($propertyList);
}
*/
// Apply filters if submitted
if ($form->isSubmitted() && $form->isValid()) {
$filters = $form->getData();
// Store the filters in the session
$session->set('property_filters', $filters);
$propertyList = $propertyListRepository->filterProperties($filters);
$totalCount = count($propertyList);
}
// Create a Pagerfanta adapter with the property list
$adapter = new ArrayAdapter($propertyList);
$paginator = new Pagerfanta($adapter);
$paginator->setMaxPerPage(20); // Display 20 properties per page
// Get the current page from the request
//$page = $request->query->getInt('page', 1);
$page = intval($request->query->get("property_filter")["page"] ?? 1);
if($page===0){ $page=1; }
$paginator->setCurrentPage($page);
// Get the properties for the current page
$currentPageProperties = $paginator->getCurrentPageResults();
return $this->render('property_page2.html.twig', [
'form' => $form->createView(),
'name' => 'PropertiesController',
'propertyList' => $currentPageProperties,
'totalCount' => $totalCount,
'currentPage' => $page,
'totalPages' => $paginator->getNbPages(),
'request'=>$request,
//'brokers'=>$brokers,
]);
}
#[Route('/newproperty', name: 'app_newproperty')]
public function newProperty(PropertyListRepository $propertyListRepository, Request $request,
BrokerRepository $brokerRepository,
UploadHandler $uploadHandler, OperacionesCPPoblacionesYProvincias $opsPobs)
{
//try {
if (!$this->isGranted('ROLE_BROKER')) {
return $this->render('errors/access.html.twig',[
]);
}
$property = new PropertyList();
$property->setStatus("Inactivo");
$property->setTypePropertyAddress("Calle");
$property_form=$this->createForm(NewPropertyType::class, $property);
$property_form->handleRequest($request);
if($property_form->isSubmitted() && $property_form->isValid()){
$property=$property_form->getData();
///// captador/vendedor/gestor add here
$listingAgent = $property_form->get('listingAgent')->getData();
$managingAgent = $property_form->get('managingAgent')->getData();
$sellingAgent = $property_form->get('sellingAgent')->getData();
$property->setManagingAgent($managingAgent);
$property->setListingAgent($listingAgent);
$property->setSellingAgent($sellingAgent);
//$brokerRepository->save($managingAgent, true);
//$brokerRepository->save($listingAgent, true);
/*
if ($sellingAgent) {
$brokerRepository->save($sellingAgent, true);
}
*/
$property->setCreatedAt(new \DateTimeImmutable());
$property->setIdzona($opsPobs->getObjZona($property->getPostcode(), $property->getPropertyCity(), $property->getProvince(), $property->getBarrio(), $property_form->get("idZona")->getData() ?? "0"));
$propertyListRepository->save($property, true);
$id = $property->getId();
$this->addFlash("success", "El inmueble ha sido añadido correctamente!");
if ($request->request->has('exit')) {
return $this->redirectToRoute('more_details', [
'id' => $id,
]);
}
if ($request->request->has('save')) {
return $this->redirectToRoute('app_newdetails', [
'id' => $id,
]);
}
//return $this->redirectToRoute('app_newdetails', ['id' => $id]);
}
// Check if the form has been submitted
if ($request->isMethod('POST') && $property_form->isValid()) {
$disableSaveButton = true;
} else {
$disableSaveButton = false;
}
return $this->render("/property_list/newproperty.html.twig", [
"property_form" => $property_form->createView(),
'disable'=>$disableSaveButton,
]);
}
#[Route('/properties/{id}', name:"more_details", )]
public function moreDetails(EntityManagerInterface $entityManager,
int $id,
PropertyListRepository $plr,
Request $request,
PotentialClientsRepository $pcr,
InterestsRepository $ir
)
{
if (!$this->isGranted('ROLE_USER')) {
return $this->render('errors/access.html.twig',[
]);
//throw $this->createAccessDeniedException('No access for you! Check your credentials with the ADMIN. Thank you.');
}
$property=$entityManager->getRepository(PropertyList::class)->find($id);
if(!$property)
{
return $this->render('/errors/notfound.html.twig',[
]);
}
// get the related PropertyDetails entity
$moreDetails = $property->getPropertyDetails();
if(!$moreDetails) {
return $this->render('/errors/notfound.html.twig',[
]);
}
$bedrooms= $moreDetails->getBedrooms();
$landlords=$property->getLandlords();
$tenants=$property->getTenants();
$images=$property->getImages();
$percentages = [];
foreach ($landlords as $landlord) {
$percentages[$landlord->getId()] = $landlord->getPercentages();
}
$utilities=$property->getUtilities();
$docs = $property->getDocuments();
$energy = false;
$occupancy = false;
foreach ($docs as $doc) {
if ($doc->getEnergy() || $doc->getDocCategory()==="Certificado Eficiencia Energética" || $doc->getDocCategory()==="CEE & CEH") {
$energy = true;
}
if ($doc->getOccupancy() || $doc->getDocCategory()==="Cédula de Habitabilitad") {
$occupancy = true;
}
}
$noDocs = '';
if ($energy && $occupancy) {
$status=$property->getStatus();
if (!$status=='en Captación') { //Modificació Javier
//$property->setStatus('Activo');
//$plr->save($property, true);
}
} else {
//$property->setStatus('Inactivo'); //Modificació Javier
//$plr->save($property, true);
if (!$energy && !$occupancy) {
$noDocs= 'Faltan el Certificado Energético y la Cédula de Habitabilidad.';
} elseif (!$occupancy) {
$noDocs = 'Falta la Cédula de Habitabilidad.';
} else {
$noDocs= 'Faltan el Certificado Energético.';
}
}
$user=$this->getUser();
$useremail=$user->getEmail();
$potential=$pcr->findOneBy(
['potentialEmail'=>$useremail]
);
if ($potential) {
$form = $this->createForm(PotentialClientsType::class, $potential,[
]);
} else {
$potential = new PotentialClients();
$this->setPotentialData($potential,$user);
$form = $this->createForm(PotentialClientsType::class, $potential);
}
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
//$interests=$form->getData()->getInterests();
if ($request->isXmlHttpRequest()) {
$pcr->save($potential,true);
//flash()->addSuccess('Precerencias Actualizadas');
} else if ($request->request->has('send')) {
$potential->addProperty($property);
$pcr->save($potential,true);
flash()->addSuccess('Mensaje enviado correctamente');
} else {
flash()->addError('Oopsie.Ha habido un problema');
}
}
return $this->render('moreDetails.html.twig', [
'property'=>$property,
'moreDetails' => $moreDetails,
'bedrooms'=>$bedrooms,
'tenants'=>$tenants,
'landlords'=>$landlords,
'percentages'=>$percentages,
'utilities'=>$utilities,
'images'=>$images,
'noDocs'=>$noDocs,
'form'=>$form->createView(),
]);
}
/*
#[Route('/properties/{id}/edit-propertys' , name:"edit_propertys" ,methods:['GET','POST'])]
public function edit(Request $request, $id,
PropertyListRepository $propertyListRepository,
EntityManagerInterface $entityManager,
PropertyDetailsRepository $propertyDetailsRepository,): Response
{
if (!$this->isGranted('ROLE_BROKER')) {
throw $this->createAccessDeniedException('No access for you! Check your credentials with the ADMIN. Thank you.');
}
$property = $propertyListRepository->find($id);
if (!$property) {
throw $this->createNotFoundException('Property' . $id .' not found');
}
$property_id= $property->getId();
$details=$property->getPropertyDetails();
//$bedrooms=$property->getPropertyDetails()->getBedrooms();
$form = $this->createForm(PropertyFormType::class, $property);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$propertyListRepository->save($property, true);
$propertyDetailsRepository->save($details,true);
return $this->redirectToRoute('edit_property', [
'id' => $property_id,
]);
}
return $this->render('aa/edit.html.twig', [
'property_form' => $form->createView(),
]);
}
*/
#[Route('/properties/{id}/edit-property' , name:"edit_property" ,methods:['GET','POST'])]
public function editProperty(Request $request,
$id,
PropertyListRepository $propertyListRepository,
PropertyDetailsRepository $propertyDetailsRepository,
OperacionesCPPoblacionesYProvincias $opsPobs
) {
if (!$this->isGranted('ROLE_BROKER')) {
return $this->render('errors/access.html.twig',[
]);
}
//$broker=$this->security->getUser()->getBroker();
$broker=$this->getUser()->getBroker();
$admin=$this->isGranted('ROLE_ADMIN');
$property = $propertyListRepository->find($id);
if (!$property) {
return $this->render('errors/notfound.html.twig',[
]);
}
$managingAgent=$property->getManagingAgent();
/*
if (!$admin && $broker !== $managingAgent && $broker !== $property->getListingAgent()) {
return $this->render('errors/access.html.twig',[
]);
} else {
*/
$property_id= $property->getId();
$details = $property->getPropertyDetails();
$type=$property->getPropertyType();
$subtype=$property->getSubType();
//$bedrooms= $details->getBedrooms();
//$landlords = $property->getLandlords();
//$tenants = $property->getTenants();
//$images = $property->getImages();
//$videos = $property->getVideos();
//$documents = $property->getDocuments();
$detailsForm = $this->createForm(NewPropertyDetailsType::class, $details);
$detailsForm->handleRequest($request);
if ($detailsForm->isSubmitted() && $detailsForm->isValid()) {
$double=$detailsForm->get('doubleBed')->getData() ?? '0';
$single=$detailsForm->get('singleBed')->getData() ?? '0';
$bedrooms=$details->setBedroomNumber($double+$single);
$details->setPropertyList($property);
$propertyDetailsRepository->save($details,true);
}
$propertyForm = $this->createForm(NewPropertyType::class, $property);
$propertyForm->get("idZona")->setData($property->getIdzona()!== null ? $property->getIdzona()->getId() : "" );
$propertyForm->handleRequest($request);
if ($propertyForm->isSubmitted() && $propertyForm->isValid()) {
//$property=$propertyForm->getData();
$property->setIdzona($opsPobs->getObjZona($property->getPostcode(), $property->getPropertyCity(), $property->getProvince(), $property->getBarrio(), $propertyForm->get("idZona")->getData() ?? "0"));
$propertyListRepository->save($property,true);
$this->addFlash(
'success',
'Inmueble modificado correctamente!'
);
}
//}
/*
//return $this->redirectToRoute('more_details', ['id' => $id]);
if ($request->request->has('exit')) {
return $this->redirectToRoute('more_details', [
'id' => $id,
]);
}
if ($request->request->has('save')) {
return $this->redirectToRoute('edit_property', [
'id' => $id,
]);
}
if ($request->request->has('add-tenant')) {
return $this->redirectToRoute('app_newtenant', [
'id' => $id,
]);
}
*/
return $this->render("/aa/edit.html.twig",[
"property_form" => $propertyForm->createView(),
//"landlord_forms"=>$landlordForms,
"property_details_form"=>$detailsForm->createView(),
"property"=>$property,
'type'=>$type,
'subtype'=>$subtype,
//"bedroom_forms" => $bedroomForms,
//"image_forms" => $imageForms,
//"tenant_forms"=>$tenantForms,
//"document_forms" => $documentForms,
//"images"=>$images,
//"documents"=>$documents,
//"bedrooms"=>$bedrooms,
//"landlords"=>$landlords,
//"tenants"=>$tenants,
//"ownership"=>$ownership,
//"percentage_forms"=>$percentageForms,
]);
}
#[Route('/properties/delete/{id}' , name:"delete_property")]
public function delete(Request $request, EntityManagerInterface $entityManager, $id): Response
{
if (!$this->isGranted('ROLE_ADMIN')) {
return $this->render('errors/access.html.twig',[
]);
}
$property = $entityManager->getRepository(PropertyList::class)->find($id);
if (!$property) {
return $this->render('errors/notfound.html.twig',[
]);
}
//$property_id= $property->getId();
$property->setStatus('Inactivo');
$details=$property->getPropertyDetails();
$bedrooms=$details->getBedrooms();
//dump($details);
/*
// Remove associated bedrooms
foreach ($bedrooms as $bedroom) {
$entityManager->remove($bedroom);
//set them inactive or not for rent.
}
/*
// Remove associated photos
foreach ($property->getImages() as $image) {
$entityManager->remove($image);
}
//
$entityManager->remove($property);
//$entityManager->remove($details);
$entityManager->flush();
*/
//return new Response('Propiedad Archivada.');
$this->addFlash(
'success',
'Propiedad Archivada.'
);
return $this->redirectToRoute('more_details',['id'=> $property]);
}
#[Route('/newproperty/{id}/newdetails', name: 'app_newdetails')]
public function newPropertyDetails( EntityManagerInterface $entityManager, int $id, Request $request, PropertyDetailsRepository $propertyDetailsRepository,)
{
if (!$this->isGranted('ROLE_BROKER')) {
return $this->render('errors/access.html.twig',[
]);
}
$property= $entityManager->getRepository(PropertyList::class)->find($id);
if (!$property) {
return $this->render('errors/notfound.html.twig',[
]);
}
$idp=$property->getId();
$type=$property->getPropertyType();
$delivery=$property->getDeliveryType();
$subtype=$property->getSubType();
$details= new PropertyDetails();
$details->setPropertyList($property);
$details_form=$this->createForm(NewPropertyDetailsType::class, $details);
$details_form->handleRequest($request);
if($details_form->isSubmitted() && $details_form->isValid()){
//$details=$details_form->getData();
//$property_details->setPropertyList($idp);
//$property_details=$id->setPropertyList();
$double=$details_form->get('doubleBed')->getData() ?? '0';
$single=$details_form->get('singleBed')->getData() ?? '0';
$addition=$single+$double;
$bedrooms=$details->setBedroomNumber($addition);
$propertyDetailsRepository->save($details, true);
//dd($details);
//die;
//$details_id = $property_details->getId();
$this->addFlash("success", "Las características han sido guardadas correctamente.");
//return $this->redirectToRoute('app_newbedroom', ['id' => $id]);
$disableSaveButton = true;
} else {
$disableSaveButton = false;
}
//dd($bedrooms);
//die;
//if ($request->isMethod('POST') && $details_form->isValid()) {
return $this->render("/property_details/newdetails.html.twig",[
"details_form" => $details_form->createView(),
'type'=>$type,
'delivery'=>$delivery,
'subtype'=>$subtype,
'id'=>$idp,
'disable_save_button'=>$disableSaveButton,
/*
return $this->render("/AAAA/newdets.html.twig",[
"details_form" => $details_form->createView(),
*/
]);
}
#[Route('/newpotential', name:"new_potential")]
public function potentialClient(
PotentialClientsRepository $potentialClientsRepository,
Request $request,
EntityManagerInterface $entityManager
): Response {
$property_id = $entityManager->getRepository(PropertyList::class)->find($id);
dd($property_id);
die;
if(!$property_id) {
return $this->render('errors/notfound.html.twig',[
]);
}
$this->getUser()->getPotentialClient();
//$potentialClient = new PotentialClients();
$potentialClient_form=$this->createForm(PotentialClientsType::class);
$potentialClient_form->handleRequest($request);
if($potentialClient_form->isSubmitted() && $potentialClient_form->isValid()){
$potentialClient=$potentialClient_form->getData();
$potentialClient->setProperty($property_id);
$potentialClient->setStatus(true);
//$potentialClientsRepository->save($potentialClient, true);
$this->addFlash ("success","You successfully sent your enquiry!");
//return $this->redirectToRoute("app_properties");
}
return $this->render('info.html.twig', [
"name"=>"potentialClient",
"potentialClient_form"=>$potentialClient_form->createView(),
]);
}
#[Route ('/success', name:'app_success')]
public function success(): Response
{
return $this->render('success/success.html.twig', [
"name"=>"SuccessPage",
]);
}
#[Route('/datosCodigoPostal/{codigoPostal}', name: 'app_datos_codigo_postal', methods: ['POST', 'GET'])]
public function getDatosCodigoPostal(OperacionesCPPoblacionesYProvincias $opsCps, string $codigoPostal):JsonResponse{
return $this->json($opsCps->getDatosCodigoPostal($codigoPostal));
}
/////////DASHBOARDS//////////////////////////////////////////////////
/*
#[Route('/broker', name:"broker_dashboard")]
public function brokerDashboard(): Response
{
return $this->render('/dashboards/broker.html.twig', [
"name"=>"brokerDashboard",
]);
}
#[Route('/landlord', name:"landlord_dashboard")]
public function landlordDashboard(): Response
{
return $this->render('/dashboards/landlord.html.twig', [
"name"=>"landlordDashboard",
]);
}
#[Route('/tenant', name:"tenant_dashboard")]
public function tenantDashboard(): Response
{
return $this->render('/dashboards/tenant.html.twig', [
"name"=>"tenantDashboard",
]);
}
*/
}