src/Controller/RCS/ContentController.php line 1321

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