src/Controller/RCS/ContentController.php line 1319

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