<?php
namespace App\Controller;
use App\Entity\AccommodationType;
use App\Entity\Blog;
use App\Entity\Bookings;
use App\Entity\DiscountCode;
use App\Entity\EmailTracing;
use App\Entity\Media;
use App\Entity\Property;
use App\Entity\User;
use App\Security\LoginFormAuthenticator;
use App\Service\GlobalFunctions;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityController extends AbstractController
{
public function __construct(\Swift_Mailer $mailer)
{
$this->mailer = $mailer;
}
/**
* @Route("/login", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}
public function changeProfilePic()
{
$user = $this->get('security.token_storage')->getToken()->getUser();
$Photo = $this->getDoctrine()->getRepository(Media::class)->findOneBy([
'UserId' => $user,
]);
if (!$Photo) {
}
$NewPhoto = new Media();
$entityManager = $this->getDoctrine()->getManager();
$form = $this->createFormBuilder($NewPhoto)
->add('documentFile', VichImageType::class)
->add('Description', TextType::class, ['label' => 'Caption'])
->add('save', SubmitType::class, ['label' => 'Upload'])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// $form->getData() holds the submitted values
// but, the original `$task` variable has also been updated
$NewPhoto = $form->getData();
$NewPhoto->setPropertyCode($listing_code);
$entityManager->persist($NewPhoto);
$entityManager->flush();
}
return $this->render('security/profilepic.html.twig', [
'profileform' => $form->createView(),
]);
}
public function stripeTokenise($stripe_token)
{
$em = $this->getDoctrine()->getManager();
\Stripe\Stripe::setApiKey(getenv('stripe_secret_key'));
$User = $this->get('security.token_storage')->getToken()->getUser();
if (null !== $User->getStripeCustomerToken()) {
$updateCustomer = \Stripe\Customer::update(
$User->getStripeCustomerToken(),
['source' => $stripe_token]
);
} else {
$newCustomer = \Stripe\Customer::create([
'name' => $User->getFirstName().' '.$User->getLastName(),
'email' => $User->getEmail(),
'source' => $stripe_token,
]);
$User->setStripeCustomerToken($newCustomer->id);
$em->persist($User);
$em->flush();
}
return new Response('success');
}
public function updateSavedCard()
{
$user = $this->get('security.token_storage')->getToken()->getUser();
$StripeCustomerToken = $user->getStripeCustomerToken();
if (null == $StripeCustomerToken) {
$StripeDetail = '<h4>You do not have a card saved on file</h4>';
} else {
\Stripe\Stripe::setApiKey(getenv('stripe_secret_key'));
$StripeCustomer = \Stripe\Customer::retrieve($StripeCustomerToken);
if (array_key_exists(0, $StripeCustomer->sources->data)) {
$StripeCardToken = $StripeCustomer->sources->data[0];
$StripeDetail = '<h4>'.$StripeCardToken->brand.' Card ending ****'.$StripeCardToken->last4.'</h4>Expires '.$StripeCardToken->exp_month.'/'.$StripeCardToken->exp_year;
} else {
$StripeDetail = '<h4>You do not have a card saved on file</h4>';
}
}
return $this->render('security/savedcard.html.twig', [
'stripe_detail' => $StripeDetail,
'stripe_public_key' => getenv('stripe_public_key'),
]);
}
public function createGuest(GuardAuthenticatorHandler $guardHandler, Request $request, LoginFormAuthenticator $authenticator, UserPasswordEncoderInterface $passwordEncoder)
{
$FirstName = $request->request->get('FirstName');
$LastName = $request->request->get('LastName');
$EmailAddress = $request->request->get('EmailAddress');
$MobileNumber = $request->request->get('MobileNumber');
if (null !== $request->request->get('Location')) {
$Location = $request->request->get('Location');
$Gender = $request->request->get('Gender');
$NewPassword = $request->request->get('NewPassword');
}
$entityManager = $this->getDoctrine()->getManager();
$GetUser = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email' => $EmailAddress]);
if ($GetUser) {
return new Response('user_exists');
} else {
$User = new User();
$User->setUsername($EmailAddress);
$User->setUsernameCanonical($EmailAddress);
$User->setEmail($EmailAddress);
$User->setEmailCanonical($EmailAddress);
$User->setEnabled(1);
$User->setTermsAccepted(1);
$User->setRoles(['ROLE_USER']);
$User->setFirstName($FirstName);
$User->setLastName($LastName);
$User->setMobilePh($MobileNumber);
$User->setPassword($passwordEncoder->encodePassword($User, $NewPassword));
$entityManager->persist($User);
$entityManager->flush();
$doLogin = $guardHandler->authenticateUserAndHandleSuccess(
$User,
$request,
$authenticator,
'main' // firewall name in security.yaml
);
return new Response('success');
}
}
public function interimDashboard(GlobalFunctions $GlobalFn)
{
/** @var User|null $user - Resolves ->getId() as it doesn't know it's an entity */
$user = $this->getUser();
if (!$user) {
return $this->redirectToRoute('app_login');
}
$user_id = $user->getId();
$getTrips = $this->getDoctrine()
->getRepository(Bookings::class)->findBy(
['HolidaymakerId' => $user_id,
'Status' => ['Confirmed', 'Awaiting Acceptance'], ]
);
$getAccommTypes = $this->getDoctrine()
->getRepository(AccommodationType::class)->findBy(
['LandownerId' => $user_id,
'Enabled' => true, ]
);
$AccommRoomCodes = [];
foreach ($getAccommTypes as $thisAccomm) {
$AccommRoomCodes[] = $thisAccomm->getRoomCode();
}
$getAllTrips = $this->getDoctrine()
->getRepository(Bookings::class)->findBy(
['RoomCode' => $AccommRoomCodes]
);
$TripInfo = [];
$RoomInfo = [];
$PropertyInfo = [];
foreach ($getTrips as $ThisTrip) {
$TripInfo[$ThisTrip->getId()] = $ThisTrip;
$ThisRoomInfo = $this->getDoctrine()
->getRepository(AccommodationType::class)->findOneBy(
['RoomCode' => $ThisTrip->getRoomCode()]
);
$ThisPropertyInfo = $this->getDoctrine()
->getRepository(Property::class)->findOneBy(
['ListingCode' => $ThisRoomInfo->getPropertyCode()]
);
$RoomInfo[$ThisTrip->getId()] = $ThisRoomInfo;
$PropertyInfo[$ThisTrip->getId()] = $ThisPropertyInfo;
}
$AllTripInfo = [];
$AllRoomInfo = [];
$AllPropertyInfo = [];
foreach ($getAllTrips as $ThisTrip) {
$AllTripInfo[$ThisTrip->getId()] = $ThisTrip;
$ThisRoomInfo = $this->getDoctrine()
->getRepository(AccommodationType::class)->findOneBy(
['RoomCode' => $ThisTrip->getRoomCode()]
);
$ThisPropertyInfo = $this->getDoctrine()
->getRepository(Property::class)->findOneBy(
['ListingCode' => $ThisRoomInfo->getPropertyCode()]
);
$AllRoomInfo[$ThisTrip->getId()] = $ThisRoomInfo;
$AllPropertyInfo[$ThisTrip->getId()] = $ThisPropertyInfo;
}
$two_weeks = new \DateTime('-2 weeks');
$MyListings = []; // @phpstan-ignore-next-line
$getListings = $this->getDoctrine()
->getRepository(Property::class)
->createQueryBuilder('p')
->where('p.LandownerId = :user_id')
// ->andWhere('p.CreatedDate >= :two_weeks ')
->setParameters([
'user_id' => $user_id,
// 'two_weeks' => $two_weeks
])
->orderBy('p.ListingStatus', 'DESC')
->getQuery()
->getResult();
foreach ($getListings as $thisListing) {
$MyListings[] = $thisListing->getListingCode();
}
/*$SwiftMailer = new \Swift_Mailer();
$GlobalFn = new GlobalFunctions($this->getDoctrine()->getManager(), $SwiftMailer);*/
$PendingBookings = $this->getDoctrine()
->getRepository(Bookings::class)->findBy(
['PropertyCode' => $MyListings,
'Status' => 'Awaiting Acceptance', ]
);
$GetHolidaymakerPending = [];
$PendingNumNights = [];
foreach ($PendingBookings as $ThisPendingBooking) {
$GetHolidaymakerPending[$ThisPendingBooking->getHolidaymakerId()] = $this->getDoctrine()
->getRepository(User::class)->find($ThisPendingBooking->getHolidaymakerId());
$PendingNumNights[$ThisPendingBooking->getHolidaymakerId()] = $GlobalFn->get_booking_info($ThisPendingBooking->getId(), 'number_nights');
}
$UpcomingBookings = $this->getDoctrine()
->getRepository(Bookings::class)->findBy(
['RoomCode' => $AccommRoomCodes,
'Status' => ['Confirmed', 'Block Out'], ], ['BookingFrom' => 'ASC']
);
$GetHolidaymakerUpcoming = [];
$UpcomingNumNights = [];
foreach ($UpcomingBookings as $ThisUpcomingBooking) {
$GetHolidaymakerUpcoming[$ThisUpcomingBooking->getHolidaymakerId()] = $this->getDoctrine()
->getRepository(User::class)->find($ThisUpcomingBooking->getHolidaymakerId());
$UpcomingNumNights[$ThisUpcomingBooking->getHolidaymakerId()] = $GlobalFn->get_booking_info($ThisUpcomingBooking->getId(), 'number_nights');
}
$ProfilePicture = $GlobalFn->user_photo($user->getId());
$LandownerBlog = $this->getDoctrine()->getRepository(Blog::class)->findBy(['Tag' => 'landowner'], ['id' => 'DESC']);
return $this->render('security/interimdashboard.html.twig', [
'user' => $user,
'user_id' => $user_id,
'listings' => $getListings,
'accomm_types' => $getAccommTypes,
'trips' => $getTrips,
'trip_info' => $TripInfo,
'room_info' => $RoomInfo,
'all_room_info' => $AllRoomInfo,
'all_trip_info' => $AllTripInfo,
'all_property_info' => $AllPropertyInfo,
'property_info' => $PropertyInfo,
'pending_bookings' => $PendingBookings,
'upcoming_bookings' => $UpcomingBookings,
'holidaymaker_pending' => $GetHolidaymakerPending,
'holidaymaker_upcoming' => $GetHolidaymakerUpcoming,
'num_nights_pending' => $PendingNumNights,
'profile_picture' => $ProfilePicture,
'num_nights_upcoming' => $UpcomingNumNights,
'landowner_blog' => $LandownerBlog,
]);
}
public function editProfile(GlobalFunctions $GlobalFn, Request $request)
{
$user = $this->getUser();
$entityManager = $this->getDoctrine()->getManager();
$ProfilePicture = $GlobalFn->user_photo($user->getId());
$form = $this->createFormBuilder($user)
->add('FirstName')
->add('LastName')
->add('LandlinePh')
->add('MobilePh')
->add('AltEmail')
->add('save', SubmitType::class, ['label' => 'Save Details'])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user = $form->getData();
$entityManager->persist($user);
$entityManager->flush();
return $this->render('security/profileedit.html.twig', [
'form' => $form->createView(),
'profile_picture' => $ProfilePicture,
'form_updated' => true,
]);
} else {
return $this->render('security/profileedit.html.twig', [
'form' => $form->createView(),
'profile_picture' => $ProfilePicture,
'form_updated' => false,
]);
}
}
public function newDashboard(GlobalFunctions $GlobalFn)
{
$user = $this->get('security.token_storage')->getToken()->getUser();
$ProfilePicture = $GlobalFn->user_photo($user->getId());
return $this->render('security/newdashboard.html.twig', [
'user' => $user,
'profile_picture' => $ProfilePicture,
]);
}
public function guestDashboard()
{
$user = $this->get('security.token_storage')->getToken()->getUser();
return $this->render('security/newdashboard.html.twig', [
'user' => $user,
]);
}
/**
* @Route("/newsletterregisterendpoint", name="newsletterregisterendpoint")
*/
public function newsletterSubscribe(Request $request, GlobalFunctions $fn)
{
$email = $request->request->get('email');
$first_name = $request->request->get('first_name');
$sg = new \App\Classes\SendGrid();
$search_request = json_decode('{
"list_id": 4302212,
"conditions": [
{"and_or":"","field":"email","value":"'.$email.'","operator":"eq"}
]
} ');
$response = $sg->client->contactdb()->recipients()->search()->post($search_request);
$response_json = json_decode($response->body());
if (isset($response_json->recipient_count) && $response_json->recipient_count > 0) {
if ($request->isXmlHttpRequest()) {
return new Response('already_listed');
}
$referer = $request->headers->get('referer') ?? $this->generateUrl('newsletter');
return $this->redirect($referer.'?error_message=already_listed');
} else {
$request_body = json_decode('[
{
"email": "'.$email.'",
"first_name": "'.$first_name.'"
}
]');
$response = $sg->client->contactdb()->recipients()->post($request_body);
$response_json = json_decode($response->body());
$recipient_id = $response_json->persisted_recipients[0];
$request_body = json_decode('[
"'.$recipient_id.'"
]');
$list_id = 4302212;
$response = $sg->client->contactdb()->lists()->_($list_id)->recipients()->post($request_body);
$this->get('session')->set('newsletter_popup_dismissed', 'dismissed');
// ///////// Send out emails
// Create Discount Code
$entityManager = $this->getDoctrine()->getManager();
/*$Code = "WELCOME20_".substr(strtoupper($first_name),0,20).rand(1000,9999);
$DateExpiry = new \DateTime(date("Y-m-d",strtotime("+30 days")));
$DiscountCode = new DiscountCode();
$DiscountCode->setCode($Code);
$DiscountCode->setReservedUses(0);
$DiscountCode->setAllowOnlyMinNights(1);
$DiscountCode->setAllowOnlyMinSpend(0);
$DiscountCode->setValidFrom(new \DateTime());
$DiscountCode->setValidTo($DateExpiry);
$DiscountCode->setDiscountAmount("20");
$DiscountCode->setEmail($email);
$entityManager->persist($DiscountCode);
$entityManager->flush();*/
$fn->send_template_email($email, 'join_tribe_welcome_email', [
'first_name' => $first_name,
]);
if ($request->isXmlHttpRequest()) {
return new Response('success');
}
$referer = $request->headers->get('referer') ?? $this->generateUrl('newsletter');
return $this->redirect($referer.'?success');
}
}
/**
* @Route("/newsletterstoppopup", name="newsletterstoppopup")
*/
public function newsletterStopPopup(Request $request)
{
$this->get('session')->set('newsletter_popup_dismissed', 'dismissed');
return new Response('dismissed');
}
/**
* @Route("/getnewsletterstatus", name="getnewsletterstatus")
*/
public function getnewsletterstatus(Request $request)
{
$status = $this->get('session')->get('newsletter_popup_dismissed');
if ('dismissed' == $status) {
return new Response('dismissed');
} else {
return new Response('show');
}
}
/**
* @Route("/exitintentserved", name="exitintentserved")
*/
public function exitintentserved(Request $request)
{
$this->get('session')->set('exitintent_popup_dismissed', 'dismissed');
return new Response('dismissed');
}
/**
* @Route("/sendexitintent", name="sendexitintent")
*/
public function sendexitintent(Request $request)
{
$email_address = $request->request->get('email_address');
$first_name = $request->request->get('first_name');
$location = $request->request->get('location');
$looking_for = $request->request->get('looking_for');
$message = (new \Swift_Message('Need a hand request - '.$first_name))
->setFrom('support@otbt.co.nz')
->setTo('info@otbt.co.nz')
->setBody(
'Hi there, a need a hand request has been received.<br><br>Requested By: '.$first_name.'<br>Email: '.$email_address.'<br><br>Location: '.$location.'<br><br>Looking For:<br>'.$looking_for.'<br><br>OTBT System',
'text/html'
);
$this->mailer->send($message);
$this->get('session')->set('exitintent_popup_dismissed', 'dismissed');
return new Response('success');
}
/**
* @Route("/countemailopen/{id}", name="count_email_open")
*/
public function count_email_open(EmailTracing $email)
{
$newCount = $email->getOpens() + 1;
$email->setOpens($newCount);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($email);
$entityManager->flush();
return new Response('success');
}
}