src/Controller/RCS/ContentController.php line 197

Open in your IDE?
  1. <?php
  2. namespace App\Controller\RCS;
  3. use App\Controller\Master\ContentController as MasterContentController;
  4. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  8. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  9. use Symfony\Component\HttpFoundation\RedirectResponse;
  10. use Symfony\Component\HttpFoundation\File\UploadedFile;
  11. use Symfony\Component\HttpFoundation\JsonResponse;
  12. use Symfony\Component\Cache\Adapter\FilesystemAdapter;
  13. use Symfony\Component\Routing\Annotation\Route;
  14. use Symfony\Component\Form\Forms;
  15. use App\Form\Type\ContentType;
  16. use App\Form\Type\ContentAdminType;
  17. use App\Form\Type\CommentType;
  18. use App\Entity\Content;
  19. use App\Entity\Site;
  20. use App\Entity\SiteConfig;
  21. use App\Entity\ContentMeta;
  22. use App\Entity\Comment;
  23. use App\Entity\Category;
  24. use App\Entity\Customer;
  25. use App\Entity\CustomerPhone;
  26. use App\Entity\CustomerAddress;
  27. use App\Entity\Lead;
  28. use App\Entity\User;
  29. use App\Entity\Coupon;
  30. use App\Entity\Product;
  31. use App\Entity\ProductOptionValue;
  32. use App\Entity\Purchase;
  33. use App\Entity\PurchaseItem;
  34. use App\Entity\PurchaseNote;
  35. use App\Entity\Media;
  36. use App\Entity\MediaGroupItem;
  37. use App\Entity\MediaGroup;
  38. use App\Entity\MediaGroupContainer;
  39. use App\Entity\Contact;
  40. use App\Entity\ContentAnalyticsDaily;
  41. use App\Entity\QuizQuestion;
  42. use App\Form\Type\CustomerType;
  43. use App\Form\Type\LeadType;
  44. use App\Form\DirectoryLeadType;
  45. use App\Utils\CategoryHelper;
  46. use App\Utils\ContentHelper;
  47. use App\Utils\CustomerHelper;
  48. use App\Utils\ContactHelper;
  49. use App\Utils\UserHelper;
  50. use App\Utils\EmailHelper;
  51. use App\Utils\OrderHelper;
  52. use App\Utils\MediaHelper;
  53. use App\Utils\MenuHelper;
  54. use App\Utils\LeadHelper;
  55. use App\Utils\PollHelper;
  56. use Vich\UploaderBundle\Storage\StorageInterface;
  57. use Vich\UploaderBundle\Mapping\PropertyMapping;
  58. use \Swift_Mailer as Swift_Mailer;
  59. use \Swift_Message as Swift_Message;
  60. use Symfony\Component\DependencyInjection\ContainerInterface as Container;
  61. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  62. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  63. use Twig\Environment;
  64. class ContentController extends MasterContentController
  65. {
  66.     
  67.     public function contentMembersOnlyCheck($content) {
  68.         if($content->getMembersOnly() && (!$this->user || (!$this->user->isMember() && !$this->user->isAdmin()))) {
  69.             $this->addFlash("warning""This page is only accessible to RCS Club members. Continue below to become a member and access this page.");
  70.             return $this->redirectToRoute("rcs-club-sign-up");
  71.         }
  72.     }
  73.     
  74.     //Post override example:
  75.     /* *
  76.      * @ Route("/post/{slug}", name="post")
  77.      * /
  78.     public function post(
  79.         Request $request,
  80.         ContentHelper $contentHelper,
  81.         $slug = ""
  82.     ) {
  83.         //return parent::post(func_get_args());
  84.         return parent::post($request, $contentHelper, $slug);
  85.     }*/
  86.     
  87.     
  88.     
  89. //TODO: Not normal route - called in template.
  90.     
  91.     // displays the webinars list page
  92.     // requres a content object to be passed as $content
  93.     public function webinars(
  94.         Request $request,
  95.         ContentHelper $helper,
  96.         MediaHelper $mediaHelper,
  97.         $content ""
  98.     ) {
  99.         $webinars = [];
  100.         $webinars["coming_up"] = $helper->getContent(Content::WEBINAR"coming-up-next""published""desc"00false"*"true)["content"];
  101.         $webinars["series_2018"] = $helper->getContent(Content::WEBINAR"rcs-2018-webinar-series-on-demand""published""desc"00false"*"true)["content"];
  102.         $webinars["archive_marketing"] = $helper->getContent(Content::WEBINAR"rcs-webinar-archive-contractor-marketing-series""published""desc"00false"*"true)["content"];
  103.         $webinars["archive_nrca"] = $helper->getContent(Content::WEBINAR"rcs-webinar-archive-nrca-webinars""published""desc"00false"*"true)["content"];
  104.         $images = [];
  105.         foreach($webinars as $key => $value) {
  106.             $images[$key] = [];
  107.             foreach($value as $c) {
  108.                 $cm $c->getContentMetaByKey("webinar_showgraphic");
  109.                 if(is_null($cm) || $cm->getMetavalue() == 0) {
  110.                     $images[$key][] = "";
  111.                 }
  112.                 else {
  113.                     $m $mediaHelper->getMediaByOldId($cm->getMetavalue());
  114.                     $images[$key][] = $m;
  115.                 }
  116.             }
  117.         }
  118.         return $this->defaultRender("content/tmpl/webinars.html.twig", [
  119.             "content" => $content,
  120.             "webinars" => $webinars,
  121.             "images" => $images,
  122.             "meta" => [
  123.                 "adGroup" => 'rlw'
  124.             ]
  125.         ]);
  126.     }
  127.     // displays the partner webinars page
  128.     // requres a content object to be passed as $content
  129.     public function partnerwebinars(
  130.         Request $request,
  131.         ContentHelper $helper,
  132.         MediaHelper $mediaHelper,
  133.         $content ""
  134.     ) {
  135.         $webinars = [];
  136.         $webinars["coming_up"] = $helper->getContent(Content::WEBINAR"partner-coming-up-next""published""desc"00false"*"true)["content"];
  137.         //$webinars["on_demand"] = $helper->getContent(Content::WEBINAR, "partner-on-demand", "published", "desc", 0, 0, false, "*", true)["content"];
  138.         return $this->defaultRender("content/tmpl/partner-webinars.html.twig", [
  139.             "content" => $content,
  140.             "webinars" => $webinars,
  141.         ]);
  142.     }
  143.     //TODO: test
  144.     // displays the roofing galleries page
  145.     // requres a content object to be passed as $content
  146.     public function roofinggalleries(
  147.         Request $request,
  148.         ContentHelper $helper,
  149.         MediaHelper $mediaHelper,
  150.         $content ""
  151.     ) {
  152.         //$galleries = [];
  153.         //$galleries = $helper->getContentByType(Content::GALLERY, 'title');
  154.         $galleries $helper->getGalleries("roofing-galleries""title");
  155.         /*
  156.         //$galleries[] = $helper->getContentBySlug(Content::GALLERY, "a-day-in-the-life");
  157.         $galleries[] = $helper->getContentBySlug(Content::GALLERY, "beautiful-roofing");
  158.         $galleries[] = $helper->getContentBySlug(Content::GALLERY, "craftsmanship");
  159.         $galleries[] = $helper->getContentBySlug(Content::GALLERY, "fun-photos");
  160.         $galleries[] = $helper->getContentBySlug(Content::GALLERY, "green-roofs");
  161.         $galleries[] = $helper->getContentBySlug(Content::GALLERY, "metal-roofing");
  162.         $galleries[] = $helper->getContentBySlug(Content::GALLERY, "roof-of-the-month");
  163.         $galleries[] = $helper->getContentBySlug(Content::GALLERY, "roofers-in-action");
  164.         $galleries[] = $helper->getContentBySlug(Content::GALLERY, "roofing-history");
  165.         $galleries[] = $helper->getContentBySlug(Content::GALLERY, "solar-roofing");
  166.         $galleries[] = $helper->getContentBySlug(Content::GALLERY, "unique-roofs");
  167.         $galleries[] = $helper->getContentBySlug(Content::GALLERY, "what-happened-here");
  168.         */
  169.         return $this->defaultRender("content/tmpl/roofing-galleries.html.twig", [
  170.             "content" => $content,
  171.             "galleries" => $galleries,
  172.         ]);
  173.     }
  174.     // displays the partner galleries page
  175.     // requres a content object to be passed as $content
  176.     public function partnergalleries(
  177.         Request $request,
  178.         ContentHelper $helper,
  179.         MediaHelper $mediaHelper,
  180.         $content ""
  181.     ) {
  182.         $galleries $helper->getGalleries("partner-galleries""title");
  183.         return $this->defaultRender("content/tmpl/roofing-galleries.html.twig", [
  184.             "content" => $content,
  185.             "galleries" => $galleries,
  186.         ]);
  187.     }
  188.     
  189.     // displays the meet the Zoom embed page
  190.     // requres a content object to be passed as $content
  191.     public function zoomembed(
  192.         Request $request,
  193.         ContentHelper $helper,
  194.         $content ""
  195.     ) {
  196.         /*
  197.         $chatAccess = false;
  198.         $ssoParams = "";
  199.         $moderator = 0;
  200.         $name = "Guest";
  201.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  202.             $user = $this->getUser();
  203.             if($user) {
  204.                 $chatAccess = true;
  205.                 if($user->isAdmin()) {
  206.                     $moderator = 1;
  207.                 }
  208.                 
  209.                 // Chatroll Single Sign-On (SSO) Parameters
  210.                 $uid = $user->getId();                  // Current user id
  211.                 $uname = $user->getUsername();          // Current user name
  212.                 $ulink = '';                               // Current user profile URL (leave blank for none)
  213.                 $upic = '';                             // Current user profile picture URL (leave blank for none)
  214.                 //if($user->getMedia()) {
  215.                 //    $upic = $user->getMedia()->getAbsoluteURL();
  216.                 //}
  217.                 $ismod = $moderator;                     // Is current user a moderator?
  218.                 $sig = md5($uid . $uname . $ismod . 'b7ofqalwup2rtbkg');
  219.                 $ssoParams = '&uid=' . $uid . "&uname=" . urlencode($uname) . "&ulink=" . urlencode($ulink) . "&upic=" . urlencode($upic) . "&ismod=" . $ismod . "&sig=" . $sig;
  220.                 
  221.             }
  222.         }
  223.         */
  224.         
  225.         $meetingAccess false;
  226.         $name "Guest";
  227.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  228.             $user $this->getUser();
  229.             if($user) {
  230.                 $name $user->getDisplayname();
  231.                 $meetingAccess true;
  232.             }
  233.         }
  234.         
  235.         $name base64_encode($name);
  236.         
  237.         $meetingId str_replace("-"""$content->getZoomMeetingId());
  238.         $displayMeeting $content->getZoomDisplayMeeting();
  239.         
  240.         return $this->defaultRender("content/tmpl/zoom-embed.html.twig", [
  241.             //"chatAccess" => $chatAccess,
  242.             //"ssoParams" => $ssoParams,
  243.             
  244.             "content" => $content,
  245.             "meetingId" => $meetingId,
  246.             "displayMeeting" => $displayMeeting,
  247.             "name" => $name,
  248.             "meetingAccess" => $meetingAccess,
  249.         ]);
  250.     }
  251.     
  252.     
  253.     
  254.     //TODO: landing pages
  255.     /**
  256.      * @Route("/rcs/{slug}", name="submit-landing-page", methods={"POST"})
  257.      *
  258.      */
  259.     public function submitLandingPage (
  260.         ContentHelper $contentHelper,
  261.         EmailHelper $emailHelper,
  262.         LeadHelper $leadHelper,
  263.         Request $request,
  264.         Container $container,
  265.         $slug
  266.     ) {
  267.         if($emailHelper->checkCaptcha($request->get("g-recaptcha-response"))) {
  268.         // because of time constraints - processing here
  269.         $lead $request->get("lead");
  270.         if(!$lead) {$lead = [];}
  271.         $firstname array_key_exists("firstname"$lead) ? $lead["firstname"] : "";
  272.         $lastname array_key_exists("lastname"$lead) ? $lead["lastname"] : "";
  273.         $company array_key_exists("company"$lead) ? $lead["company"] : "";
  274.         $phone array_key_exists("phone"$lead) ? $lead["phone"] : "";
  275.         $email array_key_exists("email"$lead) ? $lead["email"] : "";
  276.         $contractor_type array_key_exists("contractor_type"$lead) ? $lead["contractor_type"] : "";
  277.         $address1 array_key_exists("address1"$lead) ? $lead["address1"] : "";
  278.         $address2 array_key_exists("address2"$lead) ? $lead["address2"] : "";
  279.         $city array_key_exists("city"$lead) ? $lead["city"] : "";
  280.         $state array_key_exists("state"$lead) ? $lead["state"] : "";
  281.         $zip array_key_exists("zip"$lead) ? $lead["zip"] : "";
  282.         //special form fields (until the form builder is made):
  283.         //  *Note: also need to add to Utils/LeadHelper
  284.         $collar_size array_key_exists("collar_size"$lead) ? $lead["collar_size"] : "";
  285.         $years_in_business array_key_exists("years_in_business"$lead) ? $lead["years_in_business"] : "";
  286.         $num_field_crew array_key_exists("num_field_crew"$lead) ? $lead["num_field_crew"] : "";
  287.         $annual_revenue array_key_exists("annual_revenue"$lead) ? $lead["annual_revenue"] : "";
  288.         $self_perform_trade array_key_exists("self_perform_trade"$lead) ? $lead["self_perform_trade"] : "";
  289.         //custom fields from the form builder
  290.         $lead_custom $request->get("lead_custom");
  291.         $lead_custom_img $request->get("lead_custom_img");
  292.         $lead_custom_file $request->get("lead_custom_file");
  293.         try {
  294.             $content $contentHelper->getLandingPageBySlug($slug);
  295.             if(!empty($content->getContentMetaByKey("lp_recipients"))) {
  296.                 $recipients explode(","$content->getContentMetaByKey("lp_recipients")->getMetavalue());
  297.             }
  298.             else {
  299.                 $recipients = array();
  300.             }
  301.             $thankyou $content->getContentMetaValueByKey("lp_thankyou");
  302.             $titles = array();
  303.             $lead_info = [];
  304.             if($firstname) {$lead_info["First Name"] = $firstname;}
  305.             if($lastname) {$lead_info["Last Name"] = $lastname;}
  306.             if($company) {$lead_info["Company"] = $company;}
  307.             if($phone) {$lead_info["Phone Number"] = $phone;}
  308.             if($email) {$lead_info["Email Address"] = $email;}
  309.             if($address1) {$lead_info["Address Line 1"] = $address1;}
  310.             if($address2) {$lead_info["Address Line 2"] = $address2;}
  311.             if($city) {$lead_info["City"] = $city;}
  312.             if($state) {$lead_info["State / Region"] = $state;}
  313.             if($zip) {$lead_info["Zip Code"] = $zip;}
  314.             if($contractor_type) {$lead_info["Contractor Type"] = $contractor_type;}
  315.             //special form fields
  316.             $special_fields = [];
  317.             if($collar_size) {
  318.                 $lead_info["Collar Size"] = $collar_size;
  319.                 $special_fields["collar_size"] = $collar_size;
  320.             }
  321.             if($years_in_business) {
  322.                 $lead_info["Years in Business"] = $years_in_business;
  323.                 $special_fields["years_in_business"] = $years_in_business;
  324.             }
  325.             if($num_field_crew) {
  326.                 $lead_info["Approximate Number of Field Crew"] = $num_field_crew;
  327.                 $special_fields["num_field_crew"] = $num_field_crew;
  328.             }
  329.             if($annual_revenue) {
  330.                 $lead_info["Annual Revenue"] = $annual_revenue;
  331.                 $special_fields["annual_revenue"] = $annual_revenue;
  332.             }
  333.             if($self_perform_trade) {
  334.                 $lead_info["Self-Perform Trade"] = $self_perform_trade;
  335.                 $special_fields["self_perform_trade"] = $self_perform_trade;
  336.             }
  337.             
  338.             
  339.             if($lead_custom) {
  340.                 foreach($lead_custom as $key => $value) {
  341.                     if(is_array($value)) {
  342.                         //Set the checkbox value to all selected values
  343.                         $lead_custom[$key] = implode(", "$value);
  344.                     }
  345.                     
  346.                     if(!$email && strtolower($key) == "email") {
  347.                         $email $value;
  348.                     }
  349.                 }
  350.                 $lead_info array_merge($lead_info$lead_custom);
  351.             }
  352.             
  353.             if($email && !filter_var($emailFILTER_VALIDATE_EMAIL)) {
  354.                 $this->addFlash("danger""The provided e-mail address is invalid.");
  355.                 return new RedirectResponse($request->headers->get('referer'));
  356.             }
  357.             
  358.             
  359.             //Handle images separately, so they won't be emailed the ids
  360.             $lead_custom_files = [];
  361.             $uploaded_media = [];
  362.             if($lead_custom_img) {
  363.                 
  364.                 foreach($lead_custom_img as $key => $value) {
  365.                     
  366.                     if ($request->files->get("img_".$key)) { //image field
  367.                         
  368.                         $uploaded_image $request->files->get("img_".$key);
  369.                         
  370.                         $mime $uploaded_image->getMimeType();
  371.                         if(!in_array($mime, ["image/jpg""image/jpeg""image/png""image/gif""application/pdf"])) {
  372.                             $this->addFlash("danger""Only PNG, JPG, GIF, and PDF file types are allowed.");
  373.                             return new RedirectResponse($request->headers->get('referer'));
  374.                         }
  375.                         /*if(!in_array($mime, ["image/jpg", "image/jpeg", "image/png", "image/gif"])) {
  376.                             $this->addFlash("danger", "Only PNG, JPG, and GIF file types are allowed.");
  377.                             return new RedirectResponse($request->headers->get('referer'));
  378.                         }*/
  379.                         
  380.                         $media = new Media();
  381.                         $media->setTitle(pathinfo($uploaded_image->getClientOriginalName(), PATHINFO_FILENAME));
  382.                         $media->setData($uploaded_image);
  383.                         $media->setDescription("Lead image - LP " $content->getId() . " - " $key);
  384.                         $media->setName($uploaded_image->getClientOriginalName());
  385.                         
  386.                         $entityManager $this->getDoctrine()->getManager();
  387.                         $entityManager->persist($media);
  388.                         $entityManager->flush();
  389.                         
  390.                         $lead_custom_files[$value] = $media->getId();
  391.                         unset($lead_custom_img[$key]);
  392.                         //$lead_custom_img[$value] = $lead["img_".$key];
  393.                         
  394.                         $uploaded_media[] = $media;
  395.                     }
  396.                 }
  397.                 
  398.                 //$lead_info = array_merge($lead_info, $lead_custom_img);
  399.                 //$lead_custom = array_merge($lead_custom, $lead_custom_images);
  400.             }
  401.             
  402.             if($lead_custom_file) {
  403.                 
  404.                 foreach($lead_custom_file as $key => $value) {
  405.                     
  406.                     if ($request->files->get("file_".$key)) {
  407.                         
  408.                         $uploaded_file $request->files->get("file_".$key);
  409.                         
  410.                         $media = new Media();
  411.                         $media->setTitle(pathinfo($uploaded_file->getClientOriginalName(), PATHINFO_FILENAME));
  412.                         $media->setData($uploaded_file);
  413.                         $media->setDescription("Lead file - LP " $content->getId() . " - " $key);
  414.                         $media->setName($uploaded_file->getClientOriginalName());
  415.                         
  416.                         $entityManager $this->getDoctrine()->getManager();
  417.                         $entityManager->persist($media);
  418.                         $entityManager->flush();
  419.                         
  420.                         $lead_custom_files[$value] = $media->getId();
  421.                         unset($lead_custom_file[$key]);
  422.                         
  423.                         $uploaded_media[] = $media;
  424.                     }
  425.                 }
  426.                 
  427.                 //$lead_info = array_merge($lead_info, $lead_custom_file);
  428.                 //$lead_custom = array_merge($lead_custom, $lead_custom_images);
  429.             }
  430.             /*
  431.             //Uncomment if we want leads from landing pages to go to Customer emails instead of just lp_recipients
  432.             $customers = $content->getCustomers();
  433.             for ($i = 0; $i < count($customers); $i++) {
  434.                 $customer = $customers[$i];
  435.                 $title = $customer->getTitle();
  436.                 $titles[] = $title;
  437.                 if (filter_var($customer->getEmail(), FILTER_VALIDATE_EMAIL)) {
  438.                   $recipient = $customer->getEmail();
  439.                   if (in_array($recipient, $recipients)) {
  440.                       unset($recipients[array_search($recipient, $recipients)]);
  441.                   }
  442.                   $emailHelper->sendEmail(
  443.                         [$recipient],
  444.                         "Lead Received - {$title}",
  445.                         [
  446.                             ["p" => "Lead received for {$title}"],
  447.                             ["table" => [
  448.                                 "Firstname" => $firstname,
  449.                                 "Lastname" => $lastname,
  450.                                 "Company" => $company,
  451.                                 "Phone Number" => $phone,
  452.                                 "Email Address" => $email,
  453.                                 "Contractor Type" => $contractor_type,
  454.                                 //"Recipient (customer)" => $recipient,
  455.                             ]],
  456.                         ]
  457.                     );
  458.                 }
  459.             }
  460.             */
  461.             $titles implode(","$titles);
  462.             //using the landing page title instead of customer names:
  463.             $title $content->getTitle();
  464.             if(!empty($recipients)) {
  465.                 
  466.                 $user_text "";
  467.                 if ($this->user) {
  468.                     $user_text " from user <strong>" $this->user->getUsername() . "</strong>";
  469.                 }
  470.                 
  471.                 $emailHelper->sendEmail(
  472.                      $recipients,
  473.                     "Lead Received - {$title}",
  474.                     [
  475.                         ["p" => "Lead received for <strong>{$title}</strong>{$user_text}"],
  476.                         ["table" => $lead_info ],
  477.                     ], [], """"""$uploaded_media //if images
  478.                 );
  479.             }
  480.             
  481.             // store the lead
  482.             $leadHelper->saveLead($lead$content$request$lead_custom$lead_custom_files);
  483.             /*
  484.             $lead = new Lead();
  485.             $lead->setFirstname($firstname);
  486.             $lead->setLastname($lastname);
  487.             $lead->setCompany($company);
  488.             $lead->setPhoneBusiness($phone);
  489.             $lead->setEmail($email);
  490.             $lead->setTypeBusiness($contractor_type);
  491.             $lead->setAddress1($address1);
  492.             $lead->setAddress2($address2);
  493.             $lead->setCity($city);
  494.             $lead->setState($state);
  495.             $lead->setZip($zip);
  496.             //special form fields
  497.             if(!empty($special_fields)) {
  498.                 $lead->setComments(json_encode($special_fields));
  499.             }
  500.             $lead->setIpAddress($request->getClientIp());
  501.             $lead->setRefUrl($request->headers->get("referer"));
  502.             $lead->setUserAgent($request->headers->get("User-Agent"));
  503.             $lead->setContent($content);
  504.             $em = $this->getDoctrine()->getManager();
  505.             $em->persist($lead);
  506.             $em->flush();
  507.             */
  508.             /*
  509.             $redirect = substr($thankyou, strpos($thankyou, '?gaplg=') + 7);
  510.             if(!$redirect) {
  511.                 $redirect = substr($thankyou, strpos($thankyou, '.com/') + 5);
  512.             }
  513.             */
  514.             //return $this->redirect("/" . strstr($thankyou, "?gaplg="));
  515.             //2-28-2019 changing to just a straight redirect
  516.             //$redirect = substr($thankyou, strpos($thankyou, '.com/') + 5);
  517.             //return $this->redirect("/" . $redirect);
  518.             
  519.             $thankyouUrl "https://rooferscoffeeshop.com";
  520.             
  521.             $env $container->getParameter('kernel.environment');
  522.             if($env == "dev") {
  523.                 $thankyouUrl "https://staging.rooferscoffeeshop.com";
  524.             }
  525.             
  526.             if($thankyou) {
  527.                 $thankyouUrl $thankyou;
  528.             }
  529.             else {
  530.                 $children $content->getChildren();
  531.                 if(!$children->isEmpty()) {
  532.                     $thanks $children->first();
  533.                     if($thanks->getContentFull()) {
  534.                         if($env == "dev") {
  535.                             $thankyouUrl "https://staging.rooferscoffeeshop.com" $thanks->getURL();
  536.                         }
  537.                         else {
  538.                             $thankyouUrl "https://rooferscoffeeshop.com" $thanks->getURL();
  539.                         }
  540.                     }
  541.                 }
  542.             }
  543.             
  544.             
  545.             if($content->getLPEmailSend()) {
  546.                 if($email && filter_var($emailFILTER_VALIDATE_EMAIL)) {
  547.                     
  548.                     $defaultBody "Thank you for your interest in: {$title}.";
  549.                     //Send custom email to the user (if valid email was entered)
  550.                     $emailHelper->sendEmail(
  551.                          $email,
  552.                         "Form Completed - {$title}",
  553.                         [
  554.                             ["p" => $content->getLPEmailContents() ? $content->getLPEmailContentsImgFix() : $defaultBody ],
  555.                             //["p" => "Email Recipient: {$email}" ],
  556.                             /*["a" => [
  557.                                 "href" => "{$thankyouUrl}",
  558.                                 "text" => $content->getLPEmailButtonText() ? $content->getLPEmailButtonText() : "Click Here to view."]
  559.                             ],*/
  560.                         ],
  561.                         [],
  562.                         "",
  563.                         ""
  564.                     );
  565.                     
  566.                 }
  567.                 // Need to also handle $lead_custom
  568.             }
  569.             
  570.             
  571.             //Redirect to the thank you page
  572.             if($thankyouUrl) {
  573.                 return $this->redirect($thankyouUrl);
  574.             }
  575.             else {
  576.                 return $this->redirect("/");
  577.             }
  578.             
  579.             
  580.             //return $this->redirect($thankyou ? $thankyou : "/");
  581.             /*
  582.             return $this->defaultRender("content/landing-page.html.twig", [
  583.                 "page" => $content,
  584.                 "message" => [
  585.                     "type" => "success",
  586.                     "text" => "Form submitted successfully.",
  587.                 ]
  588.             ]);
  589.             */
  590.         }
  591.         catch (ResourceNotFoundException $e) {
  592.         }
  593.         }
  594.         else {
  595.             //Flash messages not showing up on landing pages, need to update this
  596.             //$this->addFlash("danger", "The reCAPTCHA was invalid. Please try again.");
  597.             return new RedirectResponse($request->headers->get('referer'));
  598.         }
  599.     }
  600.     /**
  601.      * @Route("/rcs/{slug}", name="landing-page")
  602.      *
  603.      */
  604.     public function showLandingPage (
  605.         ContentHelper $contentHelper,
  606.         Request $request,
  607.         $slug
  608.     ) {
  609.         
  610.         try {
  611.             
  612.             //Handle the unique RCS'ers questions page.
  613.             if($slug == "rcsers-questions") {
  614.                 if (!$this->user) {
  615.                     $msg = [
  616.                         "type" => "warning",
  617.                         "text" => "Please sign in to view this page.",
  618.                     ];
  619.                     return $this->redirectToRoute("sign-in", [
  620.                         "message" => $msg
  621.                     ]);
  622.                 }
  623.             }
  624.             
  625.             
  626.             
  627.             $page $contentHelper->getLandingPageBySlug($slug);
  628.             return $this->defaultRender("content/landing-page.html.twig", [
  629.                 "page" => $page,
  630.                 "meta" => [
  631.                     "title" => $page->getTitle(),
  632.                 ],
  633.             ]);
  634.         }
  635.         
  636.         catch (ResourceNotFoundException $e) {
  637.             
  638.         }
  639.         return $this->defaultRender("errors/404.html.twig", [
  640.         
  641.         ]);
  642.     }
  643.     
  644.     
  645.     
  646.     
  647.     
  648.     //TODO
  649.     /**
  650.      * @Route("/download-report", name="download_report")
  651.     **/
  652.     public function downloadReportAction(
  653.         Request $request,
  654.         ContentHelper $helper
  655.     ){
  656.         //$filename = "Analytics RoofersCoffeeShop.com - CertainTeed Corporation - March-2019.xlsx";
  657.         $filename $request->request->get("filename");
  658.         $response = new BinaryFileResponse("../var/reports/{$filename}");
  659.         //$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT,'pdf.pdf');
  660.         
  661.         $pos strrpos($filename'/');
  662.         $filename $pos === false $filename substr($filename$pos 1);
  663.         
  664.         $disposition $response->headers->makeDisposition(
  665.             ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  666.             $filename
  667.         );
  668.         $response->headers->set('Content-Disposition'$disposition);
  669.         return $response;
  670.     }
  671.     
  672.     //TODO
  673.     /**
  674.      * @Route("/admin_mega_menu"),
  675.      * name="admin_mega_menu"
  676.      */
  677.     public function menuBuilderDashboard(
  678.         Request $request,
  679.         ContentHelper $contentHelper
  680.     ){
  681.         $access false;
  682.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  683.             $user $this->getUser();
  684.             if($user) {
  685.                 if($user->isSuperAdmin()) {
  686.                     $access true;
  687.                 }
  688.             }
  689.         }
  690.         return $this->defaultRender("admin/mega_menu_builder.html.twig", [
  691.             "access" => $access,
  692.             "meta" => [
  693.                 "title" => "Mega Menu Builder",
  694.                 "root" => "/",
  695.             ]
  696.         ]);
  697.     }
  698.     
  699.     
  700.     //TODO: new controllers for this and tax report
  701.     /**
  702.      * @Route(
  703.      *      "/admin-dashboard",
  704.      *      name="admin_dashboard"
  705.      * )
  706.      */
  707.     public function loadingAdminDashboard(
  708.         Request $request,
  709.         ContentHelper $contentHelper
  710.     ) {
  711.         set_time_limit(180);
  712.         $access false;
  713.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  714.             $user $this->getUser();
  715.             if($user) {
  716.                 if($user->isAdmin()) {
  717.                     $access true;
  718.                 }
  719.             }
  720.         }
  721.         return $this->defaultRender("content/loading-admin-dashboard.html.twig", [
  722.             "access" => $access,
  723.             "meta" => [
  724.                 "title" => "Admin Dashboard",
  725.                 "root" => "/admin-directory",
  726.             ]
  727.         ]);
  728.     }
  729.     
  730.     /**
  731.     * @Route("/ajax/admin-dashboard")
  732.     */
  733.     public function adminDashboardEmbed(
  734.         Request $request,
  735.         ContentHelper $contentHelper,
  736.         CustomerHelper $customerHelper,
  737.         CategoryHelper $categoryHelper,
  738.         MediaHelper $mediaHelper,
  739.         MenuHelper $menuHelper,
  740.         Environment $twig
  741.     ) {
  742.         try {
  743.             set_time_limit(180);
  744.             
  745.             
  746.             $entityManager $this->getDoctrine()->getManager();
  747.             
  748.             $currentYear date("Y");
  749.             $month date("n");
  750.             
  751.             
  752.             
  753.             if($request->request->has("year")) {
  754.                 $year $request->request->get("year");
  755.                 if($year $currentYear) {
  756.                     $month 12;
  757.                 }
  758.             }
  759.             else {
  760.                 $year $currentYear;
  761.                 //Only show up for this year if after January
  762.                 if($month == 1) {
  763.                     $year $currentYear 1;
  764.                     //$currentYear = $year;
  765.                     $month 12;
  766.                 }
  767.             }
  768.             
  769.             $customers $customerHelper->getActiveCustomers();
  770.             $rows = [];
  771.             $keys = [];
  772.             foreach($customers as $customer) {
  773.                 $c_info = [];
  774.                 $c_info["Customer"] = htmlspecialchars_decode($customer->getTitle());
  775.                 
  776.                 $c_info["Partner Level"] = htmlspecialchars_decode($customer->getCustomerLevelString());
  777.                 $c_info["Directory Type"] = htmlspecialchars_decode($customer->getCustomerTypeString());
  778.                 
  779.                 for($m 1$m <= $month$m++) {
  780.                     
  781.                     $dateObj   \DateTime::createFromFormat('!m'$m);
  782.                     $monthName $dateObj->format('M');
  783.                     if($year == $currentYear && $month == $m) {
  784.                         //don't want the current month; only months with complete data
  785.                         break;
  786.                         //$monthName = "(partial) ".$monthName;
  787.                     }
  788.                     
  789.                     $startDate date("Y-m-d"strtotime($year."-".$m."-"."01"));
  790.                     $startDate = new \DateTime($startDate);
  791.                     $endDate date("Y-m-t"strtotime($year."-".$m."-"."01"));
  792.                     $endDate = new \DateTime($endDate." 23:59:59");
  793.                     
  794.                     $monthly_impressions $customer->getMonthlyImpressions($year$m);
  795.                     $monthly_clicks $customer->getMonthlyClicks($year$m);
  796.                     $monthly_views $customer->getMonthlyViews($year$m);
  797.                     if($monthly_impressions !== false && $monthly_clicks !== false && $monthly_views !== false) {
  798.                         $c_info[$monthName " Total Impressions"] = $monthly_impressions;
  799.                         $c_info[$monthName " Total Page Views"] = $monthly_views;
  800.                         $c_info[$monthName " Total Clicks"] = $monthly_clicks;
  801.                     }
  802.                     else {
  803.                         $links $contentHelper->countContentLinkClicks($customer$startDate$endDate);
  804.                         $total_link_clicks 0;
  805.                         foreach($links as $key => $value) {
  806.                             $total_link_clicks += $links[$key]["count"] ? $links[$key]["count"] : 0;
  807.                         }
  808.                         
  809.                         $total_content_impressions $contentHelper->countCustomerContentImpressionsAggregatedCorrected($customer$startDate$endDate);
  810.                         $total_content_views $contentHelper->countCustomerContentClicksAggregated($customer$startDate$endDate);
  811.                         $total_ad_impressions $mediaHelper->countTotalAdImpressionsAggregated($customer$startDate$endDate);
  812.                         $total_ad_clicks $mediaHelper->countTotalAdClicksAggregated($customer$startDate$endDate);
  813.                         
  814.                         $monthly_impressions $total_content_impressions $total_ad_impressions;
  815.                         $monthly_clicks $total_link_clicks $total_ad_clicks;
  816.                         $monthly_views $total_content_views;
  817.                         $c_info[$monthName " Total Impressions"] = $monthly_impressions;
  818.                         $c_info[$monthName " Total Page Views"] = $monthly_views;
  819.                         $c_info[$monthName " Total Clicks"] = $monthly_clicks;
  820.                         $customer->setMonthlyImpressions($year$m$monthly_impressions);
  821.                         $customer->setMonthlyClicks($year$m$monthly_clicks);
  822.                         $customer->setMonthlyViews($year$m$monthly_views);
  823.                         $entityManager->persist($customer);
  824.                         $entityManager->flush();
  825.                     }
  826.                 }
  827.                 $rows[] = $c_info;
  828.                 $keys array_keys($c_info);
  829.             }
  830.             //Export / Spreadsheet
  831.             $spreadsheet = new Spreadsheet();
  832.             $spreadsheet = new Spreadsheet();
  833.             $sheet $spreadsheet->getActiveSheet();
  834.             $sheet_title "RCS Customer Monthly Review ".date_format(new \DateTime(), 'M Y');
  835.             $colVal "A";
  836.             $rowNum 1;
  837.             foreach($keys as $key) {
  838.                 $sheet->setCellValue("{$colVal}{$rowNum}"$key);
  839.                 $colVal++;
  840.             }
  841.             $colVal--;
  842.             
  843.             $sheet->getStyle("A{$rowNum}:{$colVal}{$rowNum}")->getFill()
  844.                 ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  845.                 ->getStartColor()->setARGB('FFDDDDDD');
  846.             $rowNum++;
  847.             foreach($rows as $row) {
  848.                 $colVal "A";
  849.                 foreach($row as $key => $value) {
  850.                     $sheet->setCellValue("{$colVal}{$rowNum}"$value);
  851.                     $colVal++;
  852.                 }
  853.                 $rowNum++;
  854.             }
  855.             $colVal--;
  856.             foreach(range("A",$sheet->getHighestColumn()) as $columnID) {
  857.                 $sheet->getColumnDimension($columnID)
  858.                     ->setAutoSize(true);
  859.             }
  860.             //Finish and save
  861.             $writer = new Xlsx($spreadsheet);
  862.             $clean_title preg_replace('/[^A-Za-z0-9 \-_]/'''$sheet_title); // Removes special chars.
  863.             $filename "{$clean_title}.xlsx";
  864.             $writer->save("../var/reports/{$filename}");
  865.             // End Export / Spreadsheet
  866.             $tmpl $twig->load("content/admin-dashboard-embed.html.twig");
  867.             $html $tmpl->render(
  868.             [
  869.                 "rows" => $rows,
  870.                 "keys" => $keys,
  871.                 "filename" => $filename,
  872.                 "currentYear" => $currentYear,
  873.                 "year" => $year,
  874.             ]);
  875.             return new JsonResponse($html);
  876.         } catch (\Exception $e) {
  877.             return new JsonResponse("<br><h4 style='text-align: center; color: #A7252B;'>There was an error while generating your report.</h4>");
  878.             //throw $e;
  879.         }
  880.     }
  881.     
  882.     /**
  883.      * @Route(
  884.      *      "/tax-report",
  885.      *      name="tax_report"
  886.      * )
  887.      */
  888.     public function loadingTaxReport(
  889.         Request $request,
  890.         ContentHelper $contentHelper
  891.     ) {
  892.         
  893.         set_time_limit(180);
  894.         
  895.         $access false;
  896.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  897.             $user $this->getUser();
  898.             if($user) {
  899.                 if($user->isAdmin()) {
  900.                     $access true;
  901.                 }
  902.             }
  903.         }
  904.         
  905.         return $this->defaultRender("content/loading-tax-report.html.twig", [
  906.             "access" => $access,
  907.             "meta" => [
  908.                 "title" => "Tax Report",
  909.                 "root" => "/tax-report",
  910.             ]
  911.         ]);
  912.     }
  913.     
  914.     /**
  915.     * @Route("/ajax/tax-report")
  916.     */
  917.     public function taxReportEmbed(
  918.         Request $request,
  919.         OrderHelper $orderHelper,
  920.         Environment $twig
  921.     ) {
  922.         try {
  923.             
  924.             set_time_limit(180);
  925.             
  926.             /*
  927.             //Update to allow year selection
  928.             if($request->request->has("year") && $request->request->get("year")) {
  929.                 $year = date("Y", strtotime($request->request->get("year")));
  930.             }
  931.             
  932.             $year = 2020;
  933.             */
  934.             
  935.             
  936.             $year date("Y");
  937.             $month date("n");
  938.             
  939.             $rows = [];
  940.             
  941.             for($m 1$m <= $month$m++) {
  942.                 $startDate date("Y-m-d"strtotime($year."-".$m."-"."01"));
  943.                 $startDate = new \DateTime($startDate);
  944.                 $endDate date("Y-m-t"strtotime($year."-".$m."-"."01"));
  945.                 $endDate = new \DateTime($endDate." 23:59:59");
  946.                 
  947.                 
  948.                 $sales $orderHelper->sumPurchaseTotalsByType(Product::PRODUCT_TYPE_SHOP$startDate$endDate);
  949.                 $tax $orderHelper->sumTaxes($startDate$endDate);
  950.                 
  951.                 $dateObj   \DateTime::createFromFormat('!m'$m);
  952.                 $monthName $dateObj->format('F');
  953.                 if($month == $m) {
  954.                     $monthName $monthName." (partial)";
  955.                 }
  956.                 
  957.                 //$rows[$monthName] = $results;
  958.                 $rows[] = [
  959.                     "month" => $monthName,
  960.                     "sales" => '$' number_format($sales 1002),
  961.                     "tax" => '$' number_format($tax 1002),
  962.                 ];
  963.                 
  964.                 
  965.             }
  966.             
  967.             
  968.             $tmpl $twig->load("content/tax-report-embed.html.twig");
  969.             $html $tmpl->render(
  970.             [
  971.                 "year" => $year,
  972.                 "rows" => $rows,
  973.             ]);
  974.             
  975.             return new JsonResponse($html);
  976.             
  977.             } catch (\Exception $e) {
  978.                 //return new JsonResponse("<br><h4 style='text-align: center; color: #A7252B;'>There was an error while generating your report.</h4>");
  979.                 throw $e;
  980.             }
  981.     }
  982.     
  983.     
  984.     
  985.     //TODO: Keeping forum routes here for now. See if we can modify and use master functions.
  986.     /**
  987.      * @Route("/forum", name="forums")
  988.      */
  989.     public function forums(
  990.         Request $request,
  991.         ContentHelper $helper,
  992.         $slug ""
  993.     ) {
  994.         $forums = array();
  995.         foreach($helper->getContentByType(Content::FORUM) as $forum) {
  996.             $counts $helper->countTopicsPostsByForum($forum->getSlug());
  997.             $topics $helper->getTopicsByForum($forum11);
  998.             $topic "";
  999.             foreach($topics as $t) {
  1000.                 $topic $t;
  1001.             }
  1002.             $featured $forum->getFeatured();
  1003.             $forums[] = [
  1004.                 "forum" => $forum,
  1005.                 "num_topics" => $counts["num_topics"],
  1006.                 "num_posts" => $counts["num_posts"],
  1007.                 "recent_topic" => $topic,
  1008.                 "featured" => $featured,
  1009.             ];
  1010.         }
  1011.         $num_topics = array();
  1012.         foreach($forums as $key => $row) {
  1013.             $num_topics[$key] = $row["num_topics"] + ($row["featured"] * 100000);
  1014.         }
  1015.         array_multisort($num_topicsSORT_DESC$forums);
  1016.         
  1017.         $chatAccess false;
  1018.         $ssoParams "";
  1019.         $moderator 0;
  1020.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  1021.             $user $this->getUser();
  1022.             if($user) {
  1023.                 $chatAccess true;
  1024.                 if($user->isAdmin() /*|| $user->inCompany($customer)*/) {
  1025.                     $moderator 1;
  1026.                 }
  1027.                 
  1028.                 // Chatroll Single Sign-On (SSO) Parameters
  1029.                 $uid $user->getId();                  // Current user id
  1030.                 $uname $user->getUsername();          // Current user name
  1031.                 $ulink '';                               // Current user profile URL (leave blank for none)
  1032.                 $upic '';                             // Current user profile picture URL (leave blank for none)
  1033.                 /*if($user->getMedia()) {
  1034.                     $upic = $user->getMedia()->getAbsoluteURL();
  1035.                 }*/
  1036.                 $ismod $moderator;                     // Is current user a moderator?
  1037.                 $sig md5($uid $uname $ismod 'b7ofqalwup2rtbkg');
  1038.                 $ssoParams '&uid=' $uid "&uname=" urlencode($uname) . "&ulink=" urlencode($ulink) . "&upic=" urlencode($upic) . "&ismod=" $ismod "&sig=" $sig;
  1039.                 
  1040.             }
  1041.         }
  1042.         
  1043.         return $this->defaultRender("content/forums-page.html.twig", [
  1044.             "meta" => [
  1045.                 "title" => "Forums Archive",
  1046.                 "breadcrumbs" => [
  1047.                     [
  1048.                         "title" => "Our Forums",
  1049.                         "href" => "/forum",
  1050.                     ]
  1051.                 ]
  1052.             ],
  1053.             "forums" => $forums,
  1054.             "chatAccess" => $chatAccess,
  1055.             "ssoParams" => $ssoParams,
  1056.         ]);
  1057.     }
  1058.     /**
  1059.      * @Route("/forum/topic/{slug}/edit", name="forum_topic_edit")
  1060.      */
  1061.      public function forumTopicEdit(
  1062.         Request $request,
  1063.         ContentHelper $helper,
  1064.         $slug ""
  1065.      ) {
  1066.         $topic $helper->getTopicBySlug($slug);
  1067.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  1068.             $user $this->getUser();
  1069.             if($user) {
  1070.                 //$unrestricted = $user->getUserMetaValueByKey("rich_editing");
  1071.                 if($user->isAdmin()) {
  1072.                     //fully edit topic
  1073.                     if ($request->request->has("content")) {
  1074.                         $topic->setTitle($request->request->get("title"));
  1075.                         $topic->setContentFull($request->request->get("content"));
  1076.                         $topic->setPrnt($helper->getContentById($request->request->get("forum")));
  1077.                         $topic->setStatus($request->request->get("status"));
  1078.                         $em $this->getDoctrine()->getManager();
  1079.                         $em->persist($topic);
  1080.                         $em->flush();
  1081.                         $this->addFlash("success""Topic has been updated.");
  1082.                         return $this->redirectToRoute("forum_topic", ["slug" => $topic->getSlug(), "page" => "1"]);
  1083.                     }
  1084.                     return $this->defaultRender("content/tmpl/forum-topic-edit.html.twig", [
  1085.                         "content" => $topic,
  1086.                         //"unrestricted" => isset($unrestricted) ? $unrestricted : "",
  1087.                         "unrestricted" => true,
  1088.                         "forums" => $helper->getContentByType(Content::FORUM),
  1089.                         "admin" => true,
  1090.                     ]);
  1091.                 }
  1092.                 elseif($topic->getAuthor() == $user) {
  1093.                     //just allow them to edit the content and title
  1094.                     if ($request->request->has("content")) {
  1095.                         $topic->setTitle($request->request->get("title"));
  1096.                         $topic->setContentFull($request->request->get("content"));
  1097.                         $em $this->getDoctrine()->getManager();
  1098.                         $em->persist($topic);
  1099.                         $em->flush();
  1100.                         $this->addFlash("success""Topic has been updated.");
  1101.                         return $this->redirectToRoute("forum_topic", ["slug" => $topic->getSlug(), "page" => "1"]);
  1102.                     }
  1103.                     return $this->defaultRender("content/tmpl/forum-topic-edit.html.twig", [
  1104.                         "content" => $topic,
  1105.                         //"unrestricted" => isset($unrestricted) ? $unrestricted : "",
  1106.                         "unrestricted" => true,
  1107.                         "admin" => false,
  1108.                     ]);
  1109.                 }
  1110.             }
  1111.         }
  1112.         return $this->redirectToRoute("forum_topic", ["slug" => $topic->getSlug(), "page" => "1"]);
  1113.      }
  1114.      /**
  1115.      * @Route("/forum/topic/{slug}/delete", name="forum_topic_delete")
  1116.      */
  1117.      public function forumTopicDelete(
  1118.         Request $request,
  1119.         ContentHelper $helper,
  1120.         $slug ""
  1121.      ) {
  1122.         $topic $helper->getTopicBySlug($slug);
  1123.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  1124.             $user $this->getUser();
  1125.             if($user) {
  1126.                 if($user->isAdmin()) {
  1127.                     $topic->setStatus(Content::STATUS_INACTIVE);
  1128.                     $em $this->getDoctrine()->getManager();
  1129.                     $em->persist($topic);
  1130.                     $em->flush();
  1131.                     foreach($topic->getChildren() as $child) {
  1132.                         $child->setStatus(Content::STATUS_INACTIVE);
  1133.                         $em->persist($child);
  1134.                         $em->flush();
  1135.                     }
  1136.                     $this->addFlash("success""Topic has been deleted.");
  1137.                     return $this->redirectToRoute("forum", ["slug" => $topic->getPrnt()->getSlug(), "page" => "1"]);
  1138.                 }
  1139.             }
  1140.         }
  1141.      }
  1142.      /**
  1143.      * @Route("/forum/topic/{slug}/unsubscribe/{userid}", name="forum_topic_unsubscribe")
  1144.      */
  1145.      public function forumTopicUnsubscribe(
  1146.         Request $request,
  1147.         ContentHelper $helper,
  1148.         UserHelper $userhelper,
  1149.         $slug "",
  1150.         $userid ""
  1151.      ) {
  1152.         $topic $helper->getTopicBySlug($slug);
  1153.         $user $userhelper->getUserById($userid);
  1154.         $entityManager $this->getDoctrine()->getManager();
  1155.         if($topic->getAuthor() == $user) {
  1156.             $topic->setContentmetum("_notify_of_replies""0");
  1157.             $entityManager->persist($topic);
  1158.             $entityManager->flush();
  1159.         }
  1160.         foreach($topic->getActiveChildren() as $reply) {
  1161.             if($reply->getAuthor() == $user) {
  1162.                 $reply->setContentmetum("_notify_of_replies""0");
  1163.                 $entityManager->persist($reply);
  1164.                 $entityManager->flush();
  1165.             }
  1166.         }
  1167.         $this->addFlash("success""You will no longer receive email notifications about the \"{$topic->getTitle()}\" forum topic.");
  1168.         return $this->redirectToRoute("forum", ["slug" => $topic->getPrnt()->getSlug(), "page" => "1"]);
  1169.     }
  1170.     /**
  1171.     * @Route("/forum/topic/{slug}/spam", name="forum_topic_spam")
  1172.     */
  1173.     public function forumTopicSpam(
  1174.         Request $request,
  1175.         ContentHelper $helper,
  1176.         $slug ""
  1177.     ) {
  1178.         $topic $helper->getTopicBySlug($slug);
  1179.         
  1180.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  1181.             $user $this->getUser();
  1182.             if($user) {
  1183.                 if($user->isAdmin()) {
  1184.                     $forumUser $topic->getAuthor();
  1185.                     if($forumUser) {
  1186.                         $forumUser->markAsSpam();
  1187.                         
  1188.                         $em $this->getDoctrine()->getManager();
  1189.                         $em->persist($forumUser);
  1190.                         $em->flush();
  1191.                         /* //Should we do this?
  1192.                         foreach($topic->getChildren() as $child) {
  1193.                             $child->setStatus(Content::STATUS_INACTIVE);
  1194.                             $em->persist($child);
  1195.                             $em->flush();
  1196.                         }
  1197.                         */
  1198.                         $this->addFlash("success""User has been marked as spam.");
  1199.                     }
  1200.                     else {
  1201.                         $this->addFlash("warning""There was a problem marking this user as spam.");
  1202.                     }
  1203.                     
  1204.                     return $this->redirectToRoute("forum", ["slug" => $topic->getPrnt()->getSlug(), "page" => "1"]);
  1205.                 }
  1206.             }
  1207.         }
  1208.     }
  1209.     /**
  1210.      * @Route("/forum/topic/{slug}/{page}", name="forum_topic")
  1211.      */
  1212.     public function forumTopic(
  1213.         Request $request,
  1214.         ContentHelper $helper,
  1215.         EmailHelper $emailHelper,
  1216.         $slug "",
  1217.         $page 1
  1218.     ) {
  1219.         $topic $helper->getTopicBySlug($slug);
  1220.         $limit ContentHelper::FORUM_LIMIT;
  1221.         $forum $topic->getPrnt();
  1222.         
  1223.         if($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  1224.             
  1225.             /*
  1226.             if(isset($unrestricted) && $unrestricted) {
  1227.                 $form = $this->createForm(ContentAdminType::class, $content);
  1228.             }
  1229.             else {
  1230.                 $form = $this->createForm(ContentType::class, $content);
  1231.             }
  1232.             $form->handleRequest($request);
  1233.             */
  1234.             
  1235.             //if ($form->isSubmitted() && $form->isValid()) {
  1236.             if ($request->request->has("reply-content")) {
  1237.                 $content = new Content();
  1238.                 
  1239.                 $entityManager $this->getDoctrine()->getManager();
  1240.                 $site $entityManager
  1241.                     ->getRepository(Site::class)
  1242.                     ->findOneBy([
  1243.                         "id" => $this->site_code
  1244.                     ]);
  1245.                 $content->addSite($site);
  1246.                     
  1247.                 $content->setType(Content::FORUM_REPLY);
  1248.                 $content->setPrnt($topic);
  1249.                 $content->setPermission(1);
  1250.                 
  1251.                 $user $this->getUser();
  1252.                 if($user) {
  1253.                     $content->setAuthor($user);
  1254.                     //$unrestricted = $user->getUserMetaValueByKey("rich_editing");
  1255.                 }
  1256.                 if($emailHelper->checkInvisibleCaptcha($request->get("g-recaptcha-response"))) {
  1257.                     $notify = new ContentMeta();
  1258.                     $notify->setMetakey("_notify_of_replies");
  1259.                     $request->request->has("notify") ? $notify->setMetavalue(1) : $notify->setMetavalue(0);
  1260.                     $content->addContentmetum($notify);
  1261.                     $content_full $request->request->get("reply-content");
  1262.                     if(!$this->user->isAdmin()) {
  1263.                         $content_full preg_replace('/<a[^>]+>([^<]+)<\/a>/i','\1',$content_full);
  1264.                     }
  1265.                     $content->setContentFull($content_full);
  1266.                     
  1267.                     if($helper->isSpam($request->request->get("reply-content"))) {
  1268.                         $content->setStatus(Content::STATUS_IN_REVIEW);
  1269.                     }
  1270.                     else {
  1271.                         $content->setStatus(Content::STATUS_ACTIVE);
  1272.                     }
  1273.                     
  1274.                     $entityManager $this->getDoctrine()->getManager();
  1275.                     $entityManager->persist($content);
  1276.                     $entityManager->flush();
  1277.                     
  1278.                     $this->addFlash("success""Your reply has been added.");
  1279.                     
  1280.                     if($topic->getContentMetaValueByKey("_notify_of_replies")) {
  1281.                         //forum_email
  1282.                         $pooled $emailHelper->sendEmail($topic->getAuthor()->getEmail(), "New Reply to one of your Forum Topics", [
  1283.                             ["p" => "Hello {$topic->getAuthor()},"],
  1284.                             ["p" => "{$content->getAuthor()} has replied to your forum topic <a href=\"{$topic->getFullURL()}\">\"{$topic->getTitle()}\"</a> with the following reply:"],
  1285.                             ["p" => "{$content->getContentFull()}"],
  1286.                             //["a" => ["href" => "staging.rooferscoffeeshop.com/forum/topic/{$topic->getSlug()}/unsubscribe/{$topic->getAuthor()->getId()}", "text" => "Click Here to stop receiving these notifications"]],
  1287.                             ["a" => ["href" => "rooferscoffeeshop.com/forum/topic/{$topic->getSlug()}/unsubscribe/{$topic->getAuthor()->getId()}""text" => "Click Here to stop receiving these notifications"]],
  1288.                         ], [], """lauren@rooferscoffeeshop.com");
  1289.                     }
  1290.                     
  1291.                     $notify_users = array();
  1292.                     
  1293.                     foreach($topic->getActiveChildren() as $reply) {
  1294.                         if($reply != $content) {
  1295.                             if($reply->getContentMetaValueByKey("_notify_of_replies") && !in_array($reply->getAuthor(), $notify_users)
  1296.                                 && $reply->getAuthor() != $topic->getAuthor() && $reply->getAuthor() != $content->getAuthor()) {
  1297.                                 $notify_users[] = $reply->getAuthor();
  1298.                             }
  1299.                         }
  1300.                     }
  1301.                     
  1302.                     foreach($notify_users as $notify_user) {
  1303.                         //forum_email
  1304.                         $pooled $emailHelper->sendEmail($notify_user->getEmail(), "New Reply to one of your Forum Topics", [
  1305.                             ["p" => "Hello {$notify_user},"],
  1306.                             ["p" => "{$content->getAuthor()} has replied to the forum topic <a href=\"{$topic->getFullURL()}\">\"{$topic->getTitle()}\"</a> with the following reply:"],
  1307.                             ["p" => "{$content->getContentFull()}"],
  1308.                             //["a" => ["href" => "staging.rooferscoffeeshop.com/forum/topic/{$topic->getSlug()}/unsubscribe/{$notify_user->getId()}", "text" => "Click Here to stop receiving these notifications"]],
  1309.                             ["a" => ["href" => "rooferscoffeeshop.com/forum/topic/{$topic->getSlug()}/unsubscribe/{$notify_user->getId()}""text" => "Click Here to stop receiving these notifications"]],
  1310.                         ], [], """lauren@rooferscoffeeshop.com");
  1311.                     }
  1312.                     
  1313.                     $session $request->getSession();
  1314.                     $route $session->get("this_route");
  1315.                     
  1316.                     // return $this->redirectToRoute('task_success');
  1317.                     return $this->redirect($route["path"]);
  1318.                 }
  1319.                 else {
  1320.                     //failed the recaptcha check
  1321.                     $session $request->getSession();
  1322.                     $route $session->get("this_route");
  1323.                     return $this->redirect($route["path"]);
  1324.                 }
  1325.             }
  1326.         }
  1327.         
  1328.         $count $helper->countActiveChildren($topic);
  1329.         
  1330.         return $this->contentMembersOnlyCheck($forum) ??
  1331.         $this->defaultRender("content/content.html.twig", [
  1332.             "meta" => [
  1333.                 "title" => $topic->getTitle(),
  1334.                 "breadcrumbs" => [
  1335.                     [
  1336.                         "title" => "Our Forums",
  1337.                         "href" => "/forum",
  1338.                     ],
  1339.                     [
  1340.                         "title" => $forum->getTitle(),
  1341.                         "href" => "/forum/{$forum->getSlug()}",
  1342.                     ],
  1343.                     [
  1344.                         "title" => $topic->getTitle(),
  1345.                         "href" => "/forum/topic/{$topic->getSlug()}",
  1346.                     ],
  1347.                 ],
  1348.             ],
  1349.             "content" => $topic,
  1350.             "replies" => $helper->getPaginatedChildren($topic$limit$pagefalse),
  1351.             "limit" => $limit,
  1352.             "pagenum" => $page,
  1353.             "totalcount" => $count,
  1354.             "totalpages" => ceil($count $limit),
  1355.             "baseurl" => $this->generateUrl('forum_topic', ['slug' => $slug]),
  1356.             //"form" => $form->createView(),
  1357.             //"unrestricted" => isset($unrestricted) ? $unrestricted : "",
  1358.             //let everyone be unrestricted (Vickie wants everyone to be able to post images for now)
  1359.             "unrestricted" => true,
  1360.         ]);
  1361.     }
  1362.     
  1363.     /**
  1364.      * @Route("/forum/reply/{id}/{action}", name="forum_reply")
  1365.      */
  1366.     public function forumReply(
  1367.         Request $request,
  1368.         ContentHelper $helper,
  1369.         $id "",
  1370.         $action ""
  1371.     ) {
  1372.         $reply $helper->getContentById($id);
  1373.         
  1374.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  1375.             $user $this->getUser();
  1376.             if($user) {
  1377.                 if($reply->getAuthor() == $user || $user->isAdmin()) {
  1378.                     //access granted
  1379.                     //$unrestricted = $user->getUserMetaValueByKey("rich_editing");
  1380.                     
  1381.                     if($action == "edit") {
  1382.                         
  1383.                         if ($request->request->has("reply-content")) {
  1384.                             $content_full $request->request->get("reply-content");
  1385.                             if(!$this->user->isAdmin()) {
  1386.                                 $content_full preg_replace('/<a[^>]+>([^<]+)<\/a>/i','\1',$content_full);
  1387.                             }
  1388.                             $reply->setContentFull($content_full);
  1389.                             $em $this->getDoctrine()->getManager();
  1390.                             $em->persist($reply);
  1391.                             $em->flush();
  1392.                             $this->addFlash("success""Reply has been updated.");
  1393.                             return $this->redirectToRoute("forum_topic", ["slug" => $reply->getPrnt()->getSlug(), "page" => "1"]);
  1394.                         }
  1395.                         
  1396.                         return $this->defaultRender("content/tmpl/forum-reply-edit.html.twig", [
  1397.                             "content" => $reply,
  1398.                             //"unrestricted" => isset($unrestricted) ? $unrestricted : "",
  1399.                             "unrestricted" => true,
  1400.                         ]);
  1401.                     }
  1402.                     elseif ($action == "delete"){
  1403.                         $reply->setStatus(Content::STATUS_INACTIVE);
  1404.                         
  1405.                         $em $this->getDoctrine()->getManager();
  1406.                         $em->persist($reply);
  1407.                         $em->flush();
  1408.                         
  1409.                         $this->addFlash("success""Reply has been deleted.");
  1410.                         return $this->redirectToRoute("forum_topic", ["slug" => $reply->getPrnt()->getSlug(), "page" => "1"]);
  1411.                     }
  1412.                     elseif ($action == "spam"){
  1413.                         $user $reply->getAuthor();
  1414.                         if($user) {
  1415.                             $user->markAsSpam();
  1416.                             $em $this->getDoctrine()->getManager();
  1417.                             $em->persist($user);
  1418.                             $em->flush();
  1419.                             $this->addFlash("success""User has been marked as spam.");
  1420.                         }
  1421.                         else {
  1422.                             $this->addFlash("warning""There was a problem marking this user as spam.");
  1423.                         }
  1424.                         
  1425.                         return $this->redirectToRoute("forum_topic", ["slug" => $reply->getPrnt()->getSlug(), "page" => "1"]);
  1426.                     }
  1427.                 }
  1428.             }
  1429.         }
  1430.         
  1431.         // no action was taken, return to the single reply view
  1432.          return $this->defaultRender("content/tmpl/forum-reply-single.html.twig", [ // or content/content
  1433.             "content" => $reply,
  1434.         ]);
  1435.         
  1436.     }
  1437.     /**
  1438.      * @Route(
  1439.      *        "/forum/search/{search}/{page}",
  1440.      *      defaults={"search"="", "page"=1},
  1441.      *        name="forum_search",
  1442.      *      methods={"GET"}
  1443.      * )
  1444.      */
  1445.     public function forumSearch(
  1446.         Request $request,
  1447.         ContentHelper $helper,
  1448.         $search "",
  1449.         $page 1
  1450.     ) {
  1451.         $limit ContentHelper::FORUM_LIMIT;
  1452.         $count $helper->countForumSearchResults($search);
  1453.         
  1454.         return $this->defaultRender("content/forum-search.html.twig", [
  1455.             "meta" => [
  1456.                 "title" => "Forum Search Results",
  1457.             ],
  1458.             "results" => $helper->getForumSearchResults($search$limit$page),
  1459.             "search" => $search,
  1460.             "limit" => $limit,
  1461.             "pagenum" => $page,
  1462.             "totalcount" => $count,
  1463.             "totalpages" => ceil($count $limit),
  1464.             "baseurl" => $this->generateUrl('forum_search', ['search' => $search]),
  1465.         ]);
  1466.     }
  1467.     /**
  1468.      * @Route("/forum/{slug}/{page}", name="forum")
  1469.      */
  1470.     public function forum(
  1471.         Request $request,
  1472.         ContentHelper $helper,
  1473.         UserHelper $userhelper,
  1474.         EmailHelper $emailHelper,
  1475.         $slug "",
  1476.         $page 1
  1477.     ) {
  1478.         $forum $helper->getForumBySlug($slug);
  1479.         $limit ContentHelper::FORUM_LIMIT;
  1480.         
  1481.         //if ($form->isSubmitted() && $form->isValid()) {
  1482.         if ($request->request->has("content") && $request->request->has("title")) {
  1483.             
  1484.             if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  1485.                 $content = new Content();
  1486.                 
  1487.                 $entityManager $this->getDoctrine()->getManager();
  1488.                 $site $entityManager
  1489.                     ->getRepository(Site::class)
  1490.                     ->findOneBy([
  1491.                         "id" => $this->site_code
  1492.                     ]);
  1493.                 $content->addSite($site);
  1494.                 
  1495.                 $content->setType(Content::FORUM_TOPIC);
  1496.                 $content->setPrnt($forum);
  1497.                 $content->setPermission(1);
  1498.                 $user $this->getUser();
  1499.                 if($user) {
  1500.                     $content->setAuthor($user);
  1501.                     //$unrestricted = $user->getUserMetaValueByKey("rich_editing");
  1502.                 }
  1503.                 
  1504.                 if($emailHelper->checkInvisibleCaptcha($request->get("g-recaptcha-response"))) {
  1505.                     $notify = new ContentMeta();
  1506.                     $notify->setMetakey("_notify_of_replies");
  1507.                     $request->request->has("notify") ? $notify->setMetavalue(1) : $notify->setMetavalue(0);
  1508.                     $content->addContentmetum($notify);
  1509.                     $content->setTitle($request->request->get("title"));
  1510.                     $content->setContentFull($request->request->get("content"));
  1511.                     $content->setSlug($helper->getUniqueSlug($content->getTitle(), ""Content::SITE_RCS));
  1512.                     if($helper->isSpam($request->request->get("title")) || $helper->isSpam($request->request->get("content"))) {
  1513.                         //Just preventing posting entirely for now instead of marking as in review since there is so much Korean spam.
  1514.                         //$content->setStatus(Content::STATUS_IN_REVIEW);
  1515.                         //$this->addFlash("warning", "Your new topic has triggered our automatic spam filter. If you believe this is an error, please contact a site administrator.");
  1516.                         $session $request->getSession();
  1517.                         $route $session->get("this_route");
  1518.                         return $this->redirect($route["path"]);
  1519.                     }
  1520.                     else {
  1521.                         //Not spam
  1522.                         $content->setStatus(Content::STATUS_ACTIVE);
  1523.                         
  1524.                         $entityManager $this->getDoctrine()->getManager();
  1525.                         $entityManager->persist($content);
  1526.                         $entityManager->flush();
  1527.                         
  1528.                         $this->addFlash("success""Your new topic \"{$content->getTitle()}\" has been added.");
  1529.                         
  1530.                         $emailSent false;
  1531.                         //If it's a members only topic, notify members who are set to receive notifications
  1532.                         if($forum->getMembersOnly()) {
  1533.                             $notify_users $userhelper->getMembersToNotify("member_notification_forum");
  1534.                             if($notify_users) {
  1535.                                 foreach($notify_users as $notify_user) {
  1536.                                     //forum_email
  1537.                                     $pooled $emailHelper->sendEmail($notify_user->getEmail(), "New Members Only Forum Topic", [
  1538.                                         ["p" => "Hello {$notify_user},"],
  1539.                                         ["p" => "{$content->getAuthor()} has posted a new topic to the R-Club forum: \"<a href='{$content->getFullURL()}'>{$content->getTitle()}</a>\"."],
  1540.                                         ["p" => "{$content->getContentFull()}"],
  1541.                                         ["a" => ["href" => "rooferscoffeeshop.com/account""text" => "Update your membership notification setting here to stop receiving these notifications"]],
  1542.                                     ], [], """lauren@rooferscoffeeshop.com");
  1543.                                     $emailSent true;
  1544.                                 }
  1545.                             }
  1546.                         }
  1547.                         if(!$emailSent) {
  1548.                             //forum_email
  1549.                             $pooled $emailHelper->sendEmail(SiteConfig::CONFIGS[$this->site_code]["email_group"], "New Forum Topic", [
  1550.                                 //["p" => "Hello {$notify_user},"],
  1551.                                 ["p" => "{$content->getAuthor()} has posted a new topic to the forum: \"<a href='{$content->getFullURL($this->site_code)}'>{$content->getTitle()}</a>\"."],
  1552.                                 ["p" => "{$content->getContentFull()}"],
  1553.                             ]);
  1554.                         }
  1555.                         
  1556.                     }
  1557.                     
  1558.                 }
  1559.                 else {
  1560.                     //failed the recaptcha check
  1561.                     $session $request->getSession();
  1562.                     $route $session->get("this_route");
  1563.                     return $this->redirect($route["path"]);
  1564.                 }
  1565.             }
  1566.             
  1567.         }
  1568.         $count $helper->countActiveChildren($forum);
  1569.         
  1570.         return $this->contentMembersOnlyCheck($forum) ??
  1571.         $this->defaultRender("content/content.html.twig", [
  1572.             "meta" => [
  1573.                 "title" => $forum->getTitle(),
  1574.                 "breadcrumbs" => [
  1575.                     [
  1576.                         "title" => "Our Forums",
  1577.                         "href" => "/forum",
  1578.                     ],
  1579.                     [
  1580.                         "title" => $forum->getTitle(),
  1581.                         "href" => "/forum/{$forum->getSlug()}",
  1582.                     ],
  1583.                 ],
  1584.             ],
  1585.             "content" => $forum,
  1586.             //"topics" => $helper->getPaginatedChildren($forum, $limit, $page),
  1587.             "topics" => $helper->getTopicsByForum($forum$limit$page),
  1588.             "limit" => $limit,
  1589.             "pagenum" => $page,
  1590.             "totalcount" => $count,
  1591.             "totalpages" => ceil($count $limit),
  1592.             "baseurl" => $this->generateUrl('forum', ['slug' => $slug]),
  1593.             //"form" => $form->createView(),
  1594.             //"unrestricted" => isset($unrestricted) ? $unrestricted : "", //if the user can post unrestricted HTML content
  1595.             "unrestricted" => true,
  1596.         ]);
  1597.     }
  1598.     
  1599.     
  1600.     //TODO: Keep here, or move to directory specific controller?
  1601.     /**
  1602.      * @Route("/be-part-of-the-directory/{part}/{purchaseItem}",
  1603.      *      name="directory-join-post",
  1604.      *      defaults={"part": 1, "purchaseItem": ""},
  1605.      *      methods={"POST"}
  1606.      * )
  1607.      */
  1608.     public function directoryJoinPost (
  1609.         Request $request,
  1610.         CategoryHelper $categoryHelper,
  1611.         ContentHelper $contentHelper,
  1612.         StorageInterface $storeInterface,
  1613.         UserHelper $userHelper,
  1614.         EmailHelper $emailHelper,
  1615.         $part 1,
  1616.         $purchaseItem ""
  1617.     ) {
  1618.         
  1619.         $manager $this->getDoctrine()->getManager();
  1620.         $session $request->getSession();
  1621.         $user $this->user;
  1622.         
  1623.         // try to retrieve the current purchase item or create it
  1624.         $purchase null;
  1625.         if ($user) {
  1626.            $purchase $this->user->getActivePurchase();
  1627.         }
  1628.         
  1629.         if (!$purchase) {
  1630.             $purchase $session->get("purchase_id");
  1631.             if ($purchase) {
  1632.                 $purchase $manager->getRepository(Purchase::class)
  1633.                    ->findOneBy([
  1634.                        "id" => $purchase,
  1635.                    ]);
  1636.                 if ($purchase) {
  1637.                     // make sure purchase is valid ...
  1638.                     if ($purchase->getStatus() != Purchase::STATUS_ACTIVE) {
  1639.                         $session->remove("purchase_id");
  1640.                         $purchase null;
  1641.                     }
  1642.                 }
  1643.             }
  1644.         }
  1645.         
  1646.         // if still no purchase ... we need to make one
  1647.         if (!$purchase) {
  1648.             $purchase = new Purchase();
  1649.         }
  1650.         
  1651.         $action $request->get("action");
  1652.         if ($action) {
  1653.             if ($action == "edit_listing") {
  1654.                return $this->redirectToRoute("directory-join", [
  1655.                    "part" => 2,
  1656.                    "purchaseItem" => $purchaseItem,
  1657.                ]);
  1658.             }
  1659.             
  1660.             else if ($action == "discard") {
  1661.                 $step 1;
  1662.                 // should only remove if actively attached to the user object ... aka - in cart
  1663.                 $purchase $user->getActivePurchase();
  1664.                 if ($purchase) {
  1665.                     $item $purchase->getCurrentItem();
  1666.                     $purchase->removeItem($item);
  1667.                     $manager->persist($purchase);
  1668.                     $manager->flush();
  1669.                     $this->addFlash("success""The item has successfully been removed from your <a href='/cart'>cart</a>.");
  1670.                     $session->remove("directory_type");
  1671.                     $session->remove("directory_product");
  1672.                 }
  1673.                 /*
  1674.                 $purchase = $user->getActivePurchase();
  1675.                 if ($purchase) {
  1676.                     $item = $purchase->getCurrentItem();
  1677.                     $purchase->removeItem($item);
  1678.                     $manager->persist($purchase);
  1679.                     $manager->flush();
  1680.                     $this->addFlash("success", "The item has successfully been removed from your <a href='/cart'>cart</a>.");
  1681.                 }
  1682.                 */
  1683.                 
  1684.                 return $this->redirectToRoute("directory-join", [
  1685.                     "part" => 1
  1686.                 ]);
  1687.                 
  1688.             }
  1689.             
  1690.             else if ($action == "add_to_cart") {
  1691.                 if ($user) {
  1692.                     
  1693.                     $purchase $user->getActivePurchase();
  1694.                     
  1695.                     // purchase should be available here...
  1696.                     if ($purchase) {
  1697.                         $item $purchase->getCurrentItem();
  1698.                         if ($item) {
  1699.                             $item->setStatus(PurchaseItem::STATUS_ACTIVE); //< not to be confused with STATUS_CURRENT
  1700.                             $manager->persist($purchase);
  1701.                             $manager->flush();
  1702.                             $session->remove("directory_product");
  1703.                             $session->remove("directory_type");
  1704.                             $session->remove("purchase_id");
  1705.                             $this->addFlash("success""The item has successfully been added to your <a href='/cart'>cart</a>.");
  1706.                         }
  1707.                     }
  1708.                     
  1709.                     return $this->redirectToRoute("cart", [
  1710.                     
  1711.                     ]);
  1712.                 } else {
  1713.                     $this->addFlash("warning""Please sign-in.");
  1714.                     return $this->redirectToRoute("directory-join", [
  1715.                        "part" => "1",
  1716.                     ]);
  1717.                 }
  1718.             }
  1719.             
  1720.         }
  1721.         
  1722.         else if ($part == 1) {
  1723.             
  1724.             // grab the type and subscription and store in session
  1725.             $directory_type $request->get("directory_type");
  1726.             $directory_product $request->get("directory_product");
  1727.             $session->set("directory_type"$directory_type);
  1728.             $session->set("directory_product"$directory_product);
  1729.             $part 2;
  1730.             
  1731.             $product $manager->getRepository(Product::class)
  1732.                 ->findOneBy([
  1733.                     "id" => $directory_product,
  1734.                 ]);
  1735.                 
  1736.             if ($purchaseItem) {
  1737.                 
  1738.                 $item $manager->getRepository(PurchaseItem::class)
  1739.                     ->findOneBy([
  1740.                         "id" => $purchaseItem
  1741.                     ]);
  1742.                     
  1743.                 // make sure the current user can update the record
  1744.                 if ($item) {
  1745.                     $tempPurchase $item->getPurchase();
  1746.                     if ($this->user &&
  1747.                         $product && (
  1748.                         $tempPurchase->getUser()->getId() == $this->user->getId()
  1749.                     )) {
  1750.                         $item->setProduct($product);
  1751.                         $manager->persist($tempPurchase);
  1752.                         $manager->flush();
  1753.                         // update the directory type too...
  1754.                         $content $item->getContent();
  1755.                         $types $content->getSecondaryCategoriesByTaxonomy("directory-type");
  1756.                         for ($i 0$i count($types); $i++) {
  1757.                             $content->removeSecondaryCategory($types[$i]);
  1758.                         }
  1759.                         // now set the correct types
  1760.                         if ($content) {
  1761.                             for ($i 0$i count($directory_type); $i++) {
  1762.                                 //$cat = $categoryHelper->getCategoryById($directory_type[$i]);
  1763.                                 //$content->addSecondaryCategory($cat);
  1764.                             }
  1765.                         }
  1766.                         
  1767.                         $manager->persist($content);
  1768.                         $manager->flush();
  1769.                     }
  1770.                 }
  1771.             }
  1772.             
  1773.             else if ($purchase) {
  1774.                 $item $purchase->getCurrentItem();
  1775.                 
  1776.                 if ($item && $product) {
  1777.                     
  1778.                     if ($item->getType() != PurchaseItem::TYPE_DIRECTORY) {
  1779.                         // if it's not a classified purchase ... create a new one...
  1780.                         
  1781.                         // replace the current item
  1782.                         $item->setStatus(PurchaseItem::STATUS_ACTIVE);
  1783.                         $item = new PurchaseItem();
  1784.                         $item->setType(PurchaseItem::TYPE_DIRECTORY);
  1785.                         $purchase->setCurrentItem($item);
  1786.                     }
  1787.                     
  1788.                     $item->setProduct($product);
  1789.                     $manager->persist($purchase);
  1790.                     $manager->flush();
  1791.                     
  1792.                     // update the directory type too...
  1793.                     $content $item->getContent();
  1794.                     
  1795.                     if ($content) {
  1796.                         $types $content->getSecondaryCategoriesByTaxonomy("directory-type");
  1797.                         for ($i 0$i count($types); $i++) {
  1798.                             $content->removeSecondaryCategory($types[$i]);
  1799.                         }
  1800.                         // now set the correct types
  1801.                         if ($content) {
  1802.                             for ($i 0$i count($directory_type); $i++) {
  1803.                                 //$cat = $categoryHelper->getCategoryById($directory_type[$i]);
  1804.                                 //$content->addSecondaryCategory($cat);
  1805.                             }
  1806.                         }
  1807.                         
  1808.                         $manager->persist($content);
  1809.                         $manager->flush();
  1810.                     }
  1811.                 }
  1812.             }
  1813.             
  1814.         }
  1815.         
  1816.         else if ($part == 2) {
  1817.             
  1818.             // check that we have a user
  1819.             
  1820.             if (!$user) {
  1821.                 
  1822.                 $rUser $request->get("account");
  1823.                 if ($rUser) {
  1824.                     
  1825.                     // see about creating user
  1826.                     $resp $userHelper->signUp(
  1827.                         $rUser["firstname"],
  1828.                         $rUser["lastname"],
  1829.                         $rUser["username"],
  1830.                         $rUser["email"],
  1831.                         $rUser["password1"],
  1832.                         $rUser["password2"]
  1833.                     );
  1834.                     
  1835.                     // add the message
  1836.                     $this->addFlash($resp["message"]["type"], $resp["message"]["text"]);
  1837.                     
  1838.                     // was there an error creating the user?
  1839.                     if (!$resp["status"]) {
  1840.                         $session->getFlashBag()->add("directory"$request->get("directory"));
  1841.                         return $this->redirectToRoute("directory-join", [
  1842.                             "part" => 2,
  1843.                         ]);
  1844.                     }
  1845.                     
  1846.                     // set user to the newly created user
  1847.                     $user $resp["user"];
  1848.                     
  1849.                 }
  1850.                 
  1851.                 else {
  1852.                     // error - we need a user object
  1853.                     $session->getFlashBag()->add("directory"$request->get("directory"));
  1854.                     $this->addFlash("warning""You must either sign into the system or provide details to create an account.");
  1855.                     return $this->redirectToRoute("directory-join", [
  1856.                         "part" => 2,
  1857.                     ]);
  1858.                 }
  1859.                 
  1860.                 
  1861.                 return $this->redirectToRoute("directory-join", [
  1862.                     "part" => 2,
  1863.                 ]);
  1864.                 
  1865.             }
  1866.             
  1867.             // build out the directory object now
  1868.             
  1869.             $rDirectory $request->get("directory");
  1870.             
  1871.             $item null;
  1872.             
  1873.             if ($purchaseItem) {
  1874.                 $item $manager->getRepository(PurchaseItem::class)
  1875.                     ->findOneBy([
  1876.                         "id" => $purchaseItem
  1877.                     ]);
  1878.                     
  1879.                 // does the item belong to the current user?
  1880.                 if (!$item || $item->getPurchase()->getUser()->getId() == $user->getId()) {
  1881.                     if ($item) {
  1882.                         // set purchase to the correct object
  1883.                         $purchase $item->getPurchase();
  1884.                     }
  1885.                 } else {
  1886.                     $item null;
  1887.                     $purchaseItem null;
  1888.                 }
  1889.             }
  1890.             
  1891.             $purchase->setUser($user);
  1892.             
  1893.             if (!$item) {
  1894.                 $item $purchase->getCurrentItem();
  1895.                 // if no purchase item exists - create it
  1896.                 if (!$item) {
  1897.                     $item = new PurchaseItem();
  1898.                     $item->setStatus(PurchaseItem::STATUS_CURRENT);
  1899.                     $item->setType(PurchaseItem::TYPE_DIRECTORY);
  1900.                 }
  1901.             }
  1902.             
  1903.             $product_id $session->get("directory_product");
  1904.             $product $item->getProduct();
  1905.             
  1906.             if (!$product || ($product->getId() != $product_id && !$purchaseItem)) {
  1907.                 $product $manager->getRepository(Product::class)
  1908.                     ->findOneBy([
  1909.                        "status" => 1,
  1910.                        "id" => $product_id
  1911.                     ]);
  1912.             }
  1913.             
  1914.             if (!$product) {
  1915.                 $this->addFlash("warning""Please select a product.");
  1916.                 return $this->redirectToRoute("directory-join", [
  1917.                     "part" => 1
  1918.                 ]);
  1919.             }
  1920.             
  1921.             $item->setProduct($product);
  1922.             
  1923.             // set as current if not editing another record
  1924.             if (!$purchaseItem) {
  1925.                 $purchase->setCurrentItem($item);
  1926.             }
  1927.             
  1928.             $content $item->getContent();
  1929.             if (!$content) {
  1930.                 $content = new Content();
  1931.                 
  1932.                 $entityManager $this->getDoctrine()->getManager();
  1933.                 $site $entityManager
  1934.                     ->getRepository(Site::class)
  1935.                     ->findOneBy([
  1936.                         "id" => $this->site_code
  1937.                     ]);
  1938.                 $content->addSite($site);
  1939.                 
  1940.                 $content->setStatus(Content::STATUS_INACTIVE);
  1941.                 $customer = new Customer();
  1942.                 //$customer->setStatus(0);
  1943.                 $customer->setStatus(1);
  1944.                 $customer->setDirectoryContent($content);
  1945.             }
  1946.             else {
  1947.                 $customer $content->getDirectory();
  1948.             }
  1949.             
  1950.             // build the directory per the provided data
  1951.             $content->setAuthor($user);
  1952.             $content->setType(Content::DIRECTORY);
  1953.             $content->setTitle($rDirectory["title"]);
  1954.             $customer->setTitle($rDirectory["title"]);
  1955.             
  1956.             if (!$content->getSlug()) {
  1957.                $content->setSlug($contentHelper->getUniqueSlug($rDirectory["title"], ""Content::SITE_RCS));
  1958.             }
  1959.             $content->setContentFull($rDirectory["description"]);
  1960.             $content->setFeatured(0);
  1961.             
  1962.             // location
  1963.             /*
  1964.             $meta = $content->getContentMetaByKey("_job_location");
  1965.             if (!$meta) {
  1966.                 $meta = new ContentMeta();
  1967.                 $meta->setMetaKey("_job_location");
  1968.                 $meta->setMetaValue($rDirectory["location"]);
  1969.                 $content->addContentMetum($meta);
  1970.             } else {
  1971.                 $meta->setMetaValue($rDirectory["location"]);
  1972.             }
  1973.             */
  1974.             
  1975.             // country
  1976.             $meta $content->getContentMetaByKey("_job_country");
  1977.             if (!$meta) {
  1978.                 $meta = new ContentMeta();
  1979.                 $meta->setMetaKey("_job_country");
  1980.                 $meta->setMetaValue($rDirectory["country"]);
  1981.                 $content->addContentMetum($meta);
  1982.             } else {
  1983.                 $meta->setMetaValue($rDirectory["country"]);
  1984.             }
  1985.             
  1986.             $content->resetSecondaryCategories();
  1987.             
  1988.             // directory type(s)
  1989.             //print_r($rDirectory["type"]);
  1990.             $customer->setCustomerTypeArray($rDirectory["type"]);
  1991.             //for ($i = 0; $i < count($rDirectory["type"]); $i++) {
  1992.                 //$category = $categoryHelper->getCategoryById($rDirectory["type"][$i]);
  1993.                 //$content->addSecondaryCategory($category);
  1994.             //}
  1995.             
  1996.             // directory category(ies)
  1997.             for ($i 0$i count($rDirectory["category"]); $i++) {
  1998.                 $category $categoryHelper->getCategoryById($rDirectory["category"][$i]);
  1999.                 $content->addSecondaryCategory($category);
  2000.                 $customer->addCategory($category);
  2001.             }
  2002.             
  2003.             // company e-mail
  2004.             $customer->setEmail($rDirectory["contact_email"]);
  2005.             $meta $content->getContentMetaByKey("_company_email");
  2006.             if (!$meta) {
  2007.                 $meta = new ContentMeta();
  2008.                 $meta->setMetaKey("_company_email");
  2009.                 $meta->setMetaValue($rDirectory["contact_email"]);
  2010.                 $content->addContentMetum($meta);
  2011.             } else {
  2012.                 $meta->setMetaValue($rDirectory["contact_email"]);
  2013.             }
  2014.             
  2015.             // directory keywords
  2016.             $customer->setKeywords($rDirectory["keywords"]);
  2017.             $meta $content->getContentMetaByKey("_directory_keywords");
  2018.             if (!$meta) {
  2019.                 $meta = new ContentMeta();
  2020.                 $meta->setMetaKey("_directory_keywords");
  2021.                 $meta->setMetaValue($rDirectory["keywords"]);
  2022.                 $content->addContentMetum($meta);
  2023.             } else {
  2024.                 $meta->setMetaValue($rDirectory["keywords"]);
  2025.             }
  2026.             
  2027.             // distribution states / provinces (only for distributors / manufacturer reps)
  2028.             if(is_array($rDirectory["type"]) && (in_array("Distributors"$rDirectory["type"]) || in_array("Manufacturers Reps"$rDirectory["type"]) )) {
  2029.                 if(isset($rDirectory["dstates"])) {
  2030.                     $customer->setState($rDirectory["dstates"]);
  2031.                 }
  2032.             }
  2033.             
  2034.             // phone
  2035.             $customer->resetPhones();
  2036.             if($rDirectory["phone"]) {
  2037.                 $phone = new CustomerPhone();
  2038.                 $phone->setTitle("Main Phone");
  2039.                 $phone->setNumber($rDirectory["phone"]);
  2040.                 $customer->addPhone($phone);
  2041.             }
  2042.             
  2043.             // address
  2044.             $customer->resetAddresses();
  2045.             if($rDirectory["address1"]) {
  2046.                 $address = new CustomerAddress();
  2047.                 $address->setTitle("Main Address");
  2048.                 $address->setAddressLine1($rDirectory["address1"] ? $rDirectory["address1"] : "");
  2049.                 $address->setAddressLine2($rDirectory["address2"] ? $rDirectory["address2"] : "");
  2050.                 $address->setCity($rDirectory["city"] ? $rDirectory["city"] : "");
  2051.                 $address->setStateProvince($rDirectory["state"] ? $rDirectory["state"] : "");
  2052.                 $address->setPostalCode($rDirectory["zip"] ? $rDirectory["zip"] : "");
  2053.                 $address->setCountry($rDirectory["country"] ? $rDirectory["country"] : "");
  2054.                 $customer->addAddress($address);
  2055.             }
  2056.             
  2057.             $meta $content->getContentMetaByKey("_company_phone");
  2058.             if (!$meta) {
  2059.                 $meta = new ContentMeta();
  2060.                 $meta->setMetaKey("_company_phone");
  2061.                 $meta->setMetaValue($rDirectory["phone"]);
  2062.                 $content->addContentMetum($meta);
  2063.             } else {
  2064.                 $meta->setMetaValue($rDirectory["phone"]);
  2065.             }
  2066.             
  2067.             // company contact
  2068.             $meta $content->getContentMetaByKey("_company_contact");
  2069.             if (!$meta) {
  2070.                 $meta = new ContentMeta();
  2071.                 $meta->setMetaKey("_company_contact");
  2072.                 $meta->setMetaValue($rDirectory["contact"]);
  2073.                 $content->addContentMetum($meta);
  2074.             } else {
  2075.                 $meta->setMetaValue($rDirectory["contact"]);
  2076.             }
  2077.             
  2078.             // website
  2079.             $customer->setWebsite($rDirectory["website"]);
  2080.             $meta $content->getContentMetaByKey("_company_website");
  2081.             if (!$meta) {
  2082.                 $meta = new ContentMeta();
  2083.                 $meta->setMetaKey("_company_website");
  2084.                 $meta->setMetaValue($rDirectory["website"]);
  2085.                 $content->addContentMetum($meta);
  2086.             } else {
  2087.                 $meta->setMetaValue($rDirectory["website"]);
  2088.             }
  2089.             
  2090.             // twitter
  2091.             $customer->setTwitter($rDirectory["twitter"]);
  2092.             $meta $content->getContentMetaByKey("_company_twitter");
  2093.             if (!$meta) {
  2094.                 $meta = new ContentMeta();
  2095.                 $meta->setMetaKey("_company_twitter");
  2096.                 $meta->setMetaValue($rDirectory["twitter"]);
  2097.                 $content->addContentMetum($meta);
  2098.             } else {
  2099.                 $meta->setMetaValue($rDirectory["twitter"]);
  2100.             }
  2101.             
  2102.             // linkedin
  2103.             $customer->setLinkedin($rDirectory["linkedin"]);
  2104.             $meta $content->getContentMetaByKey("_company_linkedin");
  2105.             if (!$meta) {
  2106.                 $meta = new ContentMeta();
  2107.                 $meta->setMetaKey("_company_linkedin");
  2108.                 $meta->setMetaValue($rDirectory["linkedin"]);
  2109.                 $content->addContentMetum($meta);
  2110.             } else {
  2111.                 $meta->setMetaValue($rDirectory["linkedin"]);
  2112.             }
  2113.             
  2114.             // facebook
  2115.             $customer->setFacebook($rDirectory["facebook"]);
  2116.             $meta $content->getContentMetaByKey("_company_facebook");
  2117.             if (!$meta) {
  2118.                 $meta = new ContentMeta();
  2119.                 $meta->setMetaKey("_company_facebook");
  2120.                 $meta->setMetaValue($rDirectory["facebook"]);
  2121.                 $content->addContentMetum($meta);
  2122.             } else {
  2123.                 $meta->setMetaValue($rDirectory["facebook"]);
  2124.             }
  2125.             
  2126.             // instagram
  2127.             $customer->setInstagram($rDirectory["instagram"]);
  2128.             $meta $content->getContentMetaByKey("_company_instagram");
  2129.             if (!$meta) {
  2130.                 $meta = new ContentMeta();
  2131.                 $meta->setMetaKey("_company_instagram");
  2132.                 $meta->setMetaValue($rDirectory["instagram"]);
  2133.                 $content->addContentMetum($meta);
  2134.             } else {
  2135.                 $meta->setMetaValue($rDirectory["instagram"]);
  2136.             }
  2137.             
  2138.             // youtube
  2139.             $customer->setYoutube($rDirectory["youtube"]);
  2140.             $meta $content->getContentMetaByKey("_company_youtube");
  2141.             if (!$meta) {
  2142.                 $meta = new ContentMeta();
  2143.                 $meta->setMetaKey("_company_youtube");
  2144.                 $meta->setMetaValue($rDirectory["youtube"]);
  2145.                 $content->addContentMetum($meta);
  2146.             } else {
  2147.                 $meta->setMetaValue($rDirectory["youtube"]);
  2148.             }
  2149.             
  2150.             // check if uploaded a logo
  2151.             $file $request->files->get("directory");
  2152.             $file $file["logo"];
  2153.             
  2154.             if ($file) {
  2155.                 // store the logo in the content object
  2156.                 //$content->setFeaturedImageData($file);
  2157.                 
  2158.                 $mime $file->getMimeType();
  2159.                 if(!in_array($mime, ["image/jpg""image/jpeg""image/png""image/gif"])) {
  2160.                     $this->addFlash("danger""Only PNG, JPG, and GIF file types are allowed.");
  2161.                     return new RedirectResponse($request->headers->get('referer'));
  2162.                 }
  2163.                 
  2164.                 $media = new Media();
  2165.                 $media->setTitle($rDirectory["title"]. " Directory Logo");
  2166.                 $media->setData($file);
  2167.                 $media->setDescription("Directory Logo");
  2168.                 $media->setName($file->getClientOriginalName());
  2169.                 
  2170.                 $content->setMedia($media);
  2171.                 $customer->setMedia($media);
  2172.                 
  2173.             }
  2174.             else if (!empty($rDirectory["remove_logo"])) {
  2175.                 // remove the image data
  2176.                 // $storeInterface->remove($content, new PropertyMapping("featured_image_data", "featured_image"));
  2177.                 //$content->removeFeaturedImage();
  2178.                 
  2179.                 $content->setMedia(null);
  2180.                 $customer->setMedia(null);
  2181.             }
  2182.             
  2183.             // only set to in review when not already purchased ...
  2184.             if (!$content->getStatus()) {
  2185.                $content->setStatus(Content::STATUS_IN_REVIEW);
  2186.             }
  2187.             
  2188.             if (!$purchaseItem) {
  2189.                 $item $purchase->getCurrentItem();
  2190.                 $item->setContent($content);
  2191.                 $purchase->setCurrentItem($item);
  2192.             }
  2193.             
  2194.             else {
  2195.                 $this->addFlash("success""Listing Successfully Updated.");
  2196.                 //If someone edits an active listing, notify Vickie
  2197.                 if ($content->getStatus() == Content::STATUS_ACTIVE) {
  2198.                     $userText "";
  2199.                     if ($user) {
  2200.                         $username $user->getUsername();
  2201.                         $userText "by ".$username;
  2202.                     }
  2203.                     $emailHelper->sendEmail(
  2204.                         ["rcs@rooferscoffeeshop.com"],
  2205.                         "Directory Listing Updated - {$content->getTitle()}",
  2206.                         [
  2207.                             ["p" => "The directory listing '{$content->getTitle()}' has been updated {$userText}."],
  2208.                         ]
  2209.                     );
  2210.                     
  2211.                 }
  2212.             }
  2213.             
  2214.             if ($purchase->getStatus() != Purchase::STATUS_PROCESSED) {
  2215.                 if (count($purchase->getCoupons())) {
  2216.                     //Removing these on 1-13-21 for update that allows applying coupons through a link.
  2217.                     //$purchase->removeCoupons();
  2218.                     //$this->addFlash("warning", "The coupons that were assigned to this order have been reset since the order was adjusted. You may add them back to the order from the checkout screen.");
  2219.                 }
  2220.                 // update all totals
  2221.                 // $purchase->setTotal($purchase->getTotal());
  2222.                 $purchase->setTotal($purchase->calculateTotal());
  2223.             }
  2224.             
  2225.             $manager->persist($purchase);
  2226.             $manager->persist($content);
  2227.             $manager->persist($customer);
  2228.             $manager->flush();
  2229.             
  2230.             $purchase_id $purchase->getId();
  2231.             $session->set("purchase_id"$purchase_id);
  2232.             
  2233.             $part 3;
  2234.         }
  2235.         
  2236.         return $this->redirectToRoute("directory-join", [
  2237.             "part" => $part,
  2238.             "purchaseItem" => $purchaseItem,
  2239.         ]);
  2240.     }
  2241.     
  2242.     /**
  2243.      * @Route("/be-part-of-the-directory/{part}/{purchaseItem}",
  2244.      *      name="directory-join",
  2245.      *      defaults={"part": 1, "purchaseItem": ""}
  2246.      * )
  2247.      */
  2248.     public function directoryJoin (
  2249.         Request $request,
  2250.         CategoryHelper $categoryHelper,
  2251.         $part 1,
  2252.         $purchaseItem ""
  2253.     ) {
  2254.         
  2255.         $user $this->user;
  2256.         $manager $this->getDoctrine()->getManager();
  2257.         $products null;
  2258.         $purchase null;
  2259.         $session $request->getSession();
  2260.         $directoryTypes $categoryHelper->getCategoriesByTaxonomy("directory-type");
  2261.         $chosenDirectoryTypes $session->get("directory_type");
  2262.         $chosenDirectoryProduct $session->get("directory_product");
  2263.         $directoryCategories null;
  2264.         $chosenDirectoryCategories null;
  2265.         $directory null;
  2266.         $options null;
  2267.         // will contain the request data if submitted data has errors
  2268.         $tempItem null;
  2269.         $item null;
  2270.         // product id is only being grabbed from the session -
  2271.         // ======================= TRY TO GRAB THE PURCHASE OBJECT ===================== //
  2272.         // first grab the purchase item if provided in route and match to current user...
  2273.         if ($purchaseItem && $this->user) {
  2274.             $purchaseItem $manager->getRepository(PurchaseItem::class)
  2275.                 ->findOneBy([
  2276.                    "id" => $purchaseItem
  2277.                 ]);
  2278.             if ($purchaseItem) {
  2279.                 $temp $purchaseItem->getPurchase();
  2280.                 if ($temp->getUser()->getId() == $this->user->getId()) {
  2281.                     $purchase $temp;
  2282.                 } else {
  2283.                     $purchaseItem null;
  2284.                 }
  2285.             }
  2286.         }
  2287.         else if ($purchaseItem && !$this->user) {
  2288.             $this->addFlash("warning""Please log-in before editing your listing");
  2289.             return $this->redirectToRoute("directory-join", [
  2290.                "part" => 1,
  2291.                "purchaseItem" => "",
  2292.             ]);
  2293.         }
  2294.         else {
  2295.             $purchaseItem null;
  2296.         }
  2297.         // if purchase still doesn't exist - grab the purchase object if it exists
  2298.         if (!$purchase && $this->user) {
  2299.             $purchase $this->user->getActivePurchase();
  2300.         }
  2301.         // finally if purchase still doesn't exist - try to pull from the current session
  2302.         if (!$purchase) {
  2303.             $purchase $session->get("purchase_id");
  2304.             if ($purchase) {
  2305.                 $purchase $manager->getRepository(Purchase::class)
  2306.                    ->findOneBy([
  2307.                        "id" => $purchase,
  2308.                    ]);
  2309.             }
  2310.         }
  2311.         // ================== END OF TRY TO GRAB THE PURCHASE OBJECT ===================== //
  2312.         // if we have a purchaseItem at this point it is valid.
  2313.         if ($purchaseItem) {
  2314.             $item $purchaseItem;
  2315.         } else {
  2316.             $item $purchase && $purchase->getCurrentItem() ? $purchase->getCurrentItem() : null;
  2317.         }
  2318.         // make sure we're looking at a directory item
  2319.         if ($item && $item->getType() != PurchaseItem::TYPE_DIRECTORY) {
  2320.             if ($purchaseItem) {
  2321.                 // kick them over to the correct listing classified form
  2322.                 return $this->redirectToRoute("post-classified", [
  2323.                     "step" => 1,
  2324.                     "purchaseItem" => $purchaseItem,
  2325.                 ]);
  2326.             }
  2327.             else {
  2328.                 // adjust the "current" classified listing to be active instead
  2329.                 $item->setStatus(PurchaseItem::STATUS_ACTIVE);
  2330.                 $manager->persist($item);
  2331.                 $manager->flush();
  2332.                 // redirect to the main directory page again
  2333.                 return $this->redirectToRoute("directory-join");
  2334.             }
  2335.         }
  2336.         
  2337.         
  2338.         // try to find what product we are looking at
  2339.         if ($item && $item->getProduct()) {
  2340.             $chosenDirectoryProduct $item->getProduct();
  2341.         }
  2342.         if ($item && $item->getContent() && $item->getContent()->getSecondaryCategoriesByTaxonomy('directory-type')) {
  2343.             $cats $item->getContent()->getSecondaryCategoriesByTaxonomy('directory-type');
  2344.             $temp = [];
  2345.             for ($i 0$i count($cats); $i++) {
  2346.                 $temp[] = $cats[$i]->getId();
  2347.             }
  2348.             if (!empty($temp)) {
  2349.                 $chosenDirectoryTypes $temp;
  2350.             }
  2351.         }
  2352.         if (is_numeric($chosenDirectoryProduct)) {
  2353.             $chosenDirectoryProduct $manager->getRepository(Product::class)
  2354.                 ->findOneBy([
  2355.                     "status" => 1,
  2356.                     "id" => $chosenDirectoryProduct,
  2357.                 ]);
  2358.         }
  2359.         if ($part == 1) {
  2360.             if ($purchaseItem) {
  2361.                 $purchase $purchaseItem->getPurchase();
  2362.                 // don't allow changing product from completed purchases
  2363.                 if ($purchase->getStatus() != Purchase::STATUS_ACTIVE) {
  2364.                     return $this->redirectToRoute("directory-join", [
  2365.                         "part" => 1,
  2366.                     ]);
  2367.                 }
  2368.             }
  2369.             //products to display
  2370.             $options = [];
  2371.             $options[] = ["product" => $manager->getRepository(Product::class)->findOneBy(["slug" => "standard-directory-month"])];
  2372.             $options[] = ["product" => $manager->getRepository(Product::class)->findOneBy(["slug" => "standard-directory-year"])];
  2373.             if($user && $user->getMember() == User::MEMBERSHIP_COMPANY) {
  2374.                 $free_product_in_use false;
  2375.                 $product $manager->getRepository(Product::class)->findOneBy(["slug" => "free-standard-directory"]);
  2376.                 foreach($user->getPurchases() as $purchase) {
  2377.                     if($purchase->getStatus() == Purchase::STATUS_PROCESSED) {
  2378.                         foreach($purchase->getItems() as $pitem) {
  2379.                             if($product == $pitem->getProduct() && $pitem->getContent()) {
  2380.                                 if($pitem->getContent()->getStatus() != Content::STATUS_TRASH) {
  2381.                                     $free_product_in_use true;
  2382.                                 }
  2383.                             }
  2384.                         }
  2385.                     }
  2386.                 }
  2387.                 if($free_product_in_use) {
  2388.                     $options[] = [
  2389.                         "product" => $product,
  2390.                         "disabled" => true,
  2391.                         "class" => "disabled",
  2392.                         "description" => "Your free directory listing has already been redeemed. Manage your listing from your account page <a href='/account/content/4'>here</a>.",
  2393.                     ];
  2394.                 }
  2395.                 else {
  2396.                     $options[] = ["product" => $product"class" => "featured"];
  2397.                 }
  2398.             }
  2399.             $options[] = ["product" => $manager->getRepository(Product::class)->findOneBy(["slug" => "interactive-directory-month"])];
  2400.             if(!$user || $user->getMember() != User::MEMBERSHIP_PREMIUM) {
  2401.                 $options[] = [
  2402.                     "product" => $manager->getRepository(Product::class)->findOneBy(["slug" => "premium-directory-month"]),
  2403.                     "disabled" => true,
  2404.                     /*"link" => "rcs-club-sign-up",*/
  2405.                     "extra_info" => "Included in R-Club Membership. <a href='/rcs-club-sign-up'>Click here</a> to sign up.",
  2406.                 ];
  2407.             }
  2408.             else {
  2409.                 $free_product_in_use false;
  2410.                 $product $manager->getRepository(Product::class)->findOneBy(["slug" => "free-premium-directory"]);
  2411.                 foreach($user->getPurchases() as $purchase) {
  2412.                     if($purchase->getStatus() == Purchase::STATUS_PROCESSED) {
  2413.                         foreach($purchase->getItems() as $pitem) {
  2414.                             if($product == $pitem->getProduct() && $pitem->getContent()) {
  2415.                                 if($pitem->getContent()->getStatus() != Content::STATUS_TRASH) {
  2416.                                     $free_product_in_use true;
  2417.                                 }
  2418.                             }
  2419.                         }
  2420.                     }
  2421.                 }
  2422.                 if($free_product_in_use) {
  2423.                     $options[] = [
  2424.                         "product" => $product,
  2425.                         "disabled" => true,
  2426.                         "class" => "disabled",
  2427.                         "extra_info" => "Your free directory listing has already been redeemed. Manage your listing from your account page <a href='/account/content/4'>here</a>.",
  2428.                     ];
  2429.                 }
  2430.                 else {
  2431.                     $options[] = [
  2432.                         "product" => $product,
  2433.                         "class" => "featured",
  2434.                         "extra_info" => "Select this option to create your interactive directory listing, included with your premium R-Club membership!",
  2435.                     ];
  2436.                 }
  2437.             }
  2438.             $options array_filter($options);
  2439.             /*
  2440.             $products = $manager->getRepository(Product::class)
  2441.                 ->findBy([
  2442.                     "status" => 1,
  2443.                     "type" => 1 //< grab directory products
  2444.                 ]);
  2445.             */
  2446.         }
  2447.         else if ($part == 2) {
  2448.             $directoryCategories $categoryHelper->getCategoriesByTaxonomy("directory-category");
  2449.             if (!$chosenDirectoryProduct) {
  2450.                 $this->addFlash("warning""Please select a product.");
  2451.                 return $this->redirectToRoute("directory-join", [
  2452.                     "part" => 1,
  2453.                 ]);
  2454.             }
  2455.         }
  2456.         else if ($part == 3) {
  2457.             if ($purchaseItem) {
  2458.                 $directory $purchaseItem->getContent();
  2459.             } else if ($purchase && $purchase->getCurrentItem()) {
  2460.                 $item $purchase->getCurrentItem();
  2461.                 $directory $item->getContent();
  2462.             } else {
  2463.                 // redirect to step one
  2464.                 $this->addFlash("warning""No directory data found. Please fill out the form to create a directory listing.");
  2465.                 return $this->redirectToRoute("directory-join", [
  2466.                     "part" => 1
  2467.                 ]);
  2468.             }
  2469.         }
  2470.         /*
  2471.         $content = $item->getContent();
  2472.         $categories = $content->getSecondaryCategories();
  2473.         for ($i = 0; $i < count($categories); $i++) {
  2474.             var_dump($categories[$i]->getTitle());
  2475.         }
  2476.         exit;
  2477.         */
  2478.         if (!$item) {
  2479.             // check for tempItem
  2480.             $tempItem $session->getFlashBag()->get("directory");
  2481.             if ($tempItem) {
  2482.                 $tempItem $tempItem[0];
  2483.             }
  2484.         }
  2485.         $disableTypeSelect false;
  2486.         if($chosenDirectoryProduct && (strpos($chosenDirectoryProduct->getTitle(), 'Free') !== false)) {
  2487.             $chosenDirectoryTypes = [$categoryHelper->getCategoryBySlug("contractors")];
  2488.             $disableTypeSelect true;
  2489.         }
  2490.         
  2491.         $statesProvinces Customer::STATES_PROVINCES;
  2492.         $disableStateSelect true;
  2493.         if(is_array($chosenDirectoryTypes) && (in_array("Distributors"$chosenDirectoryTypes) || in_array("Manufacturers Reps"$chosenDirectoryTypes) )) {
  2494.             $disableStateSelect false;
  2495.         }
  2496.         
  2497.         return $this->defaultRender("forms/directory-join.html.twig", [
  2498.             "part" => $part,
  2499.             "item" => $item,
  2500.             "tempItem" => $tempItem,
  2501.             "options" => $options,
  2502.             "content" => $directory,
  2503.             "directoryTypes" => $directoryTypes,
  2504.             "statesProvinces" => $statesProvinces,
  2505.             "chosenDirectoryTypes" => $chosenDirectoryTypes,
  2506.             "chosenDirectoryProduct" => $chosenDirectoryProduct,
  2507.             "directoryCategories" => $directoryCategories,
  2508.             "disableTypeSelect" => $disableTypeSelect,
  2509.             "disableStateSelect" => $disableStateSelect,
  2510.             // "chosenDirectoryCategories" => $chosenDirectoryCategories,
  2511.             "purchaseItem" => $purchaseItem,
  2512.         ]);
  2513.     }
  2514.     
  2515.     //--R-Club Start--
  2516.     /**
  2517.      * @Route("/rcs-club-sign-up",
  2518.      *      name="rcs-club-sign-up-post",
  2519.      *      methods={"POST"}
  2520.      * )
  2521.      */
  2522.     public function rcsClubSignUpPost (
  2523.         Request $request,
  2524.         ContentHelper $contentHelper,
  2525.         UserHelper $userHelper,
  2526.         EmailHelper $emailHelper,
  2527.         LeadHelper $leadHelper
  2528.     ) {
  2529.         $product_id $request->get("club_product_id");
  2530.         if(!$product_id) {
  2531.             $product_id 19//The id of the individual monthly club membership product
  2532.         }
  2533.         
  2534.         $user $this->user;
  2535.         $manager $this->getDoctrine()->getManager();
  2536.         
  2537.         if (!$user) {
  2538.             $signType $request->get("signType");
  2539.             if($signType == "signIn") {
  2540.                 //Essentially a copy of the AuthController's sign-in-post function
  2541.                 $username $request->get("_username");
  2542.                 $password $request->get("_password");
  2543.                 if(!$emailHelper->checkCaptcha($request->get("g-recaptcha-response"))) {
  2544.                     //$this->addFlash("warning", "The reCAPTCHA was invalid. Please try again.");
  2545.                     $message = array (
  2546.                         "type" => "warning",
  2547.                         "text" => "The reCAPTCHA was invalid. Please try again.",
  2548.                     );
  2549.                     /*
  2550.                     return $this->defaultRender("forms/sign-in.html.twig", [
  2551.                         "message" => $message,
  2552.                     ]);
  2553.                     */
  2554.                     return $this->redirectToRoute("rcs-club-sign-up");
  2555.                 }
  2556.                 /*
  2557.                 $session = $request->getSession();
  2558.                 $nRoute = $session->get("non_sign_in_route");
  2559.                 $path = !empty($nRoute["path"]) ? $nRoute["path"] : "/";
  2560.                 */
  2561.                 $result $userHelper->signIn(
  2562.                     $username
  2563.                     $password,
  2564.                     //$this->get("security.token_storage"),
  2565.                     //$this->get("event_dispatcher")
  2566.                 );
  2567.                 if(is_array($result) && $result["status"] == 2) {
  2568.                     return new RedirectResponse("/mfa/{$result['uid']}/{$result['token']}");
  2569.                 }
  2570.                 elseif (is_array($result) && $result["status"] == 1) {
  2571.                     $user $userHelper->getUserById($result["uid"]);
  2572.                     if($user->isMember()) {
  2573.                         $this->addFlash("success""You have successfully logged in - and your account is already an R-Club member!");
  2574.                         return $this->redirectToRoute("rcs-club-sign-up");
  2575.                     }
  2576.                     else {
  2577.                         $this->addFlash("success""You have successfully logged in.");
  2578.                     }
  2579.                 }
  2580.                 else {            
  2581.                     //$this->addFlash("warning", "Invalid credentials provided.");
  2582.                     $message = array (
  2583.                         "type" => "warning",
  2584.                         "text" => "Invalid credentials provided.",
  2585.                     );
  2586.                     /*
  2587.                     return $this->defaultRender("forms/sign-in.html.twig", [
  2588.                         "message" => $message,
  2589.                     ]);
  2590.                     */
  2591.                     return $this->redirectToRoute("rcs-club-sign-up");
  2592.                 }
  2593.                 
  2594.                 //return new RedirectResponse($path);
  2595.             }
  2596.             elseif($signType == "signUp") {
  2597.                 //Essentially a copy of the AuthController's new-sign-up function
  2598.                 
  2599.                 
  2600.                 if(!$emailHelper->checkCaptcha($request->get("g-recaptcha-response"))) {
  2601.                     
  2602.                     $lead $request->get("lead");
  2603.                     
  2604.                     $firstname array_key_exists("firstname"$lead) ? $lead["firstname"] : "";
  2605.                     $lastname array_key_exists("lastname"$lead) ? $lead["lastname"] : "";
  2606.                     $email array_key_exists("email"$lead) ? $lead["email"] : "";
  2607.                     $username array_key_exists("username"$lead) ? $lead["username"] : "";
  2608.                     $address1 array_key_exists("address1"$lead) ? $lead["address1"] : "";
  2609.                     $address2 array_key_exists("address2"$lead) ? $lead["address2"] : "";
  2610.                     $city array_key_exists("city"$lead) ? $lead["city"] : "";
  2611.                     $state array_key_exists("state"$lead) ? $lead["state"] : "";
  2612.                     $zip array_key_exists("zip"$lead) ? $lead["zip"] : "";
  2613.                     $company array_key_exists("company"$lead) ? $lead["company"] : "";
  2614.                     $phone array_key_exists("phone"$lead) ? $lead["phone"] : "";
  2615.                     
  2616.                     //$this->addFlash("warning", "The reCAPTCHA was invalid. Please try again.");
  2617.                     $content $contentHelper->getPageBySlug("rcs-club-sign-up");
  2618.                     $manager $this->getDoctrine()->getManager();
  2619.                     $products $manager->getRepository(Product::class)
  2620.                         ->findBy([
  2621.                             "status" => 1,
  2622.                             "type" => Product::PRODUCT_TYPE_MEMBERSHIP //< grab r-club products
  2623.                         ]);
  2624.             
  2625.                     return $this->defaultRender("forms/rcs-club-sign-up.html.twig", [
  2626.                         "content" => $content,
  2627.                         "products" => $products,
  2628.                         "username" => $username,
  2629.                         "email" => $email,
  2630.                         "firstname" => $firstname,
  2631.                         "lastname" => $lastname,
  2632.                         "address1" => $address1,
  2633.                         "address2" => $address2,
  2634.                         "city" => $city,
  2635.                         "state" => $state,
  2636.                         "zip" => $zip,
  2637.                         "company" => $company,
  2638.                         "phone" => $phone,
  2639.                         "message" => [
  2640.                             "type" => "warning",
  2641.                             "text" => "The reCAPTCHA was invalid. Please try again.",
  2642.                         ]
  2643.                     ]);
  2644.                     /*
  2645.                     return $this->defaultRender("forms/new-sign-up.html.twig", [
  2646.                         "username" => $username,
  2647.                         "email" => $email,
  2648.                         "firstname" => $firstname,
  2649.                         "lastname" => $lastname,
  2650.                         "address1" => $address1,
  2651.                         "address2" => $address2,
  2652.                         "city" => $city,
  2653.                         "state" => $state,
  2654.                         "zip" => $zip,
  2655.                         "company" => $company,
  2656.                         "phone" => $phone,
  2657.                         "message" => [
  2658.                             "type" => "warning",
  2659.                             "text" => "The reCAPTCHA was invalid. Please try again.",
  2660.                         ]
  2661.                     ]);
  2662.                     */
  2663.                 }
  2664.                 
  2665.                 
  2666.                 $siteSignup $request->get("site-signup");
  2667.                 $enewsSignup $request->get("enews-signup");
  2668.                 //$enewsMetalSignup = $request->get("enews-metal-signup");
  2669.                 
  2670.                 $enewsSignupSuccess false//store if they signed up for the enews
  2671.                 $enewsMetalSignupSuccess false//store if they signed up for metal enews
  2672.                 $siteSignupSuccess false//store if they signed up for the site
  2673.                 
  2674.                 
  2675.                 if($siteSignup) {
  2676.                     //Handle the form for signing up to the site.
  2677.                     $lead $request->get("lead");
  2678.                     
  2679.                     $username $lead["username"];
  2680.                     $email $lead["email"];
  2681.                     $email trim($email);
  2682.                     $firstname $lead["firstname"];
  2683.                     $lastname $lead["lastname"];
  2684.                     
  2685.                     $address1 $lead["address1"];
  2686.                     $address2 $lead["address2"];
  2687.                     $city $lead["city"];
  2688.                     $state $lead["state"];
  2689.                     $zip $lead["zip"];
  2690.                     $company $lead["company"];
  2691.                     $phone $lead["phone"];
  2692.                     
  2693.                     $password1 $request->get("password1");
  2694.                     $password2 $request->get("password2");
  2695.                     
  2696.                     $rsp $userHelper->signUp(
  2697.                         $firstname,
  2698.                         $lastname,
  2699.                         $username,
  2700.                         $email,
  2701.                         $password1,
  2702.                         $password2,
  2703.                         $product_id //redirect to r-club checkout after activatino
  2704.                     );
  2705.                     
  2706.                     if ($rsp["status"]) { //success
  2707.                         $siteSignupSuccess true;
  2708.                         //return new RedirectResponse('/welcome-activation');
  2709.                     }
  2710.                     else {
  2711.                         
  2712.                         //$this->addFlash("warning", $rsp["message"]);
  2713.                         $content $contentHelper->getPageBySlug("rcs-club-sign-up");
  2714.                         $manager $this->getDoctrine()->getManager();
  2715.                         $products $manager->getRepository(Product::class)
  2716.                             ->findBy([
  2717.                                 "status" => 1,
  2718.                                 "type" => Product::PRODUCT_TYPE_MEMBERSHIP //< grab r-club products
  2719.                             ]);
  2720.                 
  2721.                         return $this->defaultRender("forms/rcs-club-sign-up.html.twig", [
  2722.                             "content" => $content,
  2723.                             "products" => $products,
  2724.                             "username" => $username,
  2725.                             "email" => $email,
  2726.                             "firstname" => $firstname,
  2727.                             "lastname" => $lastname,
  2728.                             "address1" => $address1,
  2729.                             "address2" => $address2,
  2730.                             "city" => $city,
  2731.                             "state" => $state,
  2732.                             "zip" => $zip,
  2733.                             "company" => $company,
  2734.                             "phone" => $phone,
  2735.                             "message" => $rsp["message"],
  2736.                         ]);
  2737.                         
  2738.                     }
  2739.                     
  2740.                 }
  2741.                 
  2742.                 if($enewsSignup || ($siteSignup && $siteSignupSuccess && ($request->get("enews") || $request->get("metal-enews")))) {
  2743.                     //Handle the form for signing up for just enews-signup
  2744.                     $lead $request->get("lead");
  2745.                     
  2746.                     $firstname $lead["firstname"];
  2747.                     $lastname $lead["lastname"];
  2748.                     $email $lead["email"];
  2749.                     $email trim($email);
  2750.                     $company $lead["company"];
  2751.                     $contractor_type $lead["contractor_type"];
  2752.                     $country = ($lead["country"] == "Other" $lead["country_other"] : $lead["country"]);
  2753.                     $business_type $lead["business_type"];
  2754.                     
  2755.                     if(empty($email) || filter_var($emailFILTER_VALIDATE_EMAIL) === false){
  2756.                         $this->addFlash("warning""Please enter a valid email address.");
  2757.                         return new RedirectResponse($request->headers->get('referer'));
  2758.                     }            
  2759.                     if(empty($firstname)){
  2760.                         $this->addFlash("warning""Please enter your first name");
  2761.                         return new RedirectResponse($request->headers->get('referer'));
  2762.                     }
  2763.                     if(empty($lastname)){
  2764.                         $this->addFlash("warning""Please enter your last name");
  2765.                         return new RedirectResponse($request->headers->get('referer'));
  2766.                     }
  2767.                     if(empty($company)){
  2768.                         $this->addFlash("warning""Please enter your company");
  2769.                         return new RedirectResponse($request->headers->get('referer'));
  2770.                     }
  2771.                     
  2772.                     try {
  2773.                         //add to mailchimp list
  2774.                         
  2775.                         // MailChimp API credentials
  2776.                         $apiKey "27ce559264a47aa3487224e1c95424bc-us10";
  2777.                         $listID "3efdbc4139";
  2778.                         
  2779.                         // Determine wir wim or both
  2780.                         $keys = [];
  2781.                         if ($request->get("enews")) {
  2782.                             array_push($keys'WIR');
  2783.                         }
  2784.                         if ($request->get("metal-enews")) {
  2785.                             array_push($keys'WIM');
  2786.                         }
  2787.                         // MailChimp API URL
  2788.                         $memberID md5(strtolower($email));
  2789.                         $dataCenter substr($apiKey,strpos($apiKey,'-')+1);
  2790.                         $url 'https://' $dataCenter '.api.mailchimp.com/3.0/lists/' $listID '/members/' $memberID;
  2791.                         
  2792.                         // member information
  2793.                         $json json_encode([
  2794.                             'email_address' => $email,
  2795.                             'status'        => 'subscribed',
  2796.                             'merge_fields'  => [
  2797.                                 'FNAME'     => $firstname,
  2798.                                 'LNAME'     => $lastname,
  2799.                                 'MMERGE3'    => $company,
  2800.                                 'MMERGE4'    => $contractor_type,
  2801.                                 'MMERGE5'    => $business_type
  2802.                             ],
  2803.                             'tags' => $keys
  2804.                         ]);
  2805.                         
  2806.                         $ch curl_init($url);
  2807.                         curl_setopt($chCURLOPT_USERPWD'user:' $apiKey);
  2808.                         curl_setopt($chCURLOPT_HTTPHEADER, ['Content-Type: application/json']);
  2809.                         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  2810.                         curl_setopt($chCURLOPT_TIMEOUT10);
  2811.                         curl_setopt($chCURLOPT_CUSTOMREQUEST'PUT');
  2812.                         curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
  2813.                         curl_setopt($chCURLOPT_POSTFIELDS$json);
  2814.                         $result curl_exec($ch);
  2815.                         $httpCode curl_getinfo($chCURLINFO_HTTP_CODE);
  2816.                         curl_close($ch);
  2817.                         
  2818.                         if ($httpCode != 200) {
  2819.                             $httpErrorCode $httpCode;
  2820.                         }
  2821.                         
  2822.                         // end mailchimp
  2823.                         
  2824.                         if ($request->get("enews")) {
  2825.                             $emailHelper->sendEmail(
  2826.                                 ["rcs@rooferscoffeeshop.com"],
  2827.                                 "New submission from the \"Week in Roofing\" sign-up form.",
  2828.                                 [
  2829.                                     ["p" => "New submission from the \"Week in Roofing\" sign-up form."],
  2830.                                     ["table" => [
  2831.                                         "First Name" => $firstname,
  2832.                                         "Last Name" => $lastname,
  2833.                                         "Email Address" => $email,
  2834.                                         "Company" => $company,
  2835.                                         "Country" => $country,
  2836.                                         "Type of Work" => $contractor_type,
  2837.                                         "Type of Business" => $business_type,
  2838.                                     ]],
  2839.                                 ]
  2840.                             );
  2841.                         }
  2842.                         if ($request->get("metal-enews")) {
  2843.                             $emailHelper->sendEmail(
  2844.                                 ["rcs@rooferscoffeeshop.com"],
  2845.                                 "New submission from the \"Week in Metal\" sign-up form.",
  2846.                                 [
  2847.                                     ["p" => "New submission from the \"Week in Metal\" sign-up form."],
  2848.                                     ["table" => [
  2849.                                         "First Name" => $firstname,
  2850.                                         "Last Name" => $lastname,
  2851.                                         "Email Address" => $email,
  2852.                                         "Company" => $company,
  2853.                                         "Country" => $country,
  2854.                                         "Type of Work" => $contractor_type,
  2855.                                         "Type of Business" => $business_type,
  2856.                                     ]],
  2857.                                 ]
  2858.                             );
  2859.                         }
  2860.                         // store the lead
  2861.                         $content null;
  2862.                         
  2863.                         $lead_custom $request->get("lead_custom");
  2864.                         $lead $leadHelper->saveLead($lead$content$request$lead_custom);
  2865.                         
  2866.                         if(isset($httpErrorCode)) {
  2867.                             $lead->setComments("MailChimp http code: {$httpErrorCode}");
  2868.                         }
  2869.                         
  2870.                         $em $this->getDoctrine()->getManager();
  2871.                         $em->persist($lead);
  2872.                         $em->flush();
  2873.                         
  2874.                         /*
  2875.                         //TODO: fix / test mailchimp signup
  2876.                         if(isset($httpErrorCode)) {
  2877.                             $this->addFlash("warning", "An error occurred while attempting to add you to our mailing list. Please try again later.");
  2878.                             return new RedirectResponse($request->headers->get('referer'));
  2879.                         }
  2880.                         */
  2881.                         
  2882.                         //$this->addFlash("success", "Thank you for signing up for the RCS Week in Review.");
  2883.                         //return new RedirectResponse($request->headers->get('referer'));
  2884.                         $enewsSignupSuccess true;
  2885.                         
  2886.                     }
  2887.                     
  2888.                     catch (\Exception $e) {
  2889.                         $this->addFlash("warning"$e->getMessage());
  2890.                         return new RedirectResponse($request->headers->get('referer'));
  2891.                     }
  2892.                     
  2893.                 }
  2894.                 else {
  2895.                     $lead $request->get("lead");
  2896.                     $lead_custom $request->get("lead_custom");
  2897.                     $lead $leadHelper->saveLead($leadnull$request$lead_custom);
  2898.                     $em $this->getDoctrine()->getManager();
  2899.                     $em->persist($lead);
  2900.                     $em->flush();
  2901.                 }
  2902.                 
  2903.                 
  2904.                 
  2905.                 
  2906.                 if($siteSignupSuccess) {
  2907.                     return new RedirectResponse('/welcome-activation');
  2908.                 }
  2909.                 /*
  2910.                 if($enewsSignupSuccess) {
  2911.                     // $this->addFlash("success", "Thank you for signing up for the RCS Week in Roofing.");
  2912.                     return new RedirectResponse('/thank-you-wir');
  2913.                 }
  2914.                 */
  2915.             }
  2916.             
  2917.             /*
  2918.             //create a user
  2919.             $rUser = $request->get("account");
  2920.             if ($rUser) {
  2921.                 // see about creating user
  2922.                 $resp = $userHelper->signUp(
  2923.                    "bypass",
  2924.                    "bypass",
  2925.                    $rUser["username"],
  2926.                    $rUser["email"],
  2927.                    $rUser["password1"],
  2928.                    $rUser["password2"]
  2929.                 );
  2930.                 // add the message
  2931.                 $this->addFlash($resp["message"]["type"], $resp["message"]["text"]);
  2932.                 // set user to the newly created user
  2933.                 if(array_key_exists("user", $resp)) {
  2934.                     $user = $resp["user"];
  2935.                 }
  2936.                 return $this->redirectToRoute("rcs-club-sign-up");
  2937.             }
  2938.             */
  2939.         }
  2940.         if ($user) {
  2941.             
  2942.             // use the current cart or create one
  2943.            $purchase $user->getActivePurchase();
  2944.            if (!$purchase) {
  2945.                $purchase = new Purchase();
  2946.            }
  2947.            
  2948.            //Remove all items since we're going straight to checkout
  2949.            foreach($purchase->getItems() as $item) {
  2950.                //$product = $item->getProduct();
  2951.                //if($product->getType() == Product::PRODUCT_TYPE_MEMBERSHIP) {
  2952.                    $purchase->removeItem($item);
  2953.                //}
  2954.            }
  2955.            
  2956.            $newItem = new PurchaseItem();
  2957.            
  2958.            $newItem->setProduct($contentHelper->getProductById($product_id));
  2959.            $newItem->setType(PurchaseItem::TYPE_MEMBERSHIP);
  2960.            $newItem->setPurchase($purchase);
  2961.            
  2962.            // add to the current Item
  2963.            $purchase->setCurrentItem($newItem);
  2964.            $purchase->setUser($user);
  2965.            $purchase->setDiscount(0);
  2966.            
  2967.            $manager->persist($purchase);
  2968.            $manager->flush();
  2969.            
  2970.            return $this->redirectToRoute("purchase", [
  2971.            
  2972.            ]);
  2973.        }
  2974.     }
  2975.     /**
  2976.      * @Route("/rcs-club-sign-up",
  2977.      *      name="rcs-club-sign-up"
  2978.      * )
  2979.      */
  2980.     public function rcsClubSignUp (
  2981.         Request $request,
  2982.         ContentHelper $helper
  2983.     ) {
  2984.         $content $helper->getPageBySlug("rcs-club-sign-up");
  2985.         $manager $this->getDoctrine()->getManager();
  2986.         $products $manager->getRepository(Product::class)
  2987.             ->findBy([
  2988.                 "status" => 1,
  2989.                 "type" => Product::PRODUCT_TYPE_MEMBERSHIP //< grab r-club products
  2990.             ]);
  2991.         return $this->defaultRender("forms/rcs-club-sign-up.html.twig", [
  2992.             "content" => $content,
  2993.             "products" => $products,
  2994.         ]);
  2995.     }
  2996.     /**
  2997.      * @Route("/rcs-club-quick-sign-up",
  2998.      *      name="rcs-club-quick-sign-up-post",
  2999.      *      methods={"POST"}
  3000.      * )
  3001.      */
  3002.     public function rcsClubQuickSignUpPost (
  3003.         Request $request,
  3004.         ContentHelper $contentHelper,
  3005.         UserHelper $userHelper,
  3006.         EmailHelper $emailHelper,
  3007.         LeadHelper $leadHelper
  3008.     ) {
  3009.         //$product_id = 22; //The id of the company monthly club membership product
  3010.         $user $this->getUser();
  3011.         if (!$this->isGranted('IS_AUTHENTICATED_REMEMBERED') || !$user || !$user->isAdmin()) {
  3012.             return false;
  3013.         }
  3014.         $access true;
  3015.         $message null;
  3016.         $success true;
  3017.         $lead $request->get("l");
  3018.         
  3019.         $email $lead["email"];
  3020.         $email trim($email);
  3021.         $firstname $lead["firstname"];
  3022.         $lastname $lead["lastname"];
  3023.         $company $lead["company"];
  3024.         $phone $lead["phone"];
  3025.         $notes $lead["notes"];
  3026.         $product_id $lead["club_product_id"];
  3027.         
  3028.         $tmp $userHelper->checkEmailForRClubQuickSignUp($email);
  3029.         if (!$tmp["status"]) {
  3030.             $message = [
  3031.                 "type" => "warning",
  3032.                 "text" => $tmp["message"],
  3033.             ];
  3034.             $success false;
  3035.         }
  3036.         if(empty($firstname)){
  3037.             $message = [
  3038.                 "type" => "warning",
  3039.                 "text" => "Please enter your first name.",
  3040.             ];
  3041.             $success false;
  3042.         }
  3043.         if(empty($lastname)){
  3044.             $message = [
  3045.                 "type" => "warning",
  3046.                 "text" => "Please enter your last name.",
  3047.             ];
  3048.             $success false;
  3049.         }
  3050.         if($success) {
  3051.             
  3052.             // use the current cart or create one
  3053.             $purchase $user->getActivePurchase();
  3054.             if (!$purchase) {
  3055.                 $purchase = new Purchase();
  3056.             }
  3057.             
  3058.             //Remove all items since we're going straight to checkout
  3059.             foreach($purchase->getItems() as $item) {
  3060.                 //$product = $item->getProduct();
  3061.                 //if($product->getType() == Product::PRODUCT_TYPE_MEMBERSHIP) {
  3062.                     $purchase->removeItem($item);
  3063.                 //}
  3064.             }
  3065.             
  3066.             $newItem = new PurchaseItem();
  3067.             
  3068.             $newItem->setProduct($contentHelper->getProductById($product_id));
  3069.             $newItem->setType(PurchaseItem::TYPE_MEMBERSHIP);
  3070.             $newItem->setPurchase($purchase);
  3071.             if($notes) {
  3072.                 $purchaseNote = new PurchaseNote();
  3073.                 $purchaseNote->setAuthorName("RCS Payment Gateway");
  3074.                 $purchaseNote->setAuthorEmail("admin@rooferscoffeeshop.com");
  3075.                 $purchaseNote->setDescription($notes);
  3076.                 $purchase->addPurchaseNote($purchaseNote);
  3077.             }
  3078.             
  3079.             // add to the current Item
  3080.             $purchase->setCurrentItem($newItem);
  3081.             $purchase->setUser($user);
  3082.             $purchase->setDiscount(0);
  3083.             $purchase->setAdminQuickPurchase(true);
  3084.             $purchase->setFirstName($firstname);
  3085.             $purchase->setLastName($lastname);
  3086.             $purchase->setEmail($email);
  3087.             $purchase->setPhone($phone);
  3088.             $purchase->setCompany($company);
  3089.             
  3090.             $manager $this->getDoctrine()->getManager();
  3091.             $manager->persist($newItem);
  3092.             $manager->persist($purchase);
  3093.             $manager->flush();
  3094.             
  3095.             return $this->redirectToRoute("purchase", [
  3096.             
  3097.             ]);
  3098.         }
  3099.         else {
  3100.             return $this->defaultRender("forms/rcs-club-quick-sign-up.html.twig", [
  3101.                 "access" => $access,
  3102.                 "message" => $message,
  3103.                 "email" => $email,
  3104.                 "firstname" => $firstname,
  3105.                 "lastname" => $lastname,
  3106.                 "company" => $company,
  3107.                 "phone" => $phone,
  3108.                 "notes" => $notes,
  3109.             ]);
  3110.         }
  3111.     }
  3112.     /**
  3113.      * @Route("/rcs-club-quick-sign-up",
  3114.      *      name="rcs-club-quick-sign-up",
  3115.      *      methods={"GET"}
  3116.      * )
  3117.      */
  3118.     public function rcsClubQuickSignUp (
  3119.         Request $request,
  3120.         ContentHelper $helper
  3121.     ) {
  3122.         $access false;
  3123.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  3124.             $user $this->getUser();
  3125.             if($user) {
  3126.                 if($user->isAdmin()) {
  3127.                     $access true;
  3128.                 }
  3129.             }
  3130.         }
  3131.         /*
  3132.         $content = $helper->getPageBySlug("rcs-club-sign-up");
  3133.         $manager = $this->getDoctrine()->getManager();
  3134.         $products = $manager->getRepository(Product::class)
  3135.             ->findBy([
  3136.                 "status" => 1,
  3137.                 "type" => Product::PRODUCT_TYPE_MEMBERSHIP //< grab r-club products
  3138.             ]);
  3139.         */
  3140.         return $this->defaultRender("forms/rcs-club-quick-sign-up.html.twig", [
  3141.             "access" => $access,
  3142.             //"content" => $content,
  3143.             //"products" => $products,
  3144.         ]);
  3145.     }
  3146.     /**
  3147.      * @Route("/rcs-cares-choice",
  3148.      *      name="rcs-cares-choice-post",
  3149.      *      methods={"POST"}
  3150.      * )
  3151.      */
  3152.     public function rcsCaresChoicePost (
  3153.         Request $request,
  3154.         ContentHelper $contentHelper,
  3155.         UserHelper $userHelper,
  3156.         EmailHelper $emailHelper
  3157.     ) {
  3158.         $user $this->user;
  3159.         $charity $request->get("rcs_cares_charity");
  3160.         
  3161.         $user->setUsermetum("rcs_cares_charity"$charity);
  3162.         
  3163.         $entityManager $this->getDoctrine()->getManager();
  3164.         $entityManager->persist($user);
  3165.         $entityManager->flush();
  3166.         
  3167.         $this->addFlash("success""Thank you for choosing a charity to support!");
  3168.         
  3169.         $emailHelper->sendEmail(
  3170.             ["rcs@rooferscoffeeshop.com"],
  3171.             "RCS Cares Charity Selected by {$user->getDisplayname()}",
  3172.             [
  3173.                 ["p" => "{$user->getDisplayname()} has chosen to support the following charity: {$charity}."],
  3174.                 ["a" => ["href" => "rooferscoffeeshop.com/rcs-cares-choice""text" => "Click here to view all supported charities."]],
  3175.             ]
  3176.         );
  3177.         //return $this->redirectToRoute("new-club-member");
  3178.         return $this->redirectToRoute("catchall", [
  3179.             "slug" => "new-club-member",
  3180.         ]);
  3181.     }
  3182.     /**
  3183.      * @Route("/rcs-cares-choice",
  3184.      *      name="rcs-cares-choice"
  3185.      * )
  3186.      */
  3187.     public function rcsCaresChoice (
  3188.         Request $request,
  3189.         ContentHelper $helper,
  3190.         UserHelper $userhelper
  3191.     ) {
  3192.         //Members only check
  3193.         if((!$this->user || (!$this->user->isMember() && !$this->user->isAdmin()))) {
  3194.             $this->addFlash("warning""This page is only accessible to RCS Club members. Continue below to become a member and access this page.");
  3195.             return $this->redirectToRoute("rcs-club-sign-up");
  3196.         }
  3197.         $selected $this->user->getUserMetaValueByKey("rcs_cares_charity");
  3198.         //Get number that have been selected
  3199.         $charities = [];
  3200.         $metas $userhelper->getAllUserMetaByKey("rcs_cares_charity");
  3201.         foreach($metas as $meta) {
  3202.             $charity $meta->getMetavalue();
  3203.             if(array_key_exists($charity$charities)) {
  3204.                 $charities[$charity]++;
  3205.             }
  3206.             else {
  3207.                 $charities[$charity] = 1;
  3208.             }
  3209.         }
  3210.         $access false;
  3211.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  3212.             $user $this->getUser();
  3213.             if($user) {
  3214.                 if($user->isAdmin()) {
  3215.                     $access true;
  3216.                 }
  3217.             }
  3218.         }
  3219.         return $this->defaultRender("forms/rcs-cares-choice.html.twig", [
  3220.             "selected" => $selected,
  3221.             "all_selected" => $charities,
  3222.             "show_selected" => $access,
  3223.             "charities" => [
  3224.                 "RUTHERFORD HOUSING PARTNERSHIP aka Women Roofers",
  3225.                 "RONALD McDONALD HOUSE CHARITIES",
  3226.                 "ROOFING ALLIANCE",
  3227.                 "MIKE ROWE WORKS",
  3228.                 "HELMETS TO HARDHATS",
  3229.                 "HABITAT FOR HUMANITY",
  3230.                 "DAVIS MEMORIAL FOUNDATION"
  3231.             ],
  3232.         ]);
  3233.     }
  3234.     //--R-Club End--
  3235.     
  3236.     
  3237.     //Stop here 2022-03-07
  3238.     
  3239.     
  3240.     /**
  3241.      * @Route("/edit-a-classified-ad/{purchase_item}", name="edit-classified")
  3242.      */
  3243.     public function editClassifiedListing (
  3244.         Request $request,
  3245.         $purchase_item ""
  3246.     ) {
  3247.         $manager $this->getDoctrine()->getManager();
  3248.         $purchaseItem $manager->getRepository(PurchaseItem::class)
  3249.             ->findOneBy([
  3250.                 "id" => $purchase_item,
  3251.             ]);
  3252.         // ----
  3253.         die ("start here");
  3254.     }
  3255.     /**
  3256.      * @Route("/post-a-classified-ad/{step}/{purchaseItem}",
  3257.      *     name="post-classified-post",
  3258.      *     defaults={"step":"1", "purchaseItem": ""},
  3259.      *     methods={"POST"}
  3260.      * )
  3261.      */
  3262.     public function postClassifiedListingPost (
  3263.        Request $request,
  3264.        CategoryHelper $categoryHelper,
  3265.        ContentHelper $contentHelper,
  3266.        UserHelper $userHelper,
  3267.        EmailHelper $emailHelper,
  3268.        $step 1,
  3269.        $purchaseItem ""
  3270.     ) {
  3271.         // update to pull purchase from user id if available.
  3272.         $user null;
  3273.         // check if logged in
  3274.         if ($this->user) {
  3275.             $user $this->user;
  3276.         }
  3277.         // handle all steps here ...
  3278.         $manager $this->getDoctrine()->getManager();
  3279.         $session $request->getSession();
  3280.         $purchase null;
  3281.         $error = [];
  3282.         // Only store the ID in the session - use doctrine for all else...
  3283.         // this way if the user logs out and logs back in they can still see
  3284.         // the pending purchase
  3285.         if ($user) {
  3286.            $purchase $this->user->getActivePurchase();
  3287.         }
  3288.         if (!$purchase) {
  3289.             $purchase $session->get("purchase_id");
  3290.             if ($purchase) {
  3291.                 $purchase $manager->getRepository(Purchase::class)
  3292.                    ->findOneBy([
  3293.                        "id" => $purchase,
  3294.                    ]);
  3295.                 if ($purchase) {
  3296.                     // make sure purchase is valid ...
  3297.                     if ($purchase->getStatus() != Purchase::STATUS_ACTIVE) {
  3298.                         $session->remove("purchase_id");
  3299.                         $purchase null;
  3300.                     }
  3301.                 }
  3302.             }
  3303.         }
  3304.         // if still no purchase ... we need to make one
  3305.         if (!$purchase) {
  3306.             $purchase = new Purchase();
  3307.         }
  3308.         $action $request->get("action");
  3309.         if ($action) {
  3310.             if ($action == "edit_listing") {
  3311.                $step 2;
  3312.             }
  3313.             else if ($action == "edit_product") {
  3314.                 $step 1;
  3315.             }
  3316.             else if ($action == "discard") {
  3317.                 $step 1;
  3318.                 $purchase $user->getActivePurchase();
  3319.                 if ($purchase) {
  3320.                     $item $purchase->getCurrentItem();
  3321.                     $purchase->removeItem($item);
  3322.                     if (count($purchase->getCoupons())) {
  3323.                         //$purchase->removeCoupons();
  3324.                         //$this->addFlash("warning", "The coupons that were assigned to this order have been reset since the order was adjusted. You may add them back to the order from the checkout screen.");
  3325.                     }
  3326.                     $manager->persist($purchase);
  3327.                     $manager->flush();
  3328.                     $this->addFlash("success""The item has successfully been removed from your <a href='/cart'>cart</a>.");
  3329.                 }
  3330.                 return $this->redirectToRoute("post-classified", [
  3331.                     "step" => 1
  3332.                 ]);
  3333.             }
  3334.             else if ($action == "add_to_cart") {
  3335.                 $purchase $user->getActivePurchase();
  3336.                 if ($purchase) {
  3337.                     $item $purchase->getCurrentItem();
  3338.                     if ($item) {
  3339.                         // this one might not be needed
  3340.                         if (count($purchase->getCoupons())) {
  3341.                             //$purchase->removeCoupons();
  3342.                             //$this->addFlash("warning", "The coupons that were assigned to this order have been reset since the order was adjusted. You may add them back to the order from the checkout screen.");
  3343.                         }
  3344.                         $item->setStatus(PurchaseItem::STATUS_ACTIVE); //< not to be confused with STATUS_CURRENT
  3345.                         $manager->persist($purchase);
  3346.                         $manager->flush();
  3347.                         // $session->remove("purchase_id"); - the purchase id is the
  3348.                         $session->remove("classified_id");
  3349.                     }
  3350.                 }
  3351.                 // go to the shopping cart page
  3352.                 return $this->redirectToRoute("post-classified", [
  3353.                    "step" => "1",
  3354.                 ]);
  3355.             }
  3356.         }
  3357.         // pick the product
  3358.         else if ($step == 1) {
  3359.             // store the product id in the session
  3360.             //$product_id = $request->get("product");
  3361.             //$product_id = $product_id["product_id"];
  3362.             //Switching to dynamic classified ads - not based on products
  3363.             $product_id 34;
  3364.             // make sure the product exists
  3365.             $product $manager->getRepository(Product::class)
  3366.             ->findOneBy([
  3367.                 "status" => 1,
  3368.                 "id" => $product_id
  3369.             ]);
  3370.             
  3371.             //Get other options
  3372.             $duration $request->get("duration");
  3373.             $graphic $request->get("graphic");
  3374.             $regions $request->get("regions");
  3375.             $sites $request->get("sites");
  3376.             $totalPrice $request->get("total-price-input");
  3377.             
  3378.             if ($product) {
  3379.                 // if purchase exists - set product in purchase
  3380.                 if ($purchase) {
  3381.                     $item $purchase->getCurrentItem();
  3382.                     if ($item) {
  3383.                         if (count($purchase->getCoupons())) {
  3384.                             //$purchase->removeCoupons();
  3385.                             //$this->addFlash("warning", "The coupons that were assigned to this order have been reset since the order was adjusted. You may add them back to the order from the checkout screen.");
  3386.                         }
  3387.                         $item->setProduct($product);
  3388.                         
  3389.                         //$details = [];
  3390.                         //$item->setDetails();
  3391.                         
  3392.                         $manager->persist($purchase);
  3393.                         $manager->flush();
  3394.                         
  3395.                     }
  3396.                     
  3397.                 }
  3398.                 
  3399.                 /*
  3400.                 $productOptionValues = $regions;
  3401.                 if($duration){
  3402.                     $productOptionValues[] = $duration;
  3403.                 }
  3404.                 if($graphic){
  3405.                     $productOptionValues[] = $graphic;
  3406.                 }
  3407.                 foreach($productOptionValues as $productOptionValueId) {
  3408.                     $productOptionValue = $manager->getRepository(ProductOptionValue::class)
  3409.                     ->findOneBy([
  3410.                         "id" => $productOptionValueId
  3411.                     ]);
  3412.                     if($productOptionValue) {
  3413.                         $item->addProductOptionValue($productOptionValue);
  3414.                     }
  3415.                 }
  3416.                 */
  3417.                 
  3418.                 //TODO: move away from session vars?
  3419.                 // set in the session
  3420.                 $session->set("classified_id"$product_id);
  3421.                 
  3422.                 // set some other stuff in the session for the next step
  3423.                 $session->set("duration"$duration);
  3424.                 $session->set("graphic"$graphic);
  3425.                 $session->set("regions"$regions);
  3426.                 $session->set("sites"$sites);
  3427.                 $session->set("totalPrice"$totalPrice);
  3428.                 
  3429.                 // move on to step 2
  3430.                 $step 2;
  3431.             }
  3432.             
  3433.             else {
  3434.                 $error = [
  3435.                     "message" => "Please select a valid product from the list provided."
  3436.                 ];
  3437.             }
  3438.         }
  3439.         // submit the details
  3440.         else if ($step == 2) {
  3441.             if (!$user) {
  3442.                 $rUser $request->get("account");
  3443.                 if ($rUser) {
  3444.                     // see about creating user
  3445.                     $resp $userHelper->signUp(
  3446.                         $rUser["firstname"],
  3447.                         $rUser["lastname"],
  3448.                         $rUser["username"],
  3449.                         $rUser["email"],
  3450.                         $rUser["password1"],
  3451.                         $rUser["password2"]
  3452.                     );
  3453.                     // add the message
  3454.                     $this->addFlash($resp["message"]["type"], $resp["message"]["text"]);
  3455.                     // was there an error creating the user?
  3456.                     if (!$resp["status"]) {
  3457.                         $session->getFlashBag()->add("listing"$request->get("listing"));
  3458.                         return $this->redirectToRoute("post-classified", [
  3459.                             "step" => 2,
  3460.                         ]);
  3461.                     }
  3462.                     // set user to the newly created user
  3463.                     $user $resp["user"];
  3464.                 }
  3465.                 else {
  3466.                    // error - we need a user object
  3467.                    $this->addFlash("warning""You must either <a href='/sign-in'>sign</a> into the system or provide details to create an account.");
  3468.                    return $this->redirectToRoute("post-classified", [
  3469.                        "step" => 2,
  3470.                    ]);
  3471.                 }
  3472.             }
  3473.                 else {
  3474.                 $item null;
  3475.                 if ($purchaseItem) {
  3476.                     $item $manager->getRepository(PurchaseItem::class)
  3477.                         ->findOneBy([
  3478.                             "id" => $purchaseItem
  3479.                         ]);
  3480.                     // does the item belong to the current user?
  3481.                     if (!$item || $item->getPurchase()->getUser()->getId() == $user->getId()) {
  3482.                         if ($item) {
  3483.                             // set to the correct purchase object
  3484.                             $purchase $item->getPurchase();
  3485.                         }
  3486.                     } else {
  3487.                         $item null;
  3488.                         $purchaseItem null;
  3489.                     }
  3490.                 }
  3491.                 // set the user into the purchase
  3492.                 $purchase->setUser($user);
  3493.                 // by this point we should have a user id that we can link the purchase into
  3494.                 // $purchaseItem = $purchase->getCurrentItem();
  3495.                 
  3496.                 
  3497.                 $durationId $request->get("duration");
  3498.                 $graphicId $request->get("graphic");
  3499.                 $regionIds $request->get("regions");
  3500.                 $siteIds $request->get("sites");
  3501.                 $totalPrice $request->get("total-price-input");
  3502.                 
  3503.                 $durationObject $manager->getRepository(ProductOptionValue::class)
  3504.                 ->findOneBy([
  3505.                     "id" => $durationId
  3506.                 ]);
  3507.                 
  3508.                 $graphicObject $manager->getRepository(ProductOptionValue::class)
  3509.                 ->findOneBy([
  3510.                     "id" => $graphicId
  3511.                 ]);
  3512.                 
  3513.                 $regionObjects = [];
  3514.                 foreach($regionIds as $regionId) {
  3515.                     $regionObject $manager->getRepository(ProductOptionValue::class)
  3516.                     ->findOneBy([
  3517.                         "id" => $regionId
  3518.                     ]);
  3519.                     $regionObjects[] = $regionObject;
  3520.                     if($regionObject->getValue() == "All Regions") {
  3521.                         $allRegions true;
  3522.                     }
  3523.                 }
  3524.                 
  3525.                 $siteObjects = [];
  3526.                 foreach($siteIds as $siteId) {
  3527.                     $siteObject $manager->getRepository(ProductOptionValue::class)
  3528.                     ->findOneBy([
  3529.                         "id" => $siteId
  3530.                     ]);
  3531.                     $siteObjects[] = $siteObject;
  3532.                 }
  3533.                 if (!$item) {
  3534.                     $item $purchase->getCurrentItem();
  3535.                     if (!$item) {
  3536.                         $item = new PurchaseItem();
  3537.                         $item->setStatus(PurchaseItem::STATUS_CURRENT);
  3538.                         $item->setType(PurchaseItem::TYPE_CLASSIFIED);
  3539.                         if($durationObject) {
  3540.                             $item->addProductOptionValue($durationObject);
  3541.                         }
  3542.                         if($graphicObject) {
  3543.                             $item->addProductOptionValue($graphicObject);
  3544.                         }
  3545.                         foreach($regionObjects as $regionObject) {
  3546.                             $item->addProductOptionValue($regionObject);
  3547.                         }
  3548.                         foreach($siteObjects as $siteObject) {
  3549.                             $item->addProductOptionValue($siteObject);
  3550.                         }
  3551.                     }
  3552.                 }
  3553.                 /*
  3554.                 if(empty($item->getProductOptionValues())) {
  3555.                     if($durationObject) {
  3556.                         $item->addProductOptionValue($durationObject);
  3557.                     }
  3558.                     if($graphicObject) {
  3559.                         $item->addProductOptionValue($graphicObject);
  3560.                     }
  3561.                     foreach($regionObjects as $regionObject) {
  3562.                         $item->addProductOptionValue($regionObject);
  3563.                     }
  3564.                     foreach($siteObjects as $siteObject) {
  3565.                         $item->addProductOptionValue($siteObject);
  3566.                     }
  3567.                 }
  3568.                 */
  3569.                 $product_id $session->get("classified_id");
  3570.                 // set the product in the purchaseItem
  3571.                 $product $item->getProduct();
  3572.                 if (!$product || ($product->getId() != $product_id && !$purchaseItem)) {
  3573.                     $product $manager->getRepository(Product::class)
  3574.                         ->findOneBy([
  3575.                            "status" => 1,
  3576.                            "id" => $product_id
  3577.                         ]);
  3578.                 }
  3579.                 // update the product incase it changed
  3580.                 $item->setProduct($product);
  3581.                 if (!$purchaseItem) {
  3582.                     $purchase->setCurrentItem($item);
  3583.                 }
  3584.                 // create temporary listing
  3585.                 $listing $request->get("listing");
  3586.                 $content $item->getContent();
  3587.                 if (!$content) {
  3588.                     $content = new Content();
  3589.                     
  3590.                     foreach($siteObjects as $siteObject) {
  3591.                         $site $manager
  3592.                             ->getRepository(Site::class)
  3593.                             ->findOneBy([
  3594.                                 "id" => Site::getSiteIdByCode($siteObject->getValue())
  3595.                             ]);
  3596.                         if($site) {
  3597.                             $content->addSite($site);
  3598.                         }
  3599.                     }
  3600.                     
  3601.                     if(empty($siteObjects)) {
  3602.                         $entityManager $this->getDoctrine()->getManager();
  3603.                         $site $entityManager
  3604.                             ->getRepository(Site::class)
  3605.                             ->findOneBy([
  3606.                                 "id" => $this->site_code
  3607.                             ]);
  3608.                         $content->addSite($site);
  3609.                     }
  3610.                     
  3611.                     $content->setStatus(Content::STATUS_INACTIVE);
  3612.                 }
  3613.                 // build the classified listing per the selected product
  3614.                 $content->setAuthor($user);
  3615.                 $content->setType(Content::CLASSIFIED);
  3616.                 $content->setTitle($listing["title"]);
  3617.                 
  3618.                 //Auto populate Customers field if an R-Club member
  3619.                 if($user->isMember()) {
  3620.                     $customers $user->getCompanies();
  3621.                     if(!empty($customers)) {
  3622.                         foreach($customers as $customer) {
  3623.                             $content->addCustomer($customer);
  3624.                         }
  3625.                     }
  3626.                 }
  3627.                 if (!$content->getSlug()) {
  3628.                    $content->setSlug($contentHelper->getUniqueSlug($listing["title"], ""Content::SITE_RCS));
  3629.                 }
  3630.                 $content->setContentFull($listing["description"]);
  3631.                 $content->setFeatured(0);
  3632.                 $content->resetSecondaryCategories();
  3633.                 if (stripos($product->getTitle(), "featured") != false || ($graphicObject && $graphicObject->getValue() == "featured")) {
  3634.                     $content->setFeatured(1);
  3635.                 }
  3636.                 $meta $content->getContentMetaByKey("_job_location");
  3637.                 if (!$meta) {
  3638.                     $meta = new ContentMeta();
  3639.                     $meta->setMetaKey("_job_location");
  3640.                     $meta->setMetaValue($listing["location"]);
  3641.                     $content->addContentMetum($meta);
  3642.                 } else {
  3643.                     $meta->setMetaValue($listing["location"]);
  3644.                 }
  3645.                 $regions $listing["region"];
  3646.                 foreach ($regions as $region) {
  3647.                     $region $categoryHelper->getCategoryById($region);
  3648.                     $content->addSecondaryCategory($region);
  3649.                 }
  3650.                 $meta $content->getContentMetaByKey("_job_country");
  3651.                 if(array_key_exists("country"$listing)) {
  3652.                     if (!$meta) {
  3653.                         $meta = new ContentMeta();
  3654.                         $meta->setMetaKey("_job_country");
  3655.                         $meta->setMetaValue($listing["country"]);
  3656.                         $content->addContentMetum($meta);
  3657.                     } else {
  3658.                         $meta->setMetaValue($listing["country"]);
  3659.                     }
  3660.                 }
  3661.                 /* TODO - allow multiple categories? */
  3662.                 $category $categoryHelper->getCategoryById($listing["category"]);
  3663.                 $content->addSecondaryCategory($category);
  3664.                 $content->setContentFull($listing["description"]);
  3665.                 $meta $content->getContentMetaByKey("_company_email");
  3666.                 if (!$meta) {
  3667.                     $meta = new ContentMeta();
  3668.                     $meta->setMetaKey("_company_email"); //< double check meta key ... doesn't look to be being used
  3669.                     $meta->setMetaValue($listing["email"]);
  3670.                     $content->addContentMetum($meta);
  3671.                 } else {
  3672.                     $meta->setMetaValue($listing["email"]);
  3673.                 }
  3674.                 // _application - same as above but
  3675.                 $meta $content->getContentMetaByKey("_application");
  3676.                 if (!$meta) {
  3677.                     $meta = new ContentMeta();
  3678.                     $meta->setMetaKey("_application");
  3679.                     $meta->setMetaValue($listing["email"]);
  3680.                     $content->addContentMetum($meta);
  3681.                 } else {
  3682.                     $meta->setMetaValue($listing["email"]);
  3683.                 }
  3684.                 // resume or file
  3685.                 $files $request->files->get("listing");
  3686.                 // set image file if provided
  3687.                 if (isset($files["image"])) {
  3688.                     $image $files["image"];
  3689.                     //$content->setFeaturedImageData($image);
  3690.                     
  3691.                     $mime $image->getMimeType();
  3692.                     if(!in_array($mime, ["image/jpg""image/jpeg""image/png""image/gif"])) {
  3693.                         $this->addFlash("danger""Only PNG, JPG, and GIF file types are allowed.");
  3694.                         return new RedirectResponse($request->headers->get('referer'));
  3695.                     }
  3696.                     
  3697.                     $media = new Media();
  3698.                     $media->setTitle($listing["file_title"]);
  3699.                     $media->setData($image);
  3700.                     $media->setDescription("Classified Listing File");
  3701.                     $media->setName($image->getClientOriginalName());
  3702.                     $content->setMedia($media);
  3703.                 }
  3704.                 else if (!empty($listing["remove_image"]) /* || stripos($product->getTitle(), 'includes image') === false*/ ) {
  3705.                     //$content->removeFeaturedImage();
  3706.                     $content->setMedia(null);
  3707.                 }
  3708.                 /*
  3709.                 else if (
  3710.                     (
  3711.                         !empty($listing["remove_image"]) ||
  3712.                         stripos($product->getTitle(), 'includes image') === false
  3713.                     ) && $content->getFeaturedImageURL()
  3714.                 ) {
  3715.                     $content->removeFeaturedImage();
  3716.                 }
  3717.                 */
  3718.                 
  3719.                 // set video file if provided
  3720.                 if (isset($files["video"])) {
  3721.                     $video $files["video"];
  3722.                     
  3723.                     $mime $video->getMimeType();
  3724.                     if(!in_array($mime, ["video/mp4""video/mp4"])) {
  3725.                         //$this->addFlash("danger", "This video file format is not allowed.");
  3726.                         //return new RedirectResponse($request->headers->get('referer'));
  3727.                     }
  3728.                     
  3729.                     $videoMedia = new Media();
  3730.                     $videoMedia->setTitle($video->getClientOriginalName());
  3731.                     $videoMedia->setData($video);
  3732.                     $videoMedia->setDescription("Classified Listing Video File");
  3733.                     $videoMedia->setName($video->getClientOriginalName());
  3734.                     $content->setVideoMedia($videoMedia);
  3735.                 }
  3736.                 else if (!empty($listing["remove_video"]) /*|| stripos($product->getTitle(), 'video') === false */ ) {
  3737.                     $content->setVideoMedia(null);
  3738.                 }
  3739.                 if (!empty($listing["remove_file"])) {
  3740.                     $containers $content->getMediaGroupContainers();
  3741.                     foreach($containers as $container) {
  3742.                         $group $container->getMediaGroup();
  3743.                         if($group->getTitle() == "Classified Listing Files") {
  3744.                             $items $group->getMediaGroupItems();
  3745.                             foreach($items as $item) {
  3746.                                 $media $item->getMedia();
  3747.                                 $media->removeFile();
  3748.                             }
  3749.                             $em $this->getDoctrine()->getManager();
  3750.                             $em->remove($container);
  3751.                             $em->flush();
  3752.                         }
  3753.                     }
  3754.                     /*
  3755.                     $group = $content->getMediaGroups();
  3756.                     for ($i = 0; $i < count($group); $i++) {
  3757.                         $items = $group[$i]->getMediaGroupItems();
  3758.                         for ($j = 0; $j < count($items); $j++) {
  3759.                             $media = $items[$j]->getMedia();
  3760.                             $media->removeFile();
  3761.                         }
  3762.                         $content->removeMediaGroup($group[$i]);
  3763.                     }
  3764.                     */
  3765.                 }
  3766.                 $file $files["file"];
  3767.                 if ($file) {
  3768.                     //copying this from above... to remove older file before adding new one
  3769.                     $containers $content->getMediaGroupContainers();
  3770.                     foreach($containers as $container) {
  3771.                         $group $container->getMediaGroup();
  3772.                         if($group->getTitle() == "Classified Listing Files") {
  3773.                             $items $group->getMediaGroupItems();
  3774.                             foreach($items as $item) {
  3775.                                 $media $item->getMedia();
  3776.                                 $media->removeFile();
  3777.                             }
  3778.                             $em $this->getDoctrine()->getManager();
  3779.                             $em->remove($container);
  3780.                             $em->flush();
  3781.                         }
  3782.                     }
  3783.                     // upload the image
  3784.                     // - using a media group in case we need to store more files in the future.
  3785.                     $media = new Media();
  3786.                     $media->setTitle($listing["file_title"]);
  3787.                     $media->setData($file);
  3788.                     $media->setDescription("Classified Listing File");
  3789.                     $media->setName($file->getClientOriginalName());
  3790.                     $mediaGroupItem = new MediaGroupItem();
  3791.                     $mediaGroupItem->setTitle("Classified Listing File");
  3792.                     $mediaGroupItem->setDescription("Classified Listing File");
  3793.                     $mediaGroupItem->setMedia($media);
  3794.                     $mediaGroup = new MediaGroup();
  3795.                     $mediaGroup->setTitle("Classified Listing Files");
  3796.                     $mediaGroup->setDescription("Classified Listing Files");
  3797.                     $mediaGroup->addMediaGroupItem($mediaGroupItem);
  3798.                     $mediaGroupContainer = new MediaGroupContainer();
  3799.                     $mediaGroupContainer->setMediaGroup($mediaGroup);
  3800.                     $mediaGroupContainer->setContent($content);
  3801.                     $em $this->getDoctrine()->getManager();
  3802.                     $em->persist($mediaGroupContainer);
  3803.                     $em->flush();
  3804.                     //$content->setMediaGroups(new ArrayCollection([$mediaGroup]));
  3805.                     //$content->addMediaGroup($mediaGroup);
  3806.                     $meta $content->getContentMetaByKey("_file_title");
  3807.                     if (!$meta) {
  3808.                         $meta = new ContentMeta();
  3809.                         $meta->setMetaKey("_file_title");
  3810.                         $meta->setMetaValue($listing["file_title"]);
  3811.                         $content->addContentMetum($meta);
  3812.                     } else {
  3813.                         $meta->setMetaValue($listing["file_title"]);
  3814.                     }
  3815.                 }
  3816.                 $meta $content->getContentMetaByKey("_company_contact");
  3817.                 if (!$meta) {
  3818.                     $meta = new ContentMeta();
  3819.                     $meta->setMetaKey("_company_contact");
  3820.                     $meta->setMetaValue($listing["contact"]);
  3821.                     $content->addContentMetum($meta);
  3822.                 } else {
  3823.                     $meta->setMetaValue($listing["contact"]);
  3824.                 }
  3825.                 $meta $content->getContentMetaByKey("_company_phone");
  3826.                 if (!$meta) {
  3827.                     $meta = new ContentMeta();
  3828.                     $meta->setMetaKey("_company_phone");
  3829.                     $meta->setMetaValue($listing["phone"]);
  3830.                     $content->addContentMetum($meta);
  3831.                 } else {
  3832.                     $meta->setMetaValue($listing["phone"]);
  3833.                 }
  3834.                 $meta $content->getContentMetaByKey("_company_name");
  3835.                 if (!$meta) {
  3836.                     $meta = new ContentMeta();
  3837.                     $meta->setMetaKey("_company_name");
  3838.                     $meta->setMetaValue($listing["company"]);
  3839.                     $content->addContentMetum($meta);
  3840.                 } else {
  3841.                     $meta->setMetaValue($listing["company"]);
  3842.                 }
  3843.                 $meta $content->getContentMetaByKey("_company_website");
  3844.                 if (!$meta) {
  3845.                     $meta = new ContentMeta();
  3846.                     $meta->setMetaKey("_company_website");
  3847.                     $meta->setMetaValue($listing["website"]);
  3848.                     $content->addContentMetum($meta);
  3849.                 } else {
  3850.                     $meta->setMetaValue($listing["website"]);
  3851.                 }
  3852.                 if (!$content->getStatus()) {
  3853.                    $content->setStatus(Content::STATUS_IN_REVIEW);
  3854.                 }
  3855.                 // $content->setAuthor($user); //< this was already done above
  3856.                 // if errors - go back and show
  3857.                 // if no errors - move on
  3858.                 if (!$purchaseItem) {
  3859.                     $item $purchase->getCurrentItem();
  3860.                     $item->setContent($content);
  3861.                     $purchase->setCurrentItem($item);
  3862.                 }
  3863.                 else {
  3864.                     $this->addFlash("success""Listing Successfully Updated.");
  3865.                     //If someone edits an active listing, notify Vickie
  3866.                     if ($content->getStatus() == Content::STATUS_ACTIVE) {
  3867.                         $userText "";
  3868.                         if ($user) {
  3869.                             $username $user->getUsername();
  3870.                             $userText "by ".$username;
  3871.                         }
  3872.                         $emailHelper->sendEmail(
  3873.                             ["rcs@rooferscoffeeshop.com"],
  3874.                             "Classified Listing Updated - {$content->getTitle()}",
  3875.                             [
  3876.                                 ["p" => "The classified listing '{$content->getTitle()}' has been updated {$userText}."],
  3877.                             ]
  3878.                         );
  3879.                     }
  3880.                 }
  3881.                 if ($purchase->getStatus() != Purchase::STATUS_PROCESSED) {
  3882.                     if (count($purchase->getCoupons())) {
  3883.                         //$purchase->removeCoupons();
  3884.                         //$this->addFlash("warning", "The coupons that were assigned to this order have been reset since the order was adjusted. You may add them back to the order from the checkout screen.");
  3885.                     }
  3886.                     // set the proper total
  3887.                     // $purchase->setTotal($purchase->getTotal());
  3888.                     $purchase->setTotal($purchase->calculateTotal());
  3889.                 }
  3890.                 // update the parent purchase item
  3891.                 $manager->persist($purchase);
  3892.                 $manager->flush();
  3893.                 $purchase_id $purchase->getId();
  3894.                 $session->set("purchase_id"$purchase_id);
  3895.                 // sessions do not store relational data well - we are going to use the database and link it to the user
  3896.                 // $session->set($purchase);
  3897.                 $step 3;
  3898.             }
  3899.         }
  3900.         // add the listing to the cart
  3901.         else if ($step == 3) {
  3902.             // if updating another purchase item
  3903.             if ($purchaseItem) {
  3904.             }
  3905.             // adding purchase item to cart
  3906.             else {
  3907.                 if (count($purchase->getCoupons())) {
  3908.                     //$purchase->removeCoupons();
  3909.                     //$this->addFlash("warning", "The coupons that were assigned to this order have been reset since the order was adjusted. You may add them back to the order from the checkout screen.");
  3910.                 }
  3911.                 $item $purchase->getCurrentItem();
  3912.                 $item->setStatus(PurchaseItem::STATUS_ACTIVE);
  3913.                 $manager->persist($purchase);
  3914.                 $manager->flush();
  3915.                 // $session->remove("purchase_id"); - the purchase id is the
  3916.                 $session->remove("classified_id");
  3917.             }
  3918.             // go to the shopping cart page
  3919.             return $this->redirectToRoute("cart", [
  3920.                "slug" => "list",
  3921.             ]);
  3922.         }
  3923.         return $this->redirectToRoute("post-classified", [
  3924.            "step" => $step,
  3925.            "purchaseItem" => $purchaseItem
  3926.         ]);
  3927.     }
  3928.     /**
  3929.      * @Route("/post-a-classified-ad/{step}/{purchaseItem}",
  3930.      *     name="post-classified",
  3931.      *     defaults={"step": "1", "purchaseItem": ""}
  3932.      * )
  3933.      *
  3934.      */
  3935.     public function postClassifiedListing (
  3936.        Request $request,
  3937.        CategoryHelper $categoryHelper,
  3938.        $step 1,
  3939.        $purchaseItem ""
  3940.     ) {
  3941.         /* 2018.07.31 - forcing user account to access page
  3942.         if (!$this->user) {
  3943.             die("need to log in");
  3944.         }
  3945.         */
  3946.         $session $request->getSession();
  3947.         $manager $this->getDoctrine()->getManager();
  3948.         $purchase null;
  3949.         $tempListing $session->getFlashBag()->get("listing");
  3950.         if (!empty($tempListing)) {
  3951.            $tempListing $tempListing[0];
  3952.         }
  3953.         // ==== GRAB CURRENT PURCHASE OBJECT ========= //
  3954.         // first grab the purchase item if provided in route and match to current user...
  3955.         if ($purchaseItem && $this->user) {
  3956.             $purchaseItem $manager->getRepository(PurchaseItem::class)
  3957.                 ->findOneBy([
  3958.                    "id" => $purchaseItem
  3959.                 ]);
  3960.             if ($purchaseItem) {
  3961.                 $temp $purchaseItem->getPurchase();
  3962.                 if ($temp->getUser()->getId() == $this->user->getId()) {
  3963.                     $purchase $temp;
  3964.                 } else {
  3965.                     $purchaseItem null;
  3966.                 }
  3967.             }
  3968.         }
  3969.         else if ($purchaseItem && !$this->user) {
  3970.             $this->addFlash("warning""Please log-in before editing your listing");
  3971.             return $this->redirectToRoute("post-classified", [
  3972.                "step" => 1,
  3973.                "purchaseItem" => "",
  3974.             ]);
  3975.         }
  3976.         else {
  3977.             $purchaseItem null;
  3978.         }
  3979.         // if purchase still doesn't exist - grab the purchase object if it exists
  3980.         if (!$purchase && $this->user) {
  3981.             $purchase $this->user->getActivePurchase();
  3982.         }
  3983.         // finally if purchase still doesn't exist - try to pull from the current session
  3984.         if (!$purchase) {
  3985.             $purchase $session->get("purchase_id");
  3986.             if ($purchase) {
  3987.                 $purchase $manager->getRepository(Purchase::class)
  3988.                    ->findOneBy([
  3989.                        "id" => $purchase,
  3990.                    ]);
  3991.             }
  3992.         }
  3993.         // ========= END OF GRAB PURCHASE ITEM ======== //
  3994.         if ($purchaseItem && $purchaseItem->getType() != PurchaseItem::TYPE_CLASSIFIED) {
  3995.             // redirect to the proper editing page
  3996.             return $this->redirectToRoute("directory-join", [
  3997.                 "part" => 2,
  3998.                 "purchaseItem" => $purchaseItem->getId(),
  3999.             ]);
  4000.         }
  4001.         if ($purchase) {
  4002.             // if we're looking at a current item make sure we're looking at a classified listing item
  4003.             $item $purchase->getCurrentItem();
  4004.             if ($item && $item->getType() != PurchaseItem::TYPE_CLASSIFIED) {
  4005.                 $item->setStatus(PurchaseItem::STATUS_ACTIVE);
  4006.                 $manager->persist($item);
  4007.                 $manager->flush();
  4008.                 return $this->redirectToRoute("post-classified");
  4009.             }
  4010.         }
  4011.         $listing null;
  4012.         $regions null;
  4013.         $categories null;
  4014.         $product null;
  4015.         $products $manager->getRepository(Product::class)
  4016.            ->findBy([
  4017.                "status" => 1,
  4018.                "type" => 2
  4019.            ], [
  4020.                "price" => "ASC"
  4021.            ]);
  4022.         // update to grab values from session
  4023.         if ($step == 1) {
  4024.             if ($purchaseItem) {
  4025.                 if ($purchaseItem->getStatus() != PurchaseItem::STATUS_CURRENT) {
  4026.                     return $this->redirectToRoute("post-classified");
  4027.                 }
  4028.             }
  4029.             // check if we previously started a purchase...
  4030.             if ($purchase) {
  4031.                 $temp $purchase->getCurrentItem();
  4032.                 if ($temp) {
  4033.                     $purchaseItem $temp;
  4034.                     $product $purchaseItem->getProduct();
  4035.                 }
  4036.             }
  4037.         }
  4038.         else if ($step == 2) {
  4039.             $regions $categoryHelper->getCategoriesByTaxonomy("job_listing_type");
  4040.             $categories $categoryHelper->getCategoriesByTaxonomy("job_listing_category");
  4041.             $durationId "";
  4042.             $graphicId "";
  4043.             $regionIds = [];
  4044.             $siteIds = [];
  4045.             if ($purchaseItem) {
  4046.                 $listing $purchaseItem->getContent();
  4047.                 $product $purchaseItem->getProduct();
  4048.                 $productOptionValues $purchaseItem->getProductOptionValues();
  4049.                 foreach($productOptionValues as $productOptionValue) {
  4050.                     if ($productOptionValue->getProductOption()->getId() == 1) { //duration
  4051.                         $durationId $productOptionValue->getId();
  4052.                     }
  4053.                     if ($productOptionValue->getProductOption()->getId() == 2) { //graphic
  4054.                         $graphicId $productOptionValue->getId();
  4055.                     }
  4056.                     if ($productOptionValue->getProductOption()->getId() == 3) { //regions
  4057.                         $regionIds[] = $productOptionValue->getId();
  4058.                     }
  4059.                     if ($productOptionValue->getProductOption()->getId() == 4) { //sites
  4060.                         $siteIds[] = $productOptionValue->getId();
  4061.                     }
  4062.                 }
  4063.             }
  4064.             else {
  4065.                 if ($purchase && $purchase->getCurrentItem()) {
  4066.                     $item $purchase->getCurrentItem();
  4067.                     $listing $item->getContent();
  4068.                     $product $item->getProduct();
  4069.                 }
  4070.                 else {
  4071.                     $product_id $session->get("classified_id");
  4072.                     if ($product_id) {
  4073.                         $product $manager->getRepository(Product::class)
  4074.                         ->findOneBy([
  4075.                             "id" => $product_id,
  4076.                         ]);
  4077.                     }
  4078.                 }
  4079.             }
  4080.             
  4081.             
  4082.             //TODO: Why using session variables? Look into changing this.
  4083.             if(!$durationId) {
  4084.                 $durationId $session->get("duration");
  4085.             }
  4086.             if(!$graphicId) {
  4087.                 $graphicId $session->get("graphic");
  4088.             }
  4089.             if(empty($regionIds)) {
  4090.                 $regionIds $session->get("regions");
  4091.             }
  4092.             if(!$regionIds) {
  4093.                 $regionIds = [];
  4094.             }
  4095.             if(empty($siteIds)) {
  4096.                 $siteIds $session->get("sites");
  4097.             }
  4098.             if(!$siteIds) {
  4099.                 $siteIds = [];
  4100.             }
  4101.             $totalPrice $session->get("totalPrice");
  4102.             //TODO: calculate total price when editing
  4103.             
  4104.             $durationObject $manager->getRepository(ProductOptionValue::class)
  4105.             ->findOneBy([
  4106.                 "id" => $durationId
  4107.             ]);
  4108.             
  4109.             $graphicObject $manager->getRepository(ProductOptionValue::class)
  4110.             ->findOneBy([
  4111.                 "id" => $graphicId
  4112.             ]);
  4113.             
  4114.             $regionObjects = [];
  4115.             foreach($regionIds as $regionId) {
  4116.                 $regionObject $manager->getRepository(ProductOptionValue::class)
  4117.                 ->findOneBy([
  4118.                     "id" => $regionId
  4119.                 ]);
  4120.                 $regionObjects[] = $regionObject;
  4121.                 if($regionObject->getValue() == "All Regions") {
  4122.                     $allRegions true;
  4123.                 }
  4124.             }
  4125.             $siteObjects = [];
  4126.             foreach($siteIds as $siteId) {
  4127.                 $siteObject $manager->getRepository(ProductOptionValue::class)
  4128.                 ->findOneBy([
  4129.                     "id" => $siteId
  4130.                 ]);
  4131.                 $siteObjects[] = $siteObject;
  4132.             }
  4133.             if (!$product) {
  4134.                 $this->addFlash("warning""Please select a product.");
  4135.                 return $this->redirectToRoute("post-classified", [
  4136.                     "step" => 1
  4137.                 ]);
  4138.             }
  4139.         }
  4140.         else if ($step == 3) {
  4141.             if ($purchaseItem) {
  4142.                 $listing $purchaseItem->getContent();
  4143.                 $product $purchaseItem->getProduct();
  4144.             }
  4145.             else {
  4146.                 /*
  4147.                 $items = $purchase->getItems();
  4148.                 foreach ($items as $item) {
  4149.                     var_dump($item->getStatusText());
  4150.                 }
  4151.                 */
  4152.                 $item $purchase->getCurrentItem();
  4153.                 if ($item) {
  4154.                     $listing $item->getContent();
  4155.                     $product $item->getProduct();
  4156.                 } else {
  4157.                     return $this->redirectToRoute("post-classified");
  4158.                 }
  4159.             }
  4160.         }
  4161.         return $this->defaultRender("forms/classified-listing.html.twig", [
  4162.             "products" => $products,
  4163.             "product" => $product,
  4164.             
  4165.             "durationId" => $durationId ?? "",
  4166.             "graphicId" => $graphicId ?? "",
  4167.             "regionIds" => $regionIds ?? "",
  4168.             "siteIds" => $siteIds ?? "",
  4169.             
  4170.             "durationObject" => $durationObject ?? "",
  4171.             "graphicObject" => $graphicObject ?? "",
  4172.             "regionObjects" => $regionObjects ?? "",
  4173.             "siteObjects" => $siteObjects ?? "",
  4174.             "allRegions" => $allRegions ?? false,
  4175.             
  4176.             "totalPrice" => $totalPrice ?? "",
  4177.             
  4178.             "regions" => $regions,
  4179.             "categories" => $categories,
  4180.             "listing" => $listing,
  4181.             "tempListing" => $tempListing,
  4182.             "purchaseItem" => $purchaseItem,
  4183.             "user" => $this->user,
  4184.             "step" => $step,
  4185.             "meta" => [
  4186.                 "title" => "Post a Classified Ad",
  4187.                 "breadcrumbs" => [
  4188.                     [
  4189.                         "title" => "Post a Classified Ad",
  4190.                         "href" => "/post-a-classified-ad",
  4191.                     ]
  4192.                 ]
  4193.             ]
  4194.         ]);
  4195.     }
  4196.     
  4197. }