<?php
namespace App\Controller;
use App\Entity\AccommodationType;
use App\Entity\Blog;
use App\Entity\Bookings;
use App\Entity\CMSBlocks;
use App\Entity\CMSMenu;
use App\Entity\CMSPages;
use App\Entity\Favourites;
use App\Entity\GiftVoucherPurchases;
use App\Entity\ListingQuestions;
use App\Entity\Property;
use App\Entity\PropertyReviews;
use App\Entity\PropertyTags;
use App\Entity\PropertyTagsApplied;
use App\Entity\Regions;
use App\Entity\Terms;
use App\Entity\TermsAcceptance;
use App\Entity\User;
use App\Entity\VoucherCodes;
use App\Entity\WebsiteControl;
use App\Service\GlobalFunctions;
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
use SendGrid\Response as SendGridResponse;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class StaticPagesController extends AbstractController
{
/**
* @var CacheManager
*/
private $liipCache;
public function __construct(GlobalFunctions $GlobalFn, CacheManager $liipCache)
{
$this->GlobalFn = $GlobalFn;
$this->liipCache = $liipCache;
}
/**
* @Route("/", name="home_page", schemes={"https"})
*/
public function index(GlobalFunctions $GlobalFn): Response
{
$this->get('session')->set('search_query', null);
$this->get('session')->set('search_filters_location', null);
$this->get('session')->set('search_filters_experience', null);
$this->get('session')->set('search_filters_amenity', null);
$this->get('session')->set('search_filters_propertytype', null);
$this->get('session')->set('search_filters_groupoptions', null);
$this->get('session')->set('search_check_in_date', '');
$this->get('session')->set('search_check_out_date', '');
if (isset($_GET['p'])) {
if ('listing' == $_GET['p']) {
$FirstAccomm = $this->getDoctrine()->getRepository(AccommodationType::class)->findOneBy(['PropertyCode' => $_GET['listingCode']], ['id' => 'ASC'], 1, 0);
$Property = $this->getDoctrine()->getRepository(Property::class)->findOneBy(['ListingCode' => $_GET['listingCode']]);
return $this->redirectToRoute('listing', ['listing_slug' => $Property->getListingSlug(), 'room_slug' => $FirstAccomm->getRoomSlug()]);
}
}
$Blogs = $this->getDoctrine()->getRepository(Blog::class)->findBy([], ['id' => 'DESC'], 6, 0);
$conn = $this->getDoctrine()->getManager()->getConnection();
$sql = "SELECT *,accommodation_type.key_statement AS 'accomm_key_statement' FROM accommodation_type INNER JOIN property ON accommodation_type.property_code=property.listing_code WHERE accommodation_type.enabled='1' AND accommodation_type.eating_drinking!='' AND property.listing_status='Listed' ORDER BY RAND() LIMIT 0,4
";
$stmt = $conn->prepare($sql);
$stmt->execute();
$HomeRooms = $stmt->fetchAll();
$HomeRoomPhotos = [];
$em = $this->getDoctrine()->getManager();
$Specials_GetTag = $this->getDoctrine()->getRepository(PropertyTags::class)->findOneBy(['TagName' => 'Specials']);
if (null == $Specials_GetTag) {
$Specials_Rooms = [];
} else {
$Specials_GetApplied = $this->getDoctrine()->getRepository(PropertyTagsApplied::class)->findBy(['Tag' => $Specials_GetTag]);
$Specials_Rooms = [];
shuffle($Specials_GetApplied);
$i = 0;
foreach ($Specials_GetApplied as $thisApplied) {
$Accomm = $thisApplied->getRoom();
if (null !== $Accomm) {
if (1 == $Accomm->getEnabled() && 'Listed' == $Accomm->getProperty()->getListingStatus()) {
if ('' == $Accomm->getSearchHeadline() or 'Display Name of Listing' == $Accomm->getSearchHeadline() && (0 == $Accomm->getFeaturedFirst() or null == $Accomm->getFeaturedFirst())) {
} else {
$Specials_Rooms[] = $Accomm;
if (7 == $i) {
break;
}
++$i;
}
}
}
}
}
$SweetAsFamily_GetTag = $this->getDoctrine()->getRepository(PropertyTags::class)->findOneBy(['TagName' => 'Sweet As for the Family']);
if (null == $SweetAsFamily_GetTag) {
$SweetAsFamily_Rooms = [];
} else {
$SweetAsFamily_GetApplied = $this->getDoctrine()->getRepository(PropertyTagsApplied::class)->findBy(['Tag' => $SweetAsFamily_GetTag]);
$SweetAsFamily_Rooms = [];
shuffle($SweetAsFamily_GetApplied);
$i = 0;
foreach ($SweetAsFamily_GetApplied as $thisApplied) {
$Accomm = $thisApplied->getRoom();
if (null !== $Accomm) {
if (1 == $Accomm->getEnabled() && 'Listed' == $Accomm->getProperty()->getListingStatus()) {
if ('' == $Accomm->getSearchHeadline() or 'Display Name of Listing' == $Accomm->getSearchHeadline()) {
} else {
$SweetAsFamily_Rooms[] = $Accomm;
if (7 == $i) {
break;
}
++$i;
}
}
}
}
}
$FurryFriendsWelcome_GetTag = $this->getDoctrine()->getRepository(PropertyTags::class)->findOneBy(['TagName' => 'Furry Friends Welcome']);
if (null == $FurryFriendsWelcome_GetTag) {
$FurryFriendsWelcome_Rooms = [];
} else {
$FurryFriendsWelcome_GetApplied = $this->getDoctrine()->getRepository(PropertyTagsApplied::class)->findBy(['Tag' => $FurryFriendsWelcome_GetTag]);
$FurryFriendsWelcome_Rooms = [];
shuffle($FurryFriendsWelcome_GetApplied);
$i = 0;
foreach ($FurryFriendsWelcome_GetApplied as $thisApplied) {
$Accomm = $thisApplied->getRoom();
if (null !== $Accomm) {
if (1 == $Accomm->getEnabled() && 'Listed' == $Accomm->getProperty()->getListingStatus()) {
if ('' == $Accomm->getSearchHeadline() or 'Display Name of Listing' == $Accomm->getSearchHeadline()) {
} else {
$FurryFriendsWelcome_Rooms[] = $Accomm;
if (7 == $i) {
break;
}
++$i;
}
}
}
}
}
$GetOffGrid_GetTag = $this->getDoctrine()->getRepository(PropertyTags::class)->findOneBy(['TagName' => 'Get Off the Grid']);
if (null == $GetOffGrid_GetTag) {
$GetOffGrid_Rooms = [];
} else {
$GetOffGrid_GetApplied = $this->getDoctrine()->getRepository(PropertyTagsApplied::class)->findBy(['Tag' => $GetOffGrid_GetTag]);
$GetOffGrid_Rooms = [];
shuffle($GetOffGrid_GetApplied);
$i = 0;
foreach ($GetOffGrid_GetApplied as $thisApplied) {
$Accomm = $thisApplied->getRoom();
if (null !== $Accomm) {
if (1 == $Accomm->getEnabled() && 'Listed' == $Accomm->getProperty()->getListingStatus()) {
if ('' == $Accomm->getSearchHeadline() or 'Display Name of Listing' == $Accomm->getSearchHeadline()) {
} else {
$GetOffGrid_Rooms[] = $Accomm;
if (7 == $i) {
break;
}
++$i;
}
}
}
}
}
$RomanticRetreats_GetTag = $this->getDoctrine()->getRepository(PropertyTags::class)->findOneBy(['TagName' => 'Romantic Retreats']);
if (null == $RomanticRetreats_GetTag) {
$RomanticRetreats_Rooms = [];
} else {
$RomanticRetreats_GetApplied = $this->getDoctrine()->getRepository(PropertyTagsApplied::class)->findBy(['Tag' => $RomanticRetreats_GetTag]);
$RomanticRetreats_Rooms = [];
shuffle($RomanticRetreats_GetApplied);
$i = 0;
foreach ($RomanticRetreats_GetApplied as $thisApplied) {
$Accomm = $thisApplied->getRoom();
if (null !== $Accomm) {
if (1 == $Accomm->getEnabled() && 'Listed' == $Accomm->getProperty()->getListingStatus()) {
if ('' == $Accomm->getSearchHeadline() or 'Display Name of Listing' == $Accomm->getSearchHeadline()) {
} else {
$RomanticRetreats_Rooms[] = $Accomm;
if (7 == $i) {
break;
}
++$i;
}
}
}
}
}
foreach ($HomeRooms as $ThisRoom) {
$Media = $GlobalFn->room_photos($ThisRoom['room_code'], 1);
$Media = $this->liipCache->getBrowserPath($Media, 'mobile_images');
$HomeRoomPhotos[$ThisRoom['room_code']] = $Media;
}
$CurrentDate = new \DateTimeImmutable();
$TomorrowDate = $CurrentDate->add(new \DateInterval('P1D'));
$Reviews = $this->getDoctrine()->getRepository(PropertyReviews::class)->findBy(['StarRating' => 5, 'Approved' => 1]);
shuffle($Reviews);
$i = 0;
$OutputReviews = [];
foreach ($Reviews as $thisReview) {
if (null !== $thisReview->getBookingId()) {
$ReviewBooking = $this->getDoctrine()->getRepository(Bookings::class)->find($thisReview->getBookingId());
if ($ReviewBooking) {
$Holidaymaker = $this->getDoctrine()->getRepository(User::class)->find($ReviewBooking->getHolidaymakerId());
$AccommType = $this->getDoctrine()->getRepository(AccommodationType::class)->findOneBy(['RoomCode' => $ReviewBooking->getRoomCode()]);
$Property = $this->getDoctrine()->getRepository(Property::class)->findOneBy(['ListingCode' => $AccommType->getPropertyCode()]);
$AccommImage = $GlobalFn->room_photos($AccommType->getRoomCode(), 1);
if ($i < 4) {
$OutputReviews[] = [$thisReview, $AccommType, $Holidaymaker, $AccommImage, $Property];
}
++$i;
}
}
}
// Get home page popup
$HomePagePopupEnabled = $this->getDoctrine()->getRepository(WebsiteControl::class)->findOneBy(['KeyName' => 'home_page_alert_box_enabled']);
if (1 == $HomePagePopupEnabled->getValue()) {
$PopupBoxEnabled = 1;
$HomePagePopupTitle = $this->getDoctrine()->getRepository(WebsiteControl::class)->findOneBy(['KeyName' => 'home_page_alert_box_title'])->getValue();
$HomePagePopupContent = $this->getDoctrine()->getRepository(WebsiteControl::class)->findOneBy(['KeyName' => 'home_page_alert_box_content'])->getValue();
} else {
$PopupBoxEnabled = 0;
$HomePagePopupTitle = null;
$HomePagePopupContent = null;
}
$Regions = $this->getDoctrine()->getRepository(Regions::class)->findAll();
return $this->render('static_pages/newhome.html.twig', [
'blogs' => $Blogs,
'is_home_page' => true,
'HomeRooms' => $HomeRooms,
'HomeRoomsPhotos' => $HomeRoomPhotos,
'CurrentDate' => $CurrentDate,
'TomorrowDate' => $TomorrowDate,
'reviews' => $OutputReviews,
'popup_box_enabled' => $PopupBoxEnabled,
'popup_box_title' => $HomePagePopupTitle,
'popup_box_content' => $HomePagePopupContent,
'specials' => $Specials_Rooms,
'sweetasfamily' => $SweetAsFamily_Rooms,
'furryfriendswelcome' => $FurryFriendsWelcome_Rooms,
'getoffgrid' => $GetOffGrid_Rooms,
'romanticretreats' => $RomanticRetreats_Rooms,
'regionlist' => $Regions,
]);
}
public function list()
{
return $this->render('static_pages/listyourproperty.html.twig', [
'controller_name' => 'StaticPagesController',
]);
}
public function aboutus()
{
return $this->render('static_pages/aboutus.html.twig', [
'controller_name' => 'StaticPagesController',
]);
}
public function sendTestMessage()
{
$sender = 'jsm';
$threadBuilder = $this->get('fos_message.composer')->newThread();
$threadBuilder
->addRecipient('jsm') // Retrieved from your backend, your user manager or ...
->setSender($sender)
->setSubject('Stof commented on your pull request #456789')
->setBody('You have a typo, : mondo instead of mongo. Also for coding standards ...');
$sender = $this->get('fos_message.sender');
$sender->send($threadBuilder->getMessage());
}
public function notifications()
{
return $this->render('static_pages/notifications.html.twig', [
'controller_name' => 'StaticPagesController',
]);
}
public function contactUs()
{
return $this->render('static_pages/contactus.html.twig');
}
public function faq()
{
return $this->render('static_pages/faqs.html.twig');
}
public function newsletter(Request $request)
{
return $this->render('static_pages/newsletter.html.twig');
}
public function topBarStuff(GlobalFunctions $GlobalFn)
{
if ($this->isGranted('ROLE_USER')) {
$UserId = $this->get('security.token_storage')->getToken()->getUser()->getId();
$Favourites = $this->getDoctrine()->getRepository(Favourites::class)->findBy([
'UserId' => $UserId,
]);
$Rooms = [];
foreach ($Favourites as $ThisFavourite) {
$Rooms[$ThisFavourite->getRoom()->getId()] = $this->getDoctrine()->getRepository(AccommodationType::class)->find($ThisFavourite->getRoom()->getId());
}
$RoomPhoto = [];
foreach ($Favourites as $ThisFavourite) {
$RoomPhoto[$ThisFavourite->getRoom()->getId()] = $GlobalFn->room_photos($Rooms[$ThisFavourite->getRoom()->getId()]->getRoomCode(), true);
}
$Property = [];
foreach ($Favourites as $ThisFavourite) {
$Property[$ThisFavourite->getRoom()->getId()] = $this->getDoctrine()->getRepository(Property::class)->findOneBy(['ListingCode' => $Rooms[$ThisFavourite->getRoom()->getId()]->getPropertyCode()]);
}
return $this->render('static_pages/topbaraddin.html.twig', [
'favourites' => $Favourites,
'rooms' => $Rooms,
'photos' => $RoomPhoto,
'properties' => $Property,
]);
} else {
return new Response('');
}
}
public function NEWtopBarStuff(GlobalFunctions $GlobalFn)
{
if ($this->isGranted('ROLE_USER')) {
$UserId = $this->get('security.token_storage')->getToken()->getUser()->getId();
$Favourites = $this->getDoctrine()->getRepository(Favourites::class)->findBy([
'UserId' => $UserId,
]);
$Rooms = [];
foreach ($Favourites as $ThisFavourite) {
$Rooms[$ThisFavourite->getRoomId()] = $this->getDoctrine()->getRepository(AccommodationType::class)->find($ThisFavourite->getRoomId());
}
$RoomPhoto = [];
foreach ($Favourites as $ThisFavourite) {
$RoomPhoto[$ThisFavourite->getRoomId()] = $GlobalFn->room_photos($Rooms[$ThisFavourite->getRoomId()]->getRoomCode(), true);
}
$Property = [];
foreach ($Favourites as $ThisFavourite) {
$Property[$ThisFavourite->getRoomId()] = $this->getDoctrine()->getRepository(Property::class)->findOneBy(['ListingCode' => $Rooms[$ThisFavourite->getRoomId()]->getPropertyCode()]);
}
return $this->render('static_pages/NEWtopbaraddin.html.twig', [
'favourites' => $Favourites,
'rooms' => $Rooms,
'photos' => $RoomPhoto,
'properties' => $Property,
]);
} else {
return new Response('');
}
}
public function giftvoucherBuy()
{
return $this->render('static_pages/buygiftvoucher.html.twig', [
'stripe_public_key' => getenv('stripe_public_key'),
]);
}
public function payGiftVoucherPostal($stripe_token, GlobalFunctions $GlobalFn)
{
$request = Request::createFromGlobals();
$YourName = $request->request->get('your_name');
$YourEmail = $request->request->get('your_email');
$YourMessage = $request->request->get('your_message');
$RecipientName = $request->request->get('recipient_name');
$SendingOption = $request->request->get('sending_option');
$AddressLine1 = $request->request->get('address_line1');
$AddressLine2 = $request->request->get('address_line2');
$AddressLine3 = $request->request->get('address_line3');
$AddressLine4 = $request->request->get('address_line4');
$Amount = $request->request->get('amount');
$AmountWithFee = $Amount + 5;
$Purchase = new GiftVoucherPurchases();
$NewPurchaseCode = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678901234567890'), 0, 16);
$Purchase->setPurchaseCode($NewPurchaseCode);
$Purchase->setPurchaserName($YourName);
$Purchase->setPurchaserEmail($YourEmail);
$Purchase->setMessage($YourMessage);
$Purchase->setSendingOption('post');
$Purchase->setRecipientName($RecipientName);
$Purchase->setAddressLine1($AddressLine1);
$Purchase->setAddressLine2($AddressLine2);
$Purchase->setAddressLine3($AddressLine3);
$Purchase->setAddressLine4($AddressLine4);
$Purchase->setAmount($Amount);
$em = $this->getDoctrine()->getManager();
$em->persist($Purchase);
$em->flush();
$StripeToCharge = ($AmountWithFee + 0.3) / (1 - 0.029);
$StripeToChargeCorrected = ceil($StripeToCharge * 100);
$amount = $Amount;
\Stripe\Stripe::setApiKey(getenv('stripe_secret_key'));
$ERRORMODE = 0;
$em = $this->getDoctrine()->getManager();
if (0 == $amount) {
$ERRORMODE = 0;
} else {
try {
$charge = \Stripe\Charge::create([
'amount' => $StripeToChargeCorrected,
'currency' => 'nzd',
'description' => 'Gift Voucher Purchase #'.$Purchase->getId(),
'source' => $stripe_token,
'capture' => true,
]);
} catch (\Stripe\Error\Card $e) {
$ERRORMODE = 1;
$body = $e->getJsonBody();
$err = $body['error'];
if ('card_error' == $err['type']) {
if ('invalid_number' == $err['code']) {
$ErrorReportText = "Your credit card number is INVALID. Please try again, your card HASN'T BEEN CHARGED.";
}
if ('invalid_expiry_month' == $err['code']) {
$ErrorReportText = "Your expiry month is INVALID. Please try again, your card HASN'T BEEN CHARGED.";
}
if ('invalid_expiry_year' == $err['code']) {
$ErrorReportText = "Your expiry year is INVALID. Please try again, your card HASN'T BEEN CHARGED.";
}
if ('invalid_cvc' == $err['code']) {
$ErrorReportText = "Your CVC number is INVALID. Please try again, your card HASN'T BEEN CHARGED.";
}
if ('invalid_swipe_data' == $err['code']) {
$ErrorReportText = "Your swipe data is INVALID. Please try again, your card HASN'T BEEN CHARGED.";
}
if ('incorrect_number' == $err['code']) {
$ErrorReportText = "Your credit card number is WRONG. Please try again, your card HASN'T BEEN CHARGED.";
}
if ('expired_card' == $err['code']) {
$ErrorReportText = "Your credit card has EXPIRED. Please try again, your card HASN'T BEEN CHARGED.";
}
if ('incorrect_cvc' == $err['code']) {
$ErrorReportText = "Your CVC number is wrong. Please try again, your card HASN'T BEEN CHARGED.";
}
if ('incorrect_zip' == $err['code']) {
$ErrorReportText = "Your ZIP code is wrong. Please try again, your card HASN'T BEEN CHARGED.";
}
if ('card_declined' == $err['code']) {
$ErrorReportText = 'Your card has been declined by the bank.';
}
if ('missing' == $err['code']) {
$ErrorReportText = "An error occured on OTBT's end. Please logon to the OTBT dashboard to retry payment (API-CARD-MISSING)";
}
if ('processing_error' == $err['code']) {
$ErrorReportText = "An error occured on OTBT's end. Please logon to the OTBT dashboard to retry payment (API-CARD-PROCESSING)";
}
}
} catch (\Stripe\Error\RateLimit $e) {
$ERRORMODE = 1;
// Too many requests made to the API too quickly
$ErrorReportText = "An error occured on OTBT's end. Please logon to the OTBT dashboard to retry payment (err ratelimit)";
} catch (\Stripe\Error\InvalidRequest $e) {
$ERRORMODE = 1;
$body = $e->getJsonBody();
$err = $body['error'];
// Invalid parameters were supplied to Stripe's API
$ErrorReportText = "An error occured on OTBT's end. Please logon to the OTBT dashboard to retry payment (err invalidrequest)";
echo 'Status is:'.$e->getHttpStatus()."\n";
echo 'Type is:'.$err['type']."\n";
echo 'Code is:'.$err['code']."\n";
// param is '' in this case
echo 'Param is:'."\n";
echo 'Message is:'.$err['message']."\n";
} catch (\Stripe\Error\Authentication $e) {
$ERRORMODE = 1;
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
$ErrorReportText = "An error occured on OTBT's end. Please logon to the OTBT dashboard to retry payment (err auth)";
} catch (\Stripe\Error\ApiConnection $e) {
$ERRORMODE = 1;
// Network communication with Stripe failed
$ErrorReportText = "An error occured on OTBT's end. Please logon to the OTBT dashboard to retry payment (err api)";
} catch (\Stripe\Error\Base $e) {
$ERRORMODE = 1;
// Display a very generic error to the user, and maybe send
// yourself an email
$ErrorReportText = "An error occured on OTBT's end. Please logon to the OTBT dashboard to retry payment (err errgen)";
} catch (\Throwable $e) {
$ERRORMODE = 1;
// Something else happened, completely unrelated to Stripe
$ErrorReportText = "An error occured on OTBT's end. Please logon to the OTBT dashboard to retry payment (err exception)";
}
}
if (0 == $ERRORMODE) {
$Voucher = new VoucherCodes();
$NewCode = rand(1000, 9999).'-'.rand(1000, 9999).'-'.rand(1000, 9999).'-'.rand(1000, 9999);
$Expiry = new \DateTime();
$Expiry = $Expiry->add(new \DateInterval('P1Y'));
$Voucher->setVoucherCode($NewCode);
$Voucher->setFaceValue($Amount);
$Voucher->setStoredValue($Amount);
$Voucher->setExpiry($Expiry);
$Voucher->setMinimumSpend(0);
$Voucher->setPurchaseInfo($Purchase);
$Voucher->setCreatedDate(new \DateTime());
$em->persist($Voucher);
$em->flush();
$CCfee = $StripeToCharge - $AmountWithFee;
$GiftReceipt = "<table width='100%'>";
$GiftReceipt .= '<tr>';
$GiftReceipt .= '<td><strong>Gift Voucher Value</strong></td>';
$GiftReceipt .= '<td>'.number_format($Amount, 2).'</td>';
$GiftReceipt .= '</tr>';
$GiftReceipt .= '<tr>';
$GiftReceipt .= '<td><strong>Postal Fee</strong></td>';
$GiftReceipt .= '<td>5.00</td>';
$GiftReceipt .= '</tr>';
$GiftReceipt .= '<tr>';
$GiftReceipt .= '<td><strong>Credit Card Fee</strong></td>';
$GiftReceipt .= '<td>'.number_format($CCfee, 2).'</td>';
$GiftReceipt .= '</tr>';
$GiftReceipt .= '<tr>';
$GiftReceipt .= '<td><strong>Total Paid</strong></td>';
$GiftReceipt .= '<td>'.number_format($StripeToCharge, 2).'</td>';
$GiftReceipt .= '</tr>';
$GiftReceipt .= '</table>';
$VoucherViewEmail = 'https://'.$_SERVER['SERVER_NAME'].$this->generateUrl('show_gift_voucher', ['purchase_id' => $NewPurchaseCode]);
// SEND EMAIL - RECEIPT
$email = new \SendGrid\Mail\Mail();
$email->setFrom('support@otbt.co.nz', 'Off The Beaten Track');
$email->addTo($YourEmail);
$email->setTemplateId('d-63a8db02d3ac41caa57b9349ef9f625f'); // UPDATED SG TEMPLATE 2024
$email->addDynamicTemplateDatas([
'purchaser_name' => $YourName,
'gift_receipt' => $GiftReceipt,
'voucher_url' => $VoucherViewEmail,
]);
$sendgrid = new \App\Classes\SendGrid();
try {
$response = $sendgrid->send($email);
} catch (\Throwable $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
// SEND POSTAL DESPATCH
$email = new \SendGrid\Mail\Mail();
$email->setFrom('support@otbt.co.nz', 'OTBT System');
$email->addTo('info@otbt.co.nz');
$email->addTo('jessica@otbt.co.nz');
$email->setSubject('Gift Voucher Purchase - Postal Despatch');
$email->addContent(
'text/html',
"Hi Admin, <br><br>A gift voucher has been purchased online and has been chosen as postal despatch. Please despatch this gift voucher, as per the details below:<br><br>Purchaser: $YourName ($YourEmail) <br>Voucher Code: $NewCode<br>Sending option: $SendingOption<br><br>Address for Delivery:<br>$AddressLine1<br>$AddressLine2<br>$AddressLine3<br>$AddressLine4<br><br>Recipient Name: $RecipientName<br><br><br>NOTE: If the sending option is SEND_TO_PURCHASER then put the name of the purchaser on the envelope (so it can be delivered to them) and the name of the Recipient on the gift voucher. Otherwise use the Recipient name on the envelope. <br><br>Thanks,<br>OTBT System"
);
$sendgrid = new \App\Classes\SendGrid();
try {
$response = $sendgrid->send($email);
} catch (\Throwable $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
// SEND ACCOUNTS NOTIFY
$email = new \SendGrid\Mail\Mail();
$email->setFrom('support@otbt.co.nz', 'Off The Beaten Track');
// $email->addTo("partner.otbt@luminate.one");
$email->addTo('support@otbt.co.nz');
$email->setTemplateId('d-ffb11e3792844a04ba21bd7ddc8c4995'); // UPDATE SG TEMPLATE 2024
$email->addDynamicTemplateDatas([
'purchaser_name' => $YourName,
'purchaser_email' => $YourEmail,
'gift_receipt' => $GiftReceipt,
'purchase_id' => $Purchase->getId(),
]);
$sendgrid = new \App\Classes\SendGrid();
try {
$response = $sendgrid->send($email);
} catch (\Throwable $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
return new Response('success:'.$NewPurchaseCode);
} else {
return new Response('Error: '.$ErrorReportText);
}
}
public function payGiftVoucherEmail($stripe_token, Request $request, GlobalFunctions $GlobalFn)
{
$YourName = $request->request->get('your_name');
$YourEmail = $request->request->get('your_email');
$YourMessage = $request->request->get('your_message');
$SendingOption = $request->request->get('sending_option');
$RecipientName = $request->request->get('recipient_name');
$RecipientEmail = $request->request->get('recipient_email');
$Amount = $request->request->get('amount');
$AmountWithFee = $Amount + 0;
$Purchase = new GiftVoucherPurchases();
$NewPurchaseCode = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678901234567890'), 0, 16);
$Purchase->setPurchaseCode($NewPurchaseCode);
$Purchase->setPurchaserName($YourName);
$Purchase->setPurchaserEmail($YourEmail);
$Purchase->setMessage($YourMessage);
$Purchase->setSendingOption($SendingOption);
$Purchase->setRecipientName($RecipientName);
$Purchase->setRecipientEmail($RecipientEmail);
$Purchase->setAmount($Amount);
$em = $this->getDoctrine()->getManager();
$em->persist($Purchase);
$em->flush();
$StripeToCharge = ($AmountWithFee + 0.3) / (1 - 0.029);
$StripeToChargeCorrected = ceil($StripeToCharge * 100);
$amount = $Amount;
\Stripe\Stripe::setApiKey(getenv('stripe_secret_key'));
$ERRORMODE = 0;
$em = $this->getDoctrine()->getManager();
if (0 == $amount) {
$ERRORMODE = 0;
} else {
try {
$charge = \Stripe\Charge::create([
'amount' => $StripeToChargeCorrected,
'currency' => 'nzd',
'description' => 'Gift Voucher Purchase #'.$Purchase->getId(),
'source' => $stripe_token,
'capture' => true,
]);
} catch (\Stripe\Error\Card $e) {
$ERRORMODE = 1;
$body = $e->getJsonBody();
$err = $body['error'];
if ('card_error' == $err['type']) {
if ('invalid_number' == $err['code']) {
$ErrorReportText = "Your credit card number is INVALID. Please try again, your card HASN'T BEEN CHARGED.";
}
if ('invalid_expiry_month' == $err['code']) {
$ErrorReportText = "Your expiry month is INVALID. Please try again, your card HASN'T BEEN CHARGED.";
}
if ('invalid_expiry_year' == $err['code']) {
$ErrorReportText = "Your expiry year is INVALID. Please try again, your card HASN'T BEEN CHARGED.";
}
if ('invalid_cvc' == $err['code']) {
$ErrorReportText = "Your CVC number is INVALID. Please try again, your card HASN'T BEEN CHARGED.";
}
if ('invalid_swipe_data' == $err['code']) {
$ErrorReportText = "Your swipe data is INVALID. Please try again, your card HASN'T BEEN CHARGED.";
}
if ('incorrect_number' == $err['code']) {
$ErrorReportText = "Your credit card number is WRONG. Please try again, your card HASN'T BEEN CHARGED.";
}
if ('expired_card' == $err['code']) {
$ErrorReportText = "Your credit card has EXPIRED. Please try again, your card HASN'T BEEN CHARGED.";
}
if ('incorrect_cvc' == $err['code']) {
$ErrorReportText = "Your CVC number is wrong. Please try again, your card HASN'T BEEN CHARGED.";
}
if ('incorrect_zip' == $err['code']) {
$ErrorReportText = "Your ZIP code is wrong. Please try again, your card HASN'T BEEN CHARGED.";
}
if ('card_declined' == $err['code']) {
$ErrorReportText = 'Your card has been declined by the bank.';
}
if ('missing' == $err['code']) {
$ErrorReportText = "An error occured on OTBT's end. Please logon to the OTBT dashboard to retry payment (API-CARD-MISSING)";
}
if ('processing_error' == $err['code']) {
$ErrorReportText = "An error occured on OTBT's end. Please logon to the OTBT dashboard to retry payment (API-CARD-PROCESSING)";
}
}
} catch (\Stripe\Error\RateLimit $e) {
$ERRORMODE = 1;
// Too many requests made to the API too quickly
$ErrorReportText = "An error occured on OTBT's end. Please logon to the OTBT dashboard to retry payment (err ratelimit)";
} catch (\Stripe\Error\InvalidRequest $e) {
$ERRORMODE = 1;
$body = $e->getJsonBody();
$err = $body['error'];
// Invalid parameters were supplied to Stripe's API
$ErrorReportText = "An error occured on OTBT's end. Please logon to the OTBT dashboard to retry payment (err invalidrequest)";
echo 'Status is:'.$e->getHttpStatus()."\n";
echo 'Type is:'.$err['type']."\n";
echo 'Code is:'.$err['code']."\n";
// param is '' in this case
echo 'Param is:'."\n";
echo 'Message is:'.$err['message']."\n";
} catch (\Stripe\Error\Authentication $e) {
$ERRORMODE = 1;
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
$ErrorReportText = "An error occured on OTBT's end. Please logon to the OTBT dashboard to retry payment (err auth)";
} catch (\Stripe\Error\ApiConnection $e) {
$ERRORMODE = 1;
// Network communication with Stripe failed
$ErrorReportText = "An error occured on OTBT's end. Please logon to the OTBT dashboard to retry payment (err api)";
} catch (\Stripe\Error\Base $e) {
$ERRORMODE = 1;
// Display a very generic error to the user, and maybe send
// yourself an email
$ErrorReportText = "An error occured on OTBT's end. Please logon to the OTBT dashboard to retry payment (err errgen)";
} catch (\Throwable $e) {
$ERRORMODE = 1;
// Something else happened, completely unrelated to Stripe
$ErrorReportText = "An error occured on OTBT's end. Please logon to the OTBT dashboard to retry payment (err exception)";
}
}
if (0 == $ERRORMODE) {
$Voucher = new VoucherCodes();
$NewCode = rand(1000, 9999).'-'.rand(1000, 9999).'-'.rand(1000, 9999).'-'.rand(1000, 9999);
$Expiry = new \DateTime();
$Expiry = $Expiry->add(new \DateInterval('P1Y'));
$Voucher->setVoucherCode($NewCode);
$Voucher->setFaceValue($Amount);
$Voucher->setStoredValue($Amount);
$Voucher->setExpiry($Expiry);
$Voucher->setMinimumSpend(0);
$Voucher->setPurchaseInfo($Purchase);
$Voucher->setCreatedDate(new \DateTime());
$em->persist($Voucher);
$em->flush();
$CCfee = $StripeToCharge - $AmountWithFee;
$GiftReceipt = "<table width='100%'>";
$GiftReceipt .= '<tr>';
$GiftReceipt .= '<td><strong>Gift Voucher Value</strong></td>';
$GiftReceipt .= '<td>'.number_format($Amount, 2).'</td>';
$GiftReceipt .= '</tr>';
$GiftReceipt .= '<tr>';
$GiftReceipt .= '<td><strong>Credit Card Fee</strong></td>';
$GiftReceipt .= '<td>'.number_format($CCfee, 2).'</td>';
$GiftReceipt .= '</tr>';
$GiftReceipt .= '<tr>';
$GiftReceipt .= '<td><strong>Total Paid</strong></td>';
$GiftReceipt .= '<td>'.number_format($StripeToCharge, 2).'</td>';
$GiftReceipt .= '</tr>';
$GiftReceipt .= '</table>';
$VoucherViewEmail = 'https://'.$_SERVER['SERVER_NAME'].$this->generateUrl('show_gift_voucher', ['purchase_id' => $NewPurchaseCode]);
// SEND EMAIL - RECEIPT
$email = new \SendGrid\Mail\Mail();
$email->setFrom('support@otbt.co.nz', 'Off The Beaten Track');
$email->addTo($YourEmail);
$email->setTemplateId('d-63a8db02d3ac41caa57b9349ef9f625f'); // SG TEMPLATE UPDATE 2024
$email->addDynamicTemplateDatas([
'purchaser_name' => $YourName,
'gift_receipt' => $GiftReceipt,
'voucher_url' => $VoucherViewEmail,
]);
$sendgrid = new \App\Classes\SendGrid();
try {
$response = $sendgrid->send($email);
} catch (\Throwable $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
// SEND VOUCHER EMAIL TO WHOEVER
$email = new \SendGrid\Mail\Mail();
$email->setFrom('support@otbt.co.nz', 'Off The Beaten Track');
$email->addTo($RecipientEmail);
$email->setTemplateId('d-799d041efae24812b675bae46b4420fe'); // UPDATED SG TEMPLATE 2024
$email->addDynamicTemplateDatas([
'purchaser_name' => $YourName,
'purchaser_email' => $YourEmail,
'recipient_name' => $RecipientName,
'voucher_url' => $VoucherViewEmail,
]);
$sendgrid = new \App\Classes\SendGrid();
try {
$response = $sendgrid->send($email);
} catch (\Throwable $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
// SEND ACCOUNTS NOTIFY
$email = new \SendGrid\Mail\Mail();
$email->setFrom('support@otbt.co.nz', 'Off The Beaten Track');
$email->addTo('support@otbt.co.nz');
// $email->addTo("partner.otbt@luminate.one");
$email->setTemplateId('d-ffb11e3792844a04ba21bd7ddc8c4995'); // UPDATE SG TEMPLATE 2024
$email->addDynamicTemplateDatas([
'purchaser_name' => $YourName,
'purchaser_email' => $YourEmail,
'gift_receipt' => $GiftReceipt,
'purchase_id' => $Purchase->getId(),
]);
$sendgrid = new \App\Classes\SendGrid();
try {
$response = $sendgrid->send($email);
} catch (\Throwable $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
return new Response('success:'.$NewPurchaseCode);
} else {
return new Response('Error: '.$ErrorReportText);
}
}
public function giftvoucherPaid($purchase_id)
{
$Purchase = $this->getDoctrine()->getRepository(GiftVoucherPurchases::class)->findOneBy(['PurchaseCode' => $purchase_id]);
return $this->render('static_pages/giftvoucherpaid.html.twig', [
'purchase' => $Purchase,
]);
}
public function giftvoucherView($purchase_id)
{
$Purchase = $this->getDoctrine()->getRepository(GiftVoucherPurchases::class)->findOneBy(['PurchaseCode' => $purchase_id]);
return $this->render('static_pages/giftvoucherview.html.twig', [
'purchase' => $Purchase,
]);
}
public function giftvoucherPrint($purchase_id)
{
$Purchase = $this->getDoctrine()->getRepository(GiftVoucherPurchases::class)->findOneBy(['PurchaseCode' => $purchase_id]);
return $this->render('static_pages/giftvoucherprint.html.twig', [
'purchase' => $Purchase,
]);
}
public function masthead()
{
return $this->render('static_pages/aboutwebsite.html.twig');
}
public function accept_terms(): Response
{
return $this->render('static_pages/acceptterms.html.twig', [
'returnPath' => $_GET['returnPath'], ]
);
}
public function record_accept_terms(): Response
{
$returnPath = $_GET['returnPath'];
$User = $this->getUser();
$User->setTermsAccepted(1);
$TermsAcceptance = new TermsAcceptance();
$TermsAcceptance->setUser($User);
$TermsAcceptance->setAcceptanceIP($_SERVER['REMOTE_ADDR']);
$TermsAcceptance->setAcceptanceDateTime(new \DateTime());
$this->getDoctrine()->getManager()->persist($User);
$this->getDoctrine()->getManager()->persist($TermsAcceptance);
$this->getDoctrine()->getManager()->flush();
return new RedirectResponse($returnPath);
}
public function referralReward(): Response
{
return $this->render('static_pages/propertyreferral.html.twig');
}
public function competitionEntry(): Response
{
return $this->render('static_pages/competitionentry.html.twig');
}
public function roadies(): Response
{
return $this->render('static_pages/roadies.html.twig');
}
public function hireGear(): Response
{
return $this->render('static_pages/hiregear.html.twig');
}
public function landownerVideo(): Response
{
return $this->render('static_pages/landownervideo.html.twig');
}
public function sendEmailFormToSupport($form_name, $send_to, Request $request): Response
{
// $formData = print_r($request->request, true);
$formData = '';
foreach ($request->request as $name => $value) {
$formData .= '<br>';
$formData .= '<strong>'.$name.'</strong>:<br>';
$formData .= $value.'<br>';
}
$expSendTo = explode(',', $send_to);
$email = new \SendGrid\Mail\Mail();
$email->setFrom('support@otbt.co.nz', 'OTBT System');
foreach ($expSendTo as $thisSend) {
$email->addTo($thisSend);
}
$email->setSubject('Email Form Submitted - '.$form_name);
$email->addContent(
'text/html',
'Hi Admin, <br><br><pre>'.$formData.'</pre> <br><br>Thanks,<br>OTBT System'
);
$sendgrid = new \App\Classes\SendGrid();
try {
$response = $sendgrid->send($email);
} catch (\Throwable $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
return new Response('success');
}
public function iframeCaptive(): Response
{
return new Response('success');
}
public function globalWebsiteControl(): Response
{
// Find unplanned maintenance
$UnplannedMaintenanceMode = $this->getDoctrine()->getRepository(WebsiteControl::class)->findOneBy(['KeyName' => 'unplanned_maintenance_mode']);
$UnplannedMaintenanceText = $this->getDoctrine()->getRepository(WebsiteControl::class)->findOneBy(['KeyName' => 'unplanned_maintenance_text']);
$newsletter_popup_dismissed = $this->get('session')->get('newsletter_popup_dismissed');
$exitintent_popup_dismissed = $this->get('session')->get('exitintent_popup_dismissed');
$ActiveStylesheet = $this->GlobalFn->datedVar('active_stylesheet', date('Y-m-d'));
if ('var_not_found' == $ActiveStylesheet) {
$StylesheetURL = 'newtheme/css/clean-blog.css';
} else {
$StylesheetURL = $ActiveStylesheet;
}
if ($UnplannedMaintenanceMode) {
if ('1' == $UnplannedMaintenanceMode->getValue()) {
return $this->render('static_pages/headercontrols.html.twig', [
'unplanned_maintenance_mode' => true,
'unplanned_maintenance_text' => $UnplannedMaintenanceText->getValue(),
'planned_maintenance' => null,
'site_wide_header_content' => null,
'swhcolour' => null,
'newsletter_popup_status' => $newsletter_popup_dismissed,
'exitintent_popup_status' => $exitintent_popup_dismissed,
'stylesheet_url' => $StylesheetURL,
]);
}
}
// Find planned maintenance
$TimeNow = new \DateTime();
$PlannedMaintenance = $this->getDoctrine()->getRepository("App\Entity\PlannedMaintenance")->createQueryBuilder('t')
->where(':current_time BETWEEN t.FromTime AND t.ToTime')
->setParameter('current_time', $TimeNow)
->getQuery()
->getResult();
if (0 == count($PlannedMaintenance)) {
$PlannedMaintenance = null;
} else {
return $this->render('static_pages/headercontrols.html.twig', [
'unplanned_maintenance_mode' => false,
'unplanned_maintenance_text' => null,
'planned_maintenance' => $PlannedMaintenance,
'site_wide_header_content' => null,
'swhcolour' => null,
'newsletter_popup_status' => $newsletter_popup_dismissed,
'exitintent_popup_status' => $exitintent_popup_dismissed,
'stylesheet_url' => $StylesheetURL,
]);
}
// Find site wide headers
$SiteWideHeader = $this->getDoctrine()->getRepository(WebsiteControl::class)->findOneBy(['KeyName' => 'site_wide_header_text']);
$SiteWideHeaderTimed = $this->GlobalFn->datedVar('site_wide_header_text', date('Y-m-d'));
$SiteWideHeaderColour = $this->getDoctrine()->getRepository(WebsiteControl::class)->findOneBy(['KeyName' => 'site_wide_header_colour']);
if (null == $SiteWideHeaderColour) {
$SWHColour = 'CC7722';
} else {
$SWHColour = $SiteWideHeaderColour->getValue();
}
if ('var_not_found' == $SiteWideHeaderTimed) {
$SWHText = $SiteWideHeader->getValue();
} else {
$SWHText = $SiteWideHeaderTimed;
}
if ('' !== $SiteWideHeader->getValue()) {
return $this->render('static_pages/headercontrols.html.twig', [
'unplanned_maintenance_mode' => false,
'unplanned_maintenance_text' => null,
'planned_maintenance' => null,
'site_wide_header_content' => $SWHText,
'swhcolour' => $SWHColour,
'newsletter_popup_status' => $newsletter_popup_dismissed,
'exitintent_popup_status' => $exitintent_popup_dismissed,
'stylesheet_url' => $StylesheetURL,
]);
} else {
return $this->render('static_pages/headercontrols.html.twig', [
'unplanned_maintenance_mode' => false,
'unplanned_maintenance_text' => null,
'planned_maintenance' => null,
'site_wide_header_content' => null,
'swhcolour' => null,
'newsletter_popup_status' => $newsletter_popup_dismissed,
'exitintent_popup_status' => $exitintent_popup_dismissed,
'stylesheet_url' => $StylesheetURL,
]);
}
}
public function static_page($slug): Response
{
$Page = $this->getDoctrine()->getRepository(CMSPages::class)->findOneBy(['Slug' => $slug, 'Type' => 'static']);
$GetAboveContent = $this->getDoctrine()->getRepository(CMSBlocks::class)->findOneBy(['Page' => $Page, 'Identifier' => 'abovecontent']);
if (null == $GetAboveContent) {
$AboveContent = '';
} else {
$AboveContent = $GetAboveContent->getContent();
}
$GetBody = $this->getDoctrine()->getRepository(CMSBlocks::class)->findOneBy(['Page' => $Page, 'Identifier' => 'body']);
if (null == $GetBody) {
$Body = '';
} else {
$Body = $GetBody->getContent();
}
return $this->render('static_pages/staticpage.html.twig', [
'htmlcontent' => false,
'page_title' => $Page->getPageTitle(),
'abovecontent' => $AboveContent,
'body' => $Body,
]);
}
public function dynamicMenu(): Response
{
$GetItems = $this->getDoctrine()->getRepository(CMSMenu::class)->findBy(['ParentItem' => null], ['ItemOrder' => 'ASC']);
$Env = $this->getParameter('kernel.environment');
return $this->render('static_pages/dynamicMenu.html.twig', [
'items' => $GetItems,
'env' => $Env,
]);
}
public function showNewsletterPopup()
{
if (null == $this->get('session')->get('newsletter_popup_shown')) {
}
}
/**
* @Route("/phplisttest", name="phplisttest")
*/
public function phplisttest(): Response
{
$Email = 'hello@concentric.co.nz';
$ch = curl_init();
$POST_DATA = http_build_query([
'login_name' => 'admin',
'password' => '7aqCbgQ2k',
]);
curl_setopt($ch, CURLOPT_URL, 'http://comms.otbt.co.nz/lists/api/v2/sessions');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POST_DATA);
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$keyraw = curl_exec($ch);
$keydec = json_decode($keyraw);
$key = $keydec->key;
curl_close($ch);
$ch = curl_init();
$POST_DATA = http_build_query([
'email' => $Email,
]);
curl_setopt($ch, CURLOPT_URL, 'http://comms.otbt.co.nz/custom_addsub.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POST_DATA);
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$userid = curl_exec($ch);
curl_close($ch);
$ch = curl_init();
$POST_DATA = http_build_query([
'sub_id' => $userid,
'list_id' => 3,
'action' => 'add',
]);
curl_setopt($ch, CURLOPT_URL, 'http://comms.otbt.co.nz/custom_linksublist.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POST_DATA);
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return new Response('FROM SERVER: '.$response);
}
/**
* @Route("/updatedterms/{id}", name="updatedterms")
*/
public function updatedterms(Terms $Terms)
{
@$returnPath = $_GET['returnPath'];
return $this->render('static_pages/acceptupdatedterms.html.twig', [
'terms' => $Terms,
'returnPath' => $returnPath,
]);
}
/**
* @Route("/updatedterms/{id}/accept", name="updatedterms_accept")
*/
public function updatedterms_accept(Terms $Terms)
{
$TermsAcceptance = new TermsAcceptance();
$TermsAcceptance->setTermsVersion($Terms);
$TermsAcceptance->setUser($this->getUser());
$TermsAcceptance->setAcceptanceIP($_SERVER['REMOTE_ADDR']);
$TermsAcceptance->setAcceptanceDateTime(new \DateTime());
$this->getDoctrine()->getManager()->persist($TermsAcceptance);
$this->getDoctrine()->getManager()->flush();
if (isset($_GET['returnPath'])) {
if ('' !== $_GET['returnPath']) {
return new RedirectResponse($_GET['returnPath']);
} else {
return $this->redirectToRoute('fos_user_profile_show');
}
} else {
return $this->redirectToRoute('fos_user_profile_show');
}
}
/**
* @Route("/ask_a_question", name="ask_a_question")
*/
public function listingNewQA(Request $request, UrlGeneratorInterface $router): Response
{
$person_name = (string) $request->request->get('person_name');
$person_email = (string) $request->request->get('person_email');
$question = (string) $request->request->get('question');
$room_id = (string) $request->request->get('room_id');
/**
* @var AccommodationType $Room
*/
$Room = $this->getDoctrine()->getRepository(AccommodationType::class)->find($room_id);
$Landowner = $this->getDoctrine()->getRepository(User::class)->find($Room->getLandownerId());
if ('' !== $question) {
$newQA = new ListingQuestions();
$newQA->setRoom($Room);
$newQA->setQuestion($question);
$newQA->setAskedDate(new \DateTime());
$newQA->setAskedByName($person_name);
$newQA->setAskedByEmail($person_email);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($newQA);
$entityManager->flush();
$ReplyURL = 'https://'.$_SERVER['SERVER_NAME'].$router->generate('landowner_qa_answer', ['id' => $newQA->getId()]);
$ModerateURL = 'https://'.$_SERVER['SERVER_NAME'].$router->generate('admin_listingquestions_moderate', ['id' => $newQA->getId()]);
$email = new \SendGrid\Mail\Mail();
$email->setFrom('support@otbt.co.nz', 'OTBT System');
$email->addTo('info@otbt.co.nz');
// $email->addTo('jordan@luminate.one');
// $email->addTo("partner.otbt@luminate.one");
$email->setSubject('New QA FROM HOLIDAYMAKER to be moderated');
$email->addContent(
'text/html',
"<div style='font-family: Arial, sans-serif;'>
<p style='color: #2d3748; font-size: 16px;'>Hi team,</p>
<p style='color: #2d3748;'>A new question has been asked by a holidaymaker. Please review and moderate it promptly:</p>
<p style='margin: 10px 0; text-align: center;'>
<!--[if mso]>
<v:roundrect xmlns:v='urn:schemas-microsoft-com:vml' xmlns:w='urn:schemas-microsoft-com:office:word' href='".htmlspecialchars($ModerateURL)."' style='height:40px;v-text-anchor:middle;width:200px;' arcsize='10%' stroke='f' fillcolor='#4299e1'>
<w:anchorlock/>
<center style='color:#ffffff;font-family:sans-serif;font-size:13px;font-weight:bold;'>Moderate Now</center>
</v:roundrect>
<![endif]-->
<!--[if !mso]> <!-->
<a href='".htmlspecialchars($ModerateURL)."' style='background-color: #4299e1; color: white; padding: 10px 15px; border-radius: 5px; text-decoration: none; display: inline-block; mso-hide: all;'>Moderate Now</a>
<!-- <![endif]-->
</p>
<p style='color: #718096; margin-top: 20px; font-size: 14px;'>OTBT System</p>
</div>"
);
$sendgrid = new \App\Classes\SendGrid();
try {
/** @var SendGridResponse $response */
$response = $sendgrid->send($email);
} catch (\Throwable $e) {
return new Response('error sending request', 500);
}
if (202 == $response->statusCode()) {
return new Response('success');
}
}
return new Response('something went wrong');
}
}