src/Controller/RCS/AuthController.php line 135

  1. <?php
  2. namespace App\Controller\RCS;
  3. use Symfony\Component\Routing\Annotation\Route;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  8. use App\Entity\Purchase;
  9. use App\Entity\PurchaseItem;
  10. use App\Entity\User;
  11. use App\Entity\Contact;
  12. use App\Entity\Coupon;
  13. use App\Entity\PurchaseNote;
  14. use App\Entity\Product;
  15. use App\Utils\ContentHelper;
  16. use App\Utils\UserHelper;
  17. use App\Utils\ContactHelper;
  18. use App\Utils\EmailHelper;
  19. use App\Utils\OrderHelper;
  20. use App\Utils\LeadHelper;
  21. use App\Security\WordPressPasswordEncoder;
  22. use App\Exception\ResourceNotFoundException;
  23. //use Symfony\Bridge\Doctrine\Security\RememberMe\DoctrineTokenProvider;
  24. use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentToken;
  25. use Symfony\Component\HttpFoundation\Cookie;
  26. //todo: Make a Master AuthController, and combine any other controllers that we can
  27. class AuthController extends DefaultController
  28. {
  29.     /**
  30.      * @Route("/sign-in",
  31.      *    name="sign-in-post",
  32.      *    defaults={"message": ""},
  33.      *  methods={"POST"}
  34.      *    )
  35.      */
  36.     public function signInPost(
  37.         Request $request,
  38.         UserHelper $userHelper,
  39.         EmailHelper $emailHelper,
  40.         //DoctrineTokenProvider $doctrineTokenProvider,
  41.         $message ""
  42.     
  43.     {
  44.         $username $request->get("_username");
  45.         $password $request->get("_password");
  46.         if(!$emailHelper->checkCaptcha($request->get("g-recaptcha-response"))) {
  47.             //$this->addFlash("warning", "The reCAPTCHA was invalid. Please try again.");
  48.             $message = array (
  49.                 "type" => "warning",
  50.                 "text" => "The reCAPTCHA was invalid. Please try again.",
  51.             );
  52.             return $this->defaultRender("forms/sign-in.html.twig", [
  53.                 "message" => $message,
  54.             ]);
  55.         }
  56.         $session $request->getSession();
  57.         $nRoute $session->get("non_sign_in_route");
  58.         $path = !empty($nRoute["path"]) ? $nRoute["path"] : "/";
  59.         $result $userHelper->signIn(
  60.             $username
  61.             $password
  62.         );
  63.         if(is_array($result) && $result["status"] == 2) {
  64.             return new RedirectResponse("/mfa/{$result['uid']}/{$result['token']}");
  65.         }
  66.         elseif (is_array($result) && $result["status"] == 1) {
  67.             $this->addFlash("success""You have successfully logged in.");
  68.             $response = new RedirectResponse($path);
  69.             //$response = $this->setRememberMe($request, $response, $doctrineTokenProvider, $username);
  70.         }
  71.         else {
  72.             $message = array (
  73.                 "type" => "warning",
  74.                 "text" => "Invalid credentials provided.",
  75.             );
  76.             return $this->defaultRender("forms/sign-in.html.twig", [
  77.                 "message" => $message,
  78.             ]);
  79.         }
  80.         
  81.         return $response;
  82.     }
  83.     
  84.     /**
  85.      * @Route("/sign-in",
  86.      *    name="sign-in",
  87.      *    defaults={"message": ""}
  88.      *    )
  89.      */
  90.     public function signIn(
  91.         Request $request,
  92.         AuthenticationUtils $authUtils,
  93.         WordPressPasswordEncoder $wpEncoder,
  94.         $message ""
  95.     ) {
  96.         //just testing: $message = $wpEncoder->hash("M0byd1ck771!"); 
  97.         //$message = null;
  98.         $message $request->query->get("message") ?? "";
  99.         
  100.         $error $authUtils->getLastAuthenticationError();
  101.         $lastUsername $authUtils->getLastUsername();
  102.         if ($error) {
  103.             $message = array (
  104.                 "type" => "warning",
  105.                 "text" => "Invalid credentials.",
  106.             );
  107.         }
  108.         
  109.         
  110.         return $this->defaultRender("forms/sign-in.html.twig", [
  111.             "last_username" => $lastUsername,
  112.             // "error" => $error,
  113.             "message" => $message,
  114.         ]);
  115.     }
  116.     
  117.     /**
  118.      * @Route("/forgot-password", name="forgot-password")
  119.      */
  120.     public function forgotPassword (
  121.         Request $request,
  122.         UserHelper $userHelper,
  123.         ContactHelper $contactHelper,
  124.         EmailHelper $emailHelper
  125.     ) {        
  126.         // should we rate limit ??
  127.         $username $request->request->get("username");
  128.         $message = array ();
  129.         
  130.         if ($username) {
  131.             $rsp $userHelper->forgotPassword($username);
  132.             $message = array(
  133.                 "type" => $rsp["status"] ? "success" "warning",
  134.                 "text" => $rsp["message"],
  135.             );
  136.         }
  137.         
  138.         return $this->defaultRender("forms/forgot-password.html.twig", [
  139.             "message" => $message,
  140.         ]);
  141.     }
  142.     
  143.     /**
  144.      * @Route("/forgot-username", name="forgot-username", methods={"POST"})
  145.      */
  146.     public function forgotUsername (
  147.         Request $request,
  148.         UserHelper $userHelper
  149.     ) {
  150.         $email $request->get("email");
  151.         $rsp $userHelper->forgotUsername($email);
  152.         $msg = array ();
  153.         
  154.         if ($rsp["status"]) {
  155.             $msg = array (
  156.                 "type" => "success",
  157.                 "text" => $rsp["message"],
  158.             );
  159.         } 
  160.         
  161.         else {
  162.             sleep (3);
  163.             $msg = array (
  164.                 "type" => "warning",
  165.                 "text" => $rsp["message"],
  166.             );
  167.         }
  168.         
  169.         return $this->defaultRender("forms/forgot-username.html.twig", [
  170.             "message" => $msg
  171.         ]);
  172.         
  173.         /*
  174.         try {
  175.             $user = $userHelper->getUserByEmail($email);
  176.             $username = $user->getUsername();
  177.             
  178.             return $this->defaultRender("forms/sign-in.html.twig", [
  179.                 "message" => [
  180.                     "type" => "success",
  181.                     "text" => "The username linked to that account is <strong>{$username}</strong>.",
  182.                 ]
  183.             ]);
  184.             
  185.         } catch (ResourceNotFoundException $e) {
  186.             sleep(3);
  187.             return $this->defaultRender("forms/forgot-username.html.twig", [
  188.                 "message" => [
  189.                     "type" => "warning",
  190.                     "text" => "That e-mail address was not found in the system.",
  191.                 ]
  192.             ]);
  193.         } 
  194.         */    
  195.     }
  196.     
  197.     /**
  198.      * @Route("/forgot-username", name="forgot-username-form")
  199.      */
  200.     public function viewForgotUsername (
  201.     
  202.     ) {
  203.         
  204.         return $this->defaultRender("forms/forgot-username.html.twig", [
  205.             "message" => array ()
  206.         ]);
  207.     }
  208.     
  209.     /**
  210.      * @Route("/rcs-reset-password/{id}/{token}", name="reset-password-form", defaults={"message": ""})
  211.      */
  212.     public function viewResetPassword (
  213.         UserHelper $userHelper,
  214.         Request $request,
  215.         $id
  216.         $token,
  217.         $message ""
  218.     ) {
  219.         
  220.         try {
  221.             $user $userHelper->getUserById($id);
  222.             
  223.             $message $request->query->get("message") ?? "";
  224.             // if token does not match 
  225.             if ($token != $user->getResetPwToken()) {
  226.                 return $this->defaultRender("errors/404.html.twig");
  227.             }
  228.             
  229.             return $this->defaultRender("forms/reset-password.html.twig", [
  230.                 "user" => $user,
  231.                 "id" => $id,
  232.                 "token" => $token,
  233.                 "message" => $message
  234.             ]);
  235.         } catch (ResourceNotFoundException $e) {
  236.             
  237.         }
  238.     }
  239.     
  240.     /**
  241.      * @Route("/rcs-reset-password", name="reset-password", methods={"POST"})
  242.      */
  243.     public function resetPassword (
  244.         Request $request,
  245.         WordPressPasswordEncoder $wpEncoder,
  246.         UserHelper $userHelper
  247.     ) {
  248.         
  249.         $id $request->get("id");
  250.         $token $request->get("token");
  251.         $password1 $request->get("password1");
  252.         $password2 $request->get("password2");
  253.         
  254.         $rsp $userHelper->resetPassword(
  255.             $id,
  256.             $token,
  257.             $password1,
  258.             $password2
  259.         );
  260.         
  261.         $msg = array ();
  262.         
  263.         if ($rsp["status"]) {
  264.             $msg = array (
  265.                 "type" => "success",
  266.                 "text" => $rsp["message"],
  267.             );
  268.             return $this->redirectToRoute("sign-in", [
  269.                 "message" => $msg
  270.             ]);
  271.         } 
  272.         
  273.         else {
  274.             $msg = array (
  275.                 "type" => "warning",
  276.                 "text" => $rsp["message"],
  277.             );
  278.             return $this->redirectToRoute("reset-password-form", [
  279.                "id" => $id,
  280.                "token" => $token,
  281.                "message" => $msg
  282.             ]);
  283.         }
  284.         
  285.     }
  286.      
  287.     /* *
  288.      * @ R o u t e ("/rcs-sign-up", name="sign-up", methods={"POST"})
  289.      * /
  290.     public function signUp (
  291.         Request $request,
  292.         UserHelper $userHelper,
  293.         EmailHelper $emailHelper
  294.     ) {
  295.         
  296.         $username = $request->get("username");
  297.         $email = $request->get("email");
  298.         
  299.         if($emailHelper->checkCaptcha($request->get("g-recaptcha-response"))) {
  300.             
  301.             $password1 = $request->get("password1");
  302.             $password2 = $request->get("password2");
  303.             
  304.             $rsp = $userHelper->signUp(
  305.                 $username,
  306.                 $email,
  307.                 $password1,
  308.                 $password2
  309.             );
  310.             
  311.             if ($rsp["status"]) {
  312.                 return $this->defaultRender("forms/sign-in.html.twig", [
  313.                     "message" => $rsp["message"],
  314.                 ]);
  315.             }
  316.             
  317.             return $this->defaultRender("forms/sign-up.html.twig", [
  318.                 "username" => $username,
  319.                 "email" => $email,
  320.                 "message" => $rsp["message"],
  321.             ]);
  322.         }
  323.         else {
  324.             return $this->defaultRender("forms/sign-up.html.twig", [
  325.                 "username" => $username,
  326.                 "email" => $email,
  327.                 "message" => [
  328.                     "type" => "warning",
  329.                     "text" => "The reCAPTCHA was invalid. Please try again.",
  330.                 ],
  331.             ]);
  332.         }
  333.     }
  334.     */
  335.     
  336.     /* *
  337.      * @ R o u t e("/rcs-sign-up", name="sign-up-form")
  338.      * /
  339.     public function viewSignUp (
  340.     
  341.     ) {
  342.         
  343.         return $this->defaultRender("forms/sign-up.html.twig", [
  344.             "username" => "",
  345.             "email" => "",
  346.             "message" => array (
  347.             
  348.             )
  349.         ]);
  350.     }
  351.     */
  352.     
  353.     /**
  354.      * @Route("/sign-up", name="new-sign-up", methods={"POST"})
  355.      */
  356.     public function newSignUp (
  357.         Request $request,
  358.         UserHelper $userHelper,
  359.         EmailHelper $emailHelper,
  360.         LeadHelper $leadHelper,
  361.         ContentHelper $contentHelper
  362.     ) {
  363.         
  364.         if(!$emailHelper->checkCaptcha($request->get("g-recaptcha-response"))) {
  365.             
  366.             $lead $request->get("lead");
  367.             
  368.             $firstname array_key_exists("firstname"$lead) ? $lead["firstname"] : "";
  369.             $lastname array_key_exists("lastname"$lead) ? $lead["lastname"] : "";
  370.             $email array_key_exists("email"$lead) ? $lead["email"] : "";
  371.             $username array_key_exists("username"$lead) ? $lead["username"] : "";
  372.             $address1 array_key_exists("address1"$lead) ? $lead["address1"] : "";
  373.             $address2 array_key_exists("address2"$lead) ? $lead["address2"] : "";
  374.             $city array_key_exists("city"$lead) ? $lead["city"] : "";
  375.             $state array_key_exists("state"$lead) ? $lead["state"] : "";
  376.             $zip array_key_exists("zip"$lead) ? $lead["zip"] : "";
  377.             $company array_key_exists("company"$lead) ? $lead["company"] : "";
  378.             $phone array_key_exists("phone"$lead) ? $lead["phone"] : "";
  379.             
  380.             //$this->addFlash("warning", "The reCAPTCHA was invalid. Please try again.");
  381.             return $this->defaultRender("forms/new-sign-up.html.twig", [
  382.                 "username" => $username,
  383.                 "email" => $email,
  384.                 "firstname" => $firstname,
  385.                 "lastname" => $lastname,
  386.                 "address1" => $address1,
  387.                 "address2" => $address2,
  388.                 "city" => $city,
  389.                 "state" => $state,
  390.                 "zip" => $zip,
  391.                 "company" => $company,
  392.                 "phone" => $phone,
  393.                 "message" => [
  394.                     "type" => "warning",
  395.                     "text" => "The reCAPTCHA was invalid. Please try again.",
  396.                 ]
  397.             ]);
  398.         }
  399.         
  400.         
  401.         $siteSignup $request->get("site-signup");
  402.         $enewsSignup $request->get("enews-signup");
  403.         //$enewsMetalSignup = $request->get("enews-metal-signup");
  404.         
  405.         $enewsSignupSuccess false//store if they signed up for the enews
  406.         $enewsMetalSignupSuccess false//store if they signed up for metal enews
  407.         $siteSignupSuccess false//store if they signed up for the site
  408.         
  409.         
  410.         if($siteSignup) {
  411.             //Handle the form for signing up to the site.
  412.             $lead $request->get("lead");
  413.             
  414.             $username $lead["username"];
  415.             $email $lead["email"];
  416.             $email trim($email);
  417.             $firstname $lead["firstname"];
  418.             $lastname $lead["lastname"];
  419.             
  420.             $address1 $lead["address1"];
  421.             $address2 $lead["address2"];
  422.             $city $lead["city"];
  423.             $state $lead["state"];
  424.             $zip $lead["zip"];
  425.             $company $lead["company"];
  426.             $phone $lead["phone"];
  427.             
  428.             $password1 $request->get("password1");
  429.             $password2 $request->get("password2");
  430.             
  431.             $rsp $userHelper->signUp(
  432.                 $firstname,
  433.                 $lastname,
  434.                 $username,
  435.                 $email,
  436.                 $password1,
  437.                 $password2
  438.             );
  439.             
  440.             if ($rsp["status"]) { //success
  441.                 $siteSignupSuccess true;
  442.                 //return new RedirectResponse('/welcome-activation');
  443.             }
  444.             else {
  445.                 
  446.                 //$this->addFlash("warning", $rsp["message"]);
  447.                 return $this->defaultRender("forms/new-sign-up.html.twig", [
  448.                     "username" => $username,
  449.                     "email" => $email,
  450.                     "firstname" => $firstname,
  451.                     "lastname" => $lastname,
  452.                     "address1" => $address1,
  453.                     "address2" => $address2,
  454.                     "city" => $city,
  455.                     "state" => $state,
  456.                     "zip" => $zip,
  457.                     "company" => $company,
  458.                     "phone" => $phone,
  459.                     "message" => $rsp["message"],
  460.                 ]);
  461.                 
  462.             }
  463.             
  464.         }
  465.         
  466.         
  467.         
  468.         if ($enewsSignup || ($siteSignup && $siteSignupSuccess && ($request->get("enews") || $request->get("metal-enews") || $request->get("coatings-enews")))) {
  469.             //Handle the form for signing up for just enews-signup
  470.             $lead $request->get("lead");
  471.             
  472.             $firstname $lead["firstname"];
  473.             $lastname $lead["lastname"];
  474.             $email $lead["email"];
  475.             $email trim($email);
  476.             $company $lead["company"];
  477.             $contractor_type $lead["contractor_type"];
  478.             $country = ($lead["country"] == "Other" $lead["country_other"] : $lead["country"]);
  479.             $business_type $lead["business_type"];
  480.             
  481.             if(empty($email) || filter_var($emailFILTER_VALIDATE_EMAIL) === false){
  482.                 $this->addFlash("warning""Please enter a valid email address.");
  483.                 return new RedirectResponse($request->headers->get('referer'));
  484.             }            
  485.             if(empty($firstname)){
  486.                 $this->addFlash("warning""Please enter your first name");
  487.                 return new RedirectResponse($request->headers->get('referer'));
  488.             }
  489.             if(empty($lastname)){
  490.                 $this->addFlash("warning""Please enter your last name");
  491.                 return new RedirectResponse($request->headers->get('referer'));
  492.             }
  493.             if(empty($company)){
  494.                 $this->addFlash("warning""Please enter your company");
  495.                 return new RedirectResponse($request->headers->get('referer'));
  496.             }
  497.             
  498.             try {
  499.                 //add to mailchimp list
  500.                 
  501.                 // MailChimp API credentials
  502.                 $apiKey "27ce559264a47aa3487224e1c95424bc-us10";
  503.                 $listID "3efdbc4139";
  504.                 
  505.                 // Determine wir wim or both
  506.                 $keys = [];
  507.                 if ($request->get("enews")) {
  508.                     array_push($keys'WIR');
  509.                 }
  510.                 if ($request->get("metal-enews")) {
  511.                     array_push($keys'WIM');
  512.                 }
  513.                 if ($request->get("coatings-enews")) {
  514.                     array_push($keys'WIC');
  515.                 }
  516.                 // MailChimp API URL
  517.                 $memberID md5(strtolower($email));
  518.                 $dataCenter substr($apiKey,strpos($apiKey,'-')+1);
  519.                 $url 'https://' $dataCenter '.api.mailchimp.com/3.0/lists/' $listID '/members/' $memberID;
  520.                 
  521.                 // member information
  522.                 $json json_encode([
  523.                     'email_address' => $email,
  524.                     'status'        => 'subscribed',
  525.                     'merge_fields'  => [
  526.                         'FNAME'     => $firstname,
  527.                         'LNAME'     => $lastname,
  528.                         'MMERGE3'    => $company,
  529.                         'MMERGE4'    => $contractor_type,
  530.                         'MMERGE5'    => $business_type
  531.                     ],
  532.                     'tags' => $keys
  533.                 ]);
  534.                 
  535.                 $ch curl_init($url);
  536.                 curl_setopt($chCURLOPT_USERPWD'user:' $apiKey);
  537.                 curl_setopt($chCURLOPT_HTTPHEADER, ['Content-Type: application/json']);
  538.                 curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  539.                 curl_setopt($chCURLOPT_TIMEOUT10);
  540.                 curl_setopt($chCURLOPT_CUSTOMREQUEST'PUT');
  541.                 curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
  542.                 curl_setopt($chCURLOPT_POSTFIELDS$json);
  543.                 $result curl_exec($ch);
  544.                 $httpCode curl_getinfo($chCURLINFO_HTTP_CODE);
  545.                 curl_close($ch);
  546.                 
  547.                 if ($httpCode != 200) {
  548.                     $httpErrorCode $httpCode;
  549.                 }
  550.                 
  551.                 // end mailchimp
  552.                 
  553.                 if ($request->get("enews")) {
  554.                     $emailHelper->sendEmail(
  555.                         ["rcs@rooferscoffeeshop.com"],
  556.                         "New submission from the \"Week in Roofing\" sign-up form.",
  557.                         [
  558.                             ["p" => "New submission from the \"Week in Roofing\" sign-up form."],
  559.                             ["table" => [
  560.                                 "First Name" => $firstname,
  561.                                 "Last Name" => $lastname,
  562.                                 "Email Address" => $email,
  563.                                 "Company" => $company,
  564.                                 "Country" => $country,
  565.                                 "Type of Work" => $contractor_type,
  566.                                 "Type of Business" => $business_type,
  567.                             ]],
  568.                         ]
  569.                     );
  570.                 }
  571.                 if ($request->get("metal-enews")) {
  572.                     $emailHelper->sendEmail(
  573.                         ["rcs@rooferscoffeeshop.com"],
  574.                         "New submission from the \"Week in Metal\" sign-up form.",
  575.                         [
  576.                             ["p" => "New submission from the \"Week in Metal\" sign-up form."],
  577.                             ["table" => [
  578.                                 "First Name" => $firstname,
  579.                                 "Last Name" => $lastname,
  580.                                 "Email Address" => $email,
  581.                                 "Company" => $company,
  582.                                 "Country" => $country,
  583.                                 "Type of Work" => $contractor_type,
  584.                                 "Type of Business" => $business_type,
  585.                             ]],
  586.                         ]
  587.                     );
  588.                 }
  589.                 if ($request->get("coatings-enews")) {
  590.                     $emailHelper->sendEmail(
  591.                         ["rcs@rooferscoffeeshop.com"],
  592.                         "New submission from the \"Week in Coatings\" sign-up form.",
  593.                         [
  594.                             ["p" => "New submission from the \"Week in Coatings\" sign-up form."],
  595.                             ["table" => [
  596.                                 "First Name" => $firstname,
  597.                                 "Last Name" => $lastname,
  598.                                 "Email Address" => $email,
  599.                                 "Company" => $company,
  600.                                 "Country" => $country,
  601.                                 "Type of Work" => $contractor_type,
  602.                                 "Type of Business" => $business_type,
  603.                             ]],
  604.                         ]
  605.                     );
  606.                 }
  607.                 // store the lead
  608.                 $content null;
  609.                 
  610.                 $lead_custom $request->get("lead_custom");
  611.                 $lead $leadHelper->saveLead($lead$content$request$lead_custom);
  612.                 
  613.                 if(isset($httpErrorCode)) {
  614.                     $lead->setComments("MailChimp http code: {$httpErrorCode}");
  615.                 }
  616.                 
  617.                 $em $this->getDoctrine()->getManager();
  618.                 $em->persist($lead);
  619.                 $em->flush();
  620.                 
  621.                 if(isset($httpErrorCode)) {
  622.                     $this->addFlash("warning""An error occurred while attempting to add you to our mailing list. Please try again later.");
  623.                     return new RedirectResponse($request->headers->get('referer'));
  624.                 }
  625.                 
  626.                 //$this->addFlash("success", "Thank you for signing up for the RCS Week in Review.");
  627.                 //return new RedirectResponse($request->headers->get('referer'));
  628.                 $enewsSignupSuccess true;
  629.                 
  630.             }
  631.             
  632.             catch (\Exception $e) {
  633.                 $this->addFlash("warning"$e->getMessage());
  634.                 return new RedirectResponse($request->headers->get('referer'));
  635.             }
  636.             
  637.         }
  638.         else {
  639.             $lead $request->get("lead");
  640.             $lead_custom $request->get("lead_custom");
  641.             $lead $leadHelper->saveLead($leadnull$request$lead_custom);
  642.             $em $this->getDoctrine()->getManager();
  643.             $em->persist($lead);
  644.             $em->flush();
  645.         }
  646.         
  647.         if($siteSignupSuccess) {
  648.             return new RedirectResponse('/welcome-activation');
  649.         }
  650.         
  651.         if($enewsSignupSuccess) {
  652.             // $this->addFlash("success", "Thank you for signing up for the RCS Week in Roofing.");
  653.             return new RedirectResponse('/thank-you-wir');
  654.         }
  655.         
  656.     }
  657.     
  658.     /**
  659.      * @Route("/sign-up", name="new-sign-up-form")
  660.      */
  661.     public function viewNewSignUp (
  662.     
  663.     ) {
  664.         
  665.         return $this->defaultRender("forms/new-sign-up.html.twig", [
  666.             "firstname" => "",
  667.             "lastname" => "",
  668.             "username" => "",
  669.             "email" => "",
  670.             "address1" => "",
  671.             "address2" => "",
  672.             "city" => "",
  673.             "state" => "",
  674.             "zip" => "",
  675.             "company" => "",
  676.             "message" => array (
  677.             
  678.             ),
  679.             "meta" => array (
  680.                "breadcrumbs" => [
  681.                    [
  682.                        "title" => "Sign Up",
  683.                        "href" => "/sign-up",
  684.                    ]
  685.                ]
  686.            )
  687.         ]);
  688.     }
  689.     
  690.     
  691.     
  692.     
  693.     
  694.     
  695.     
  696.     
  697.     /**
  698.      * @Route("/activate-account", name="activate", methods={"POST"})
  699.      */
  700.     public function activateAccount (
  701.         Request $request,
  702.         UserHelper $userHelper,
  703.         ContentHelper $contentHelper
  704.     ) {
  705.         
  706.         $id $request->get("id");
  707.         $token $request->get("token");
  708.         $rclubProdId $request->get("rclubProdId");
  709.         $rsp $userHelper->activateAccount($id$token);
  710.         
  711.         if ($rsp["status"]) {
  712.             
  713.             //redirect to purchase page if rclubProdId is set
  714.             if($rclubProdId) {
  715.                 $user $userHelper->getUserById($id);
  716.                 if ($user) {
  717.             
  718.                     // use the current cart or create one
  719.                    $purchase $user->getActivePurchase();
  720.                    if (!$purchase) {
  721.                        $purchase = new Purchase();
  722.                    }
  723.                    
  724.                    //Remove all items since we're going straight to checkout
  725.                    foreach($purchase->getItems() as $item) {
  726.                        //$product = $item->getProduct();
  727.                        //if($product->getType() == Product::PRODUCT_TYPE_MEMBERSHIP) {
  728.                            $purchase->removeItem($item);
  729.                        //}
  730.                    }
  731.                    
  732.                    $newItem = new PurchaseItem();
  733.                    
  734.                    $newItem->setProduct($contentHelper->getProductById($rclubProdId));
  735.                    $newItem->setType(PurchaseItem::TYPE_MEMBERSHIP);
  736.                    $newItem->setPurchase($purchase);
  737.                    
  738.                    // add to the current Item
  739.                    $purchase->setCurrentItem($newItem);
  740.                    $purchase->setUser($user);
  741.                    $purchase->setDiscount(0);
  742.                    
  743.                    $manager $this->getDoctrine()->getManager();
  744.                    $manager->persist($purchase);
  745.                    $manager->flush();
  746.                    
  747.                    $this->addFlash("success""You have successfully activated your account! Please complete your purchase below to join the R-Club.");
  748.                    return $this->redirectToRoute("purchase", [
  749.                    
  750.                    ]);
  751.         
  752.                }
  753.             }
  754.             /*return $this->defaultRender("/", [
  755.                 "message" => array (
  756.                     "type" => "success",
  757.                     "text" => $rsp["message"],
  758.                 )
  759.             ]);*/
  760.             
  761.             //$this->addFlash("success", $rsp["message"]);
  762.             //return $this->redirect("/");
  763.             return $this->redirect("/welcome-to-rcs");
  764.             
  765.             //$this->addFlash("success", $rsp["message"]);
  766.             //return $this->redirect('http://staging.rooferscoffeeshop.com/post-a-classified-ad/2');
  767.         
  768.         
  769.         else {
  770.             return $this->defaultRender("forms/send-activation.html.twig", [
  771.                 "type" => "warning",
  772.                 "text" => $rsp["message"],
  773.             ]);
  774.         }
  775.         
  776.         
  777.         /*
  778.         try {
  779.             $id = $request->get("id");
  780.             $token = $request->get("token");
  781.             
  782.             $user = $userHelper->getUserById($id);
  783.             $expires = $user->getActivationExpires();
  784.             
  785.             if ($user->getActivationToken() == $token && 
  786.                 new \DateTime("now") < $expires
  787.             ) {
  788.                 $user->setActivationToken(null);
  789.                 $user->setActivationExpires(null);
  790.                 // $user->setIsActive(1);
  791.                 $user->setStatus(1);
  792.                 
  793.                 $em = $this->getDoctrine()->getManager();
  794.                 $em->persist($user);
  795.                 $em->flush();
  796.                 $em->clear();
  797.                 
  798.                 return $this->defaultRender("forms/sign-in.html.twig", [
  799.                     "message" => array (
  800.                         "type" => "success",
  801.                         "text" => "The account has been activated. You may now sign in.",
  802.                     ),
  803.                 ]);
  804.             }
  805.         } 
  806.         
  807.         catch (ResourceNotFoundException $e) {
  808.             // ... ignore
  809.         }
  810.         
  811.         return $this->defaultRender("forms/send-activation.html.twig", [
  812.             "message" => array (
  813.                 "type" => "warning",
  814.                 "text" => "The provided token was not found in the system. It is possible that it has expired. If the token has expired, you will need to sign up again.",
  815.             ),
  816.         ]);
  817.         */
  818.         
  819.     }
  820.     
  821.     /**
  822.      * @Route("/activate-account/{id}/{token}/{rclubProdId}", name="view-activation-form")
  823.      */
  824.     public function viewActivateAccount (
  825.         UserHelper $userHelper,
  826.         $id "",
  827.         $token "",
  828.         $rclubProdId ""
  829.     ) {
  830.         try {
  831.             $user $userHelper->getUserById($id);
  832.             $expires $user->getActivationExpires();
  833.             if ($token == $user->getActivationToken() && 
  834.                 new \DateTime("now") < $expires 
  835.             ) {
  836.                 return $this->defaultRender("forms/activate.html.twig", [
  837.                     "username" => $user->getUsername(),
  838.                     "id" => $id,
  839.                     "token" => $token,
  840.                     "rclubProdId" => $rclubProdId,
  841.                 ]);
  842.             }
  843.         } catch (ResourceNotFoundException $e) {
  844.             // ... ignore
  845.         }
  846.         
  847.         return $this->defaultRender("forms/send-activation.html.twig", [
  848.             "message" => array (
  849.                 "type" => "warning",
  850.                 "text" => "The provided token was not found in the system. It is possible that it has expired. If the token has expired, you will need to sign up again or re-send the activation link.",
  851.             ),
  852.         ]);
  853.     }
  854.     
  855.     /**
  856.      * @Route("/send-activation", name="send-activation", methods={"POST"})
  857.      */
  858.     public function sendActivation (
  859.         Request $request,
  860.         UserHelper $userHelper,
  861.         EmailHelper $emailHelper
  862.     ) {
  863.         
  864.         $email $request->get("email");
  865.         $resp $userHelper->sendActivation($email);
  866.                  
  867.         if ($resp["status"]) {
  868.             return $this->defaultRender("forms/send-activation.html.twig", [
  869.                 "message" => array (
  870.                     "type" => "success",
  871.                     "text" => $resp["message"],
  872.                 )
  873.             ]);
  874.         }
  875.         
  876.         return $this->defaultRender("forms/send-activation.html.twig", [
  877.             "message" => array (
  878.                 "type" => "warning",
  879.                 "text" => $resp["message"],
  880.             )
  881.         ]);
  882.         
  883.         /*
  884.         try {
  885.             $email = $request->get("email");
  886.             $user = $userHelper->getUserByEmail($email);
  887.             $uid = $user->getId();
  888.             $token = $user->getActivationToken();
  889.             $expires = $user->getActivationExpires();
  890.             
  891.             $pooled = $emailHelper->sendEmail($email, "Account Activation Link", [
  892.                 ["p" => "Hello {$user->getFullName()},"],
  893.                 ["p" => "You recently requested to receive an activation link for your RoofersCoffeeShop account. Click the button below to activate it."],
  894.                 ["button" => [
  895.                     "text" => "Activate Account",
  896.                     "href" => "https://rooferscoffeeshop.com/activate-account/{$uid}/{$token}",
  897.                 ]],
  898.                 ["p" => "If you did not request a password reset, please ignore this email or reply to let us know. This password reset link is only valid for the next 2 hours."],
  899.             ]);
  900.             
  901.             if ($pooled) {
  902.                 return $this->defaultRender("forms/send-activation.html.twig", [
  903.                     "message" => array (
  904.                         "type" => "success",
  905.                         "text" => "The activation link has been sent to that e-mail address.",
  906.                     )
  907.                 ]);
  908.             } 
  909.             
  910.             return $this->defaultRender("forms/send-activation.html.twig", [
  911.                 "message" => array (
  912.                     "type" => "warning",
  913.                     "text" => "An error occurred while trying to send a system e-mail. If this error continues to occur please contact support.",
  914.                 )
  915.             ]);
  916.             
  917.         } catch (ResourceNotFoundException $e) {
  918.             
  919.         }
  920.         
  921.         return $this->defaultRender("forms/send-activation.html.twig", [
  922.             "message" => array (
  923.                 "type" => "warning",
  924.                 "text" => "No account found matching that criteria.",
  925.             )
  926.         ]);
  927.         */
  928.         
  929.     }
  930.     
  931.     /**
  932.      * @Route("/send-activation", name="send-activation-form")
  933.      */
  934.     public function viewSendActivation (
  935.         UserHelper $userHelper
  936.     ) {
  937.         return $this->defaultRender("forms/send-activation.html.twig", [
  938.             "message" => array (),
  939.         ]);
  940.     }
  941.     /**
  942.      * @Route("/mfa/{id}/{token}", name="view-mfa-form")
  943.      */
  944.     public function viewMfa (
  945.         UserHelper $userHelper,
  946.         $id "",
  947.         $token ""
  948.     ) {
  949.         try {
  950.             $user $userHelper->getUserById($id);
  951.             $expires $user->getMfaTokenExpires();
  952.             if ($token == $user->getMfaToken() && 
  953.                 new \DateTime("now") < $expires 
  954.             ) {
  955.                 return $this->defaultRender("forms/mfa.html.twig", [
  956.                     "username" => $user->getUsername(),
  957.                     "id" => $id,
  958.                     "token" => $token,
  959.                 ]);
  960.             }
  961.         } catch (ResourceNotFoundException $e) {
  962.             // ... ignore
  963.         }
  964.         
  965.         return $this->defaultRender("forms/sign-in.html.twig", [
  966.             "message" => array (
  967.                 "type" => "warning",
  968.                 "text" => "The provided token was not found in the system. It is possible that it has expired. Try signing in again.",
  969.             ),
  970.         ]);
  971.     }
  972.     /**
  973.      * @Route("/mfasignin", name="mfasignin", methods={"POST"})
  974.      */
  975.     public function mfaSignIn (
  976.         Request $request,
  977.         UserHelper $userHelper
  978.         //DoctrineTokenProvider $doctrineTokenProvider
  979.     ) {
  980.         
  981.         $id $request->get("id");
  982.         $token $request->get("token");
  983.         $code $request->get("code");
  984.         $rsp $userHelper->signInMfa($id$token$code);
  985.         
  986.         if ($rsp["status"]) {
  987.             
  988.             /*return $this->defaultRender("/", [
  989.                 "message" => array (
  990.                     "type" => "success",
  991.                     "text" => $rsp["message"],
  992.                 )
  993.             ]);*/
  994.             $session $request->getSession();
  995.             $nRoute $session->get("non_sign_in_route");
  996.             $path = !empty($nRoute["path"]) ? $nRoute["path"] : "/";
  997.             $user $userHelper->getUserById($id);
  998.             $username $user->getUsername();
  999.             
  1000.             $this->addFlash("success""You have successfully logged in.");
  1001.             $response = new RedirectResponse($path);
  1002.             //$response = $this->setRememberMe($request, $response, $doctrineTokenProvider, $username);
  1003.             return $response;
  1004.             
  1005.             //return $this->redirect("/");
  1006.             
  1007.             //$this->addFlash("success", $rsp["message"]);
  1008.             //return $this->redirect('http://staging.rooferscoffeeshop.com/post-a-classified-ad/2');
  1009.         
  1010.         
  1011.         else {
  1012.             return $this->defaultRender("forms/mfa.html.twig", [
  1013.                 //"username" => $user->getUsername(),
  1014.                 "id" => $id,
  1015.                 "token" => $token,
  1016.                 "message" => array (
  1017.                     "type" => "warning",
  1018.                     "text" => $rsp["message"],
  1019.                 )
  1020.             ]);
  1021.         }
  1022.         
  1023.     }
  1024.     //no longer used
  1025.     public function setRememberMe(
  1026.         $request,
  1027.         $response,
  1028.         $doctrineTokenProvider,
  1029.         $username
  1030.     ) {
  1031.         return false;
  1032.         $series base64_encode(random_bytes(64));
  1033.         $tokenValue base64_encode(random_bytes(64));
  1034.         $user $this->user;
  1035.         $doctrineTokenProvider->createNewToken(
  1036.             new PersistentToken(
  1037.                 User::class,
  1038.                 //$user->getUsername(),
  1039.                 $username,
  1040.                 $series,
  1041.                 $tokenValue,
  1042.                 new \DateTime()
  1043.             )
  1044.         );
  1045.         
  1046.         $options = [
  1047.             'name' => 'REMEMBERME',
  1048.             'lifetime' => 604800,
  1049.             'path' => '/',
  1050.             //'domain' => 'staging.rooferscoffeeshop.com',
  1051.             'domain' => null,
  1052.             'secure' => true,
  1053.             'httponly' => true,
  1054.             'samesite' => 'strict',
  1055.         ];
  1056.         //samesite = 
  1057.         //public const SAMESITE_NONE = 'none';
  1058.         //public const SAMESITE_LAX = 'lax';
  1059.         //public const SAMESITE_STRICT = 'strict';
  1060.         $cookieParts = [$series$tokenValue];
  1061.         
  1062.         foreach ($cookieParts as $cookiePart) {
  1063.             if (str_contains($cookiePart":")) {
  1064.                 throw new \InvalidArgumentException(sprintf('$cookieParts should not contain the cookie delimiter "%s".'":"));
  1065.             }
  1066.         }
  1067.         $encodedCookie base64_encode(implode(":"$cookieParts));
  1068.         //$response = new Response();
  1069.         $response->headers->setCookie(
  1070.             new Cookie(
  1071.                 $options['name'],
  1072.                 //$this->encodeCookie([$series, $tokenValue]),
  1073.                 $encodedCookie,
  1074.                 time() + $options['lifetime'],
  1075.                 $options['path'],
  1076.                 $options['domain'],
  1077.                 $options['secure'] ?? $request->isSecure(),
  1078.                 $options['httponly'],
  1079.                 false,
  1080.                 $options['samesite']
  1081.             )
  1082.         );
  1083.         return $response;
  1084.     }
  1085.     
  1086.     /**
  1087.      * @Route("/account", methods={"POST"}, name="post-account")
  1088.      */
  1089.     public function updateAccount (
  1090.         Request $request,
  1091.         UserHelper $userHelper
  1092.     ) {
  1093.         // if we have a current user
  1094.         if ($this->user) {
  1095.             // grab the fields
  1096.             $data = [];
  1097.             
  1098.             if ($request->get("firstname")) {
  1099.                 $data["firstname"] = $request->get("firstname");
  1100.             }
  1101.             
  1102.             if ($request->get("lastname")) {
  1103.                 $data["lastname"] = $request->get("lastname");
  1104.             }
  1105.             
  1106.             if ($request->get("displayname")) {
  1107.                 $data["displayname"] = $request->get("displayname");
  1108.             }
  1109.             
  1110.             if ($request->get("username")) {
  1111.                 $data["username"] = $request->get("username");
  1112.             }
  1113.             
  1114.             if ($request->get("email")) {
  1115.                 $data["email"] = $request->get("email");
  1116.             }
  1117.             
  1118.             if ($request->get("password1")) {
  1119.                 $data["password1"] = $request->get("password1");
  1120.                 $data["password2"] = $request->get("password2");
  1121.                 $data["password3"] = $request->get("password3");
  1122.             }
  1123.             
  1124.             // user avatar
  1125.             if ($request->files->get("avatar")) {
  1126.                 $data["avatar"] = $request->files->get("avatar");
  1127.                 $mime =  $data["avatar"]->getMimeType();
  1128.                 if(!in_array($mime, ["image/jpg""image/jpeg""image/png""image/gif"])) {
  1129.                     $this->addFlash("danger""Only PNG, JPG, and GIF file types are allowed.");
  1130.                     return new RedirectResponse($request->headers->get('referer'));
  1131.                 }
  1132.             }
  1133.             
  1134.             else if ($request->get("remove_avatar")) {
  1135.                 $data["remove_avatar"] = true;
  1136.             }
  1137.             
  1138.             //Update notifications 
  1139.             $data["usermeta"] = [];
  1140.             $notifications $request->get("notifications");
  1141.             if(empty($notifications)) {
  1142.                 $notifications = [];
  1143.             }
  1144.             $data["usermeta"]["member_notification_forum"] = in_array("forum"$notifications);
  1145.             $data["usermeta"]["member_notification_page"] = in_array("page"$notifications);
  1146.             $data["usermeta"]["member_notification_classifieds"] = in_array("classifieds"$notifications);
  1147.             
  1148.             
  1149.             $rsp $userHelper->updateAccount(
  1150.                 $this->user->getId(),
  1151.                 $data
  1152.             );
  1153.             $this->addFlash($rsp["type"], $rsp["message"]);
  1154.         }
  1155.         
  1156.         return $this->redirectToRoute("account");
  1157.     }
  1158.     
  1159.     
  1160.     /**
  1161.      * @Route("/account/profile", methods={"POST"}, name="post-account-profile")
  1162.      */
  1163.     public function updateAccountProfile (
  1164.         Request $request,
  1165.         ContactHelper $contactHelper,
  1166.         EmailHelper $emailHelper
  1167.     ) {
  1168.         
  1169.         $user $this->user;
  1170.         // if we have a current user
  1171.         if($user) {
  1172.             
  1173.             $contact $user->getContact();
  1174.             if(!$contact) {
  1175.                 $contact = new Contact();
  1176.                 $user->setContact($contact);
  1177.                 $entityManager $this->getDoctrine()->getManager();
  1178.                 $entityManager->persist($user);
  1179.                 $entityManager->flush();
  1180.             }
  1181.             
  1182.             $contactHelper->updateContact($contact->getId(), $request->request->all());
  1183.             $this->addFlash("success""Profile updated.");
  1184.             
  1185.             $emailHelper->sendEmail(
  1186.                 ["rcs@rooferscoffeeshop.com"],
  1187.                 "Profile Updated - {$user->getUsername()}",
  1188.                 [
  1189.                     ["p" => "{$user->getUsername()} has updated their account's profile information."],
  1190.                     ["p" => "Visit the User Dashboard to view these changes."],
  1191.                     ["button" => [
  1192.                         "text" => "User Dashboard",
  1193.                         "href" => "https://www.rooferscoffeeshop.com/user-dashboard",
  1194.                     ]],
  1195.                 ]
  1196.             );
  1197.             
  1198.         }
  1199.         
  1200.         return $this->redirectToRoute("account", [
  1201.            "slug" => "profile",
  1202.         ]);
  1203.     }
  1204.     
  1205.     /**
  1206.      * @Route("/account/content/{type}", name="account-content-filter")
  1207.      */
  1208.     public function viewAccountContentType (
  1209.         Request $request,
  1210.         UserHelper $userHelper,
  1211.         $type ""
  1212.     ) {
  1213.         if (!$this->user) {
  1214.             return $this->redirect("/sign-in");
  1215.         }
  1216.         $user $this->user;
  1217.         
  1218.         return $this->defaultRender("forms/user-account.html.twig", [
  1219.             "user" => $user,
  1220.             "slug" => "content",
  1221.             "type" => $type,
  1222.             
  1223.             "meta" => [
  1224.                 "breadcrumbs" => [
  1225.                     [
  1226.                         "title" => "Your Account",
  1227.                         "href" => "/account",
  1228.                     ]
  1229.                 ]
  1230.             ]
  1231.         ]);
  1232.         
  1233.         
  1234.     }
  1235.     
  1236.     /**
  1237.      * @Route("/account/membership/cancel", methods={"POST"}, name="post-account-membership-cancel")
  1238.      */
  1239.     public function cancelAccountMembership (
  1240.         Request $request,
  1241.         UserHelper $userHelper,
  1242.         OrderHelper $orderHelper,
  1243.         EmailHelper $emailHelper
  1244.     ) {
  1245.         if (!$this->user) {
  1246.             return $this->redirect("/sign-in");
  1247.         }
  1248.         $user $this->user;
  1249.         
  1250.         $manager $this->getDoctrine()->getManager();
  1251.         $item $manager->getRepository(PurchaseItem::class)
  1252.             ->findOneBy([
  1253.                "id" => $request->get("item_id"),
  1254.             ]);
  1255.         
  1256.         $item->setStatus(PurchaseItem::STATUS_ACTIVE);
  1257.         $manager->persist($item);
  1258.         $manager->flush();
  1259.         
  1260.         //send email
  1261.         $message = [];
  1262.         $message[] = ["p" => "Your R-Club membership has been cancelled and will not auto-renew."];
  1263.         $message[] = ["a" => ["href" => "rooferscoffeeshop.com/account""text" => "Go to your account page to turn auto-renew back on or update your settings."]];
  1264.         
  1265.         $emailHelper->sendEmail (
  1266.             [$user->getEmail()],
  1267.             "R-Club Auto-Renew Cancelled",
  1268.             $message
  1269.         );
  1270.         
  1271.         $this->addFlash("success""Your membership has been cancelled and will not auto-renew.");
  1272.         return $this->redirectToRoute("account", [
  1273.            "slug" => "membership",
  1274.         ]);
  1275.     }
  1276.     
  1277.     /**
  1278.      * @Route("/account/membership/continue", methods={"POST"}, name="post-account-membership-continue")
  1279.      */
  1280.     public function continueAccountMembership (
  1281.         Request $request,
  1282.         UserHelper $userHelper,
  1283.         OrderHelper $orderHelper,
  1284.         EmailHelper $emailHelper
  1285.     ) {
  1286.         if (!$this->user) {
  1287.             return $this->redirect("/sign-in");
  1288.         }
  1289.         $user $this->user;
  1290.         
  1291.         $manager $this->getDoctrine()->getManager();
  1292.         $item $manager->getRepository(PurchaseItem::class)
  1293.             ->findOneBy([
  1294.                "id" => $request->get("item_id"),
  1295.             ]);
  1296.         
  1297.         $item->setStatus($item->getPaymentFailed() ? PurchaseItem::STATUS_ACTIVE_RENEWING_FINAL PurchaseItem::STATUS_ACTIVE_RENEWING);
  1298.         $manager->persist($item);
  1299.         $manager->flush();
  1300.         
  1301.         //send email
  1302.         $message = [];
  1303.         $message[] = ["p" => "Thank you for re-activating your R-Club membership."];
  1304.         $message[] = ["a" => ["href" => "rooferscoffeeshop.com/account""text" => "Go to your account page to view your renewal information."]];
  1305.         
  1306.         $emailHelper->sendEmail (
  1307.             [$user->getEmail()],
  1308.             "R-Club Auto-Renew Activated",
  1309.             $message
  1310.         );
  1311.         
  1312.         $this->addFlash("success""Your membership has been re-activated and will now automatically renew.");
  1313.         return $this->redirectToRoute("account", [
  1314.            "slug" => "membership",
  1315.         ]);
  1316.     }
  1317.     
  1318.     /**
  1319.      * @Route("/account/membership", methods={"POST"}, name="post-account-membership")
  1320.      */
  1321.     public function updateAccountMembership (
  1322.         Request $request,
  1323.         UserHelper $userHelper,
  1324.         OrderHelper $orderHelper
  1325.     ) {
  1326.         
  1327.         if (!$this->user) {
  1328.             return $this->redirect("/sign-in");
  1329.         }
  1330.         $user $this->user;
  1331.         
  1332.         $payment $request->get("payment");
  1333.         $card $request->get("card");
  1334.         
  1335.         //expiration date
  1336.         $card["card_expires"] = $card["card_expires_month"].$card["card_expires_year"];
  1337.         
  1338.         if (!$payment || !isset($payment["terms"])) {
  1339.             $this->addFlash("warning""You must accept the terms and conditions.");
  1340.             return $this->redirectToRoute("account", [
  1341.                "slug" => "membership",
  1342.             ]);
  1343.         }
  1344.         
  1345.         $result $orderHelper->generateToken(
  1346.            $payment["firstname"],
  1347.            $payment["lastname"],
  1348.            $payment["company"],
  1349.            $payment["address1"],
  1350.            $payment["address2"],
  1351.            $payment["city"],
  1352.            $payment["state"],
  1353.            $payment["zip"],
  1354.            $payment["country"],
  1355.            $payment["email"],
  1356.            $payment["phone"],
  1357.            $_SERVER["REMOTE_ADDR"],
  1358.            $card["card_number"],
  1359.            $card["card_expires"],
  1360.            $card["card_csc"]
  1361.         );
  1362.         
  1363.         if ($result["result"] == "APPROVAL" || $result["result"] == "APPROVED") {
  1364.             
  1365.             $last4 $card["card_number"];
  1366.             $last4 preg_replace("/[^0-9]/"''$last4);
  1367.             $last4 substr($last4, -4);
  1368.             
  1369.             $user->setUsermetum("has_payment_info""1");
  1370.             $user->setUsermetum("payment_first_name"$payment["firstname"]);
  1371.             $user->setUsermetum("payment_last_name"$payment["lastname"]);
  1372.             $user->setUsermetum("payment_company"$payment["company"]);
  1373.             $user->setUsermetum("payment_address_line_1"$payment["address1"]);
  1374.             $user->setUsermetum("payment_address_line_2"$payment["address2"]);
  1375.             $user->setUsermetum("payment_city"$payment["city"]);
  1376.             $user->setUsermetum("payment_state_province"$payment["state"]);
  1377.             $user->setUsermetum("payment_postal_code"$payment["zip"]);
  1378.             $user->setUsermetum("payment_country"$payment["country"]);
  1379.             $user->setUsermetum("payment_email"$payment["email"]);
  1380.             $user->setUsermetum("payment_phone"$payment["phone"]);
  1381.             $user->setUsermetum("payment_last4"$last4);
  1382.             $user->setUsermetum("payment_exp"$card["card_expires"]);
  1383.             //$user->setUsermetum("payment_cvv2", $card["card_csc"]);
  1384.             $user->setUsermetum("payment_token"$result["token"]);
  1385.             $user->setUsermetum("payment_token_response"$result["token_response"]);
  1386.             
  1387.             $manager $this->getDoctrine()->getManager();
  1388.             $manager->persist($user);
  1389.             $manager->flush();
  1390.             
  1391.             $this->addFlash("success""Membership settings updated.");
  1392.             return $this->redirectToRoute("account", [
  1393.                //"slug" => "membership",
  1394.             ]);
  1395.         }
  1396.         else {
  1397.             $this->addFlash("warning""Their was an error while updating your payment information. Response: {$result["result"]}");
  1398.             return $this->redirectToRoute("account", [
  1399.                "slug" => "membership",
  1400.             ]);
  1401.         }
  1402.         
  1403.         
  1404.         
  1405.     }
  1406.     
  1407.     /**
  1408.      * @Route("/account/{slug}/{id}", 
  1409.      *      name="account",
  1410.      *      defaults={"slug": "", "id": ""}
  1411.      * )
  1412.      */
  1413.     public function viewAccount (
  1414.         UserHelper $userHelper,
  1415.         Request $request,
  1416.         $slug "",
  1417.         $id ""
  1418.     ) {
  1419.         if (!$this->user) {
  1420.             return $this->redirect("/sign-in");
  1421.         }
  1422.         $user $this->user;
  1423.         $manager $this->getDoctrine()->getManager();
  1424.         $purchases $user->getPurchases();
  1425.         $purchase null;
  1426.         
  1427.         if (!$slug) {
  1428.             $slug "account";
  1429.         }
  1430.         
  1431.         if ($slug == "order" && $id) {
  1432.             // show the order details
  1433.             $purchase $manager->getRepository(Purchase::class)
  1434.                 ->findOneBy([
  1435.                     "id" => $id
  1436.                 ]);
  1437.             
  1438.             if (!$purchase || $purchase->getUser()->getId() != $user->getId()) {
  1439.                 $purchase null;
  1440.             }
  1441.         }
  1442.         
  1443.         $customers $user->getCompanies();
  1444.         
  1445.         $membership_item "";
  1446.         $membership_product "";
  1447.         $will_renew false;
  1448.         //Get the current purchase item used to activate the user's membership
  1449.         if($user->isMember()) {
  1450.             $now = new \DateTime();
  1451.             foreach($purchases as $p) {
  1452.                 $items $p->getItems();
  1453.                 foreach($items as $item) {
  1454.                     if(($item->getStatus() >= PurchaseItem::STATUS_ACTIVE) && ($item->getType() == PurchaseItem::TYPE_MEMBERSHIP) && ($item->getExpiresAt() > $now)) {
  1455.                         $membership_item $item;
  1456.                         $membership_product $item->getProduct();
  1457.                         $will_renew = ($item->getStatus() >= PurchaseItem::STATUS_ACTIVE_RENEWING true false);
  1458.                     }
  1459.                 }
  1460.             }
  1461.         }
  1462.         
  1463.         $payment false;
  1464.         if($slug == "membership") {
  1465.             if($user->getUserMetaValueByKey("has_payment_info")) {
  1466.                 $payment = [];
  1467.                 $payment["firstname"] = $user->getUserMetaValueByKey("payment_first_name");
  1468.                 $payment["lastname"] = $user->getUserMetaValueByKey("payment_last_name");
  1469.                 $payment["company"] = $user->getUserMetaValueByKey("payment_company");
  1470.                 $payment["address1"] = $user->getUserMetaValueByKey("payment_address_line_1");
  1471.                 $payment["address2"] = $user->getUserMetaValueByKey("payment_address_line_2");
  1472.                 $payment["city"] = $user->getUserMetaValueByKey("payment_city");
  1473.                 $payment["state"] = $user->getUserMetaValueByKey("payment_state_province");
  1474.                 $payment["zip"] = $user->getUserMetaValueByKey("payment_postal_code");
  1475.                 $payment["country"] = $user->getUserMetaValueByKey("payment_country");
  1476.                 $payment["email"] = $user->getUserMetaValueByKey("payment_email");
  1477.                 $payment["phone"] = $user->getUserMetaValueByKey("payment_phone");
  1478.             }
  1479.         }
  1480.         
  1481.         return $this->defaultRender("forms/user-account.html.twig", [
  1482.             "user" => $user,
  1483.             "purchases" => $purchases,
  1484.             "purchase" => $purchase,
  1485.             "slug" => $slug,
  1486.             "customers" => $customers,
  1487.             "membership_item" => $membership_item,
  1488.             "membership_product" => $membership_product,
  1489.             "will_renew" => $will_renew,
  1490.             "payment" => $payment,
  1491.             
  1492.             "meta" => [
  1493.                 "breadcrumbs" => [
  1494.                     [
  1495.                         "title" => "Your Account",
  1496.                         "href" => "/account",
  1497.                     ]
  1498.                 ]
  1499.             ]
  1500.         ]);
  1501.     }
  1502.     
  1503.     /**
  1504.      * @Route("/admin-account/membership/{id}", methods={"GET"}, name="admin-account-membership")
  1505.      */
  1506.     public function adminAccountMembership(
  1507.         Request $request,
  1508.         UserHelper $userHelper,
  1509.         $id ""
  1510.     ) {
  1511.         //Admin check
  1512.         $access false;
  1513.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  1514.             $user $this->getUser();
  1515.             if($user) {
  1516.                 if($user->isAdmin()) {
  1517.                     $access true;
  1518.                 }
  1519.             }
  1520.         }
  1521.         
  1522.         if(!$access) {
  1523.             $this->addFlash("warning""This page is only accessible to site administrators.");
  1524.             return $this->redirectToRoute("/");
  1525.         }
  1526.         
  1527.         $member "";
  1528.         if($id) {
  1529.             $member $userHelper->getUserById($id);
  1530.         }
  1531.         $manager $this->getDoctrine()->getManager();
  1532.         $purchases $member->getPurchases();
  1533.         $purchase null;
  1534.         
  1535.         $membership_item "";
  1536.         $membership_product "";
  1537.         $will_renew false;
  1538.         $last_membership_item "";
  1539.         $last_membership_product "";
  1540.         $renewal_price "";
  1541.         //Get the current purchase item used to activate the user's membership
  1542.         if($member->isMember()) {
  1543.             $now = new \DateTime();
  1544.             foreach($purchases as $p) {
  1545.                 $items $p->getItems();
  1546.                 foreach($items as $item) {
  1547.                     if(($item->getStatus() >= PurchaseItem::STATUS_ACTIVE) && ($item->getType() == PurchaseItem::TYPE_MEMBERSHIP) && ($item->getExpiresAt() > $now)) {
  1548.                         $membership_item $item;
  1549.                         $membership_product $item->getProduct();
  1550.                         $will_renew = ($item->getStatus() >= PurchaseItem::STATUS_ACTIVE_RENEWING true false);
  1551.                         $renewal_price $membership_product->getPrice();
  1552.                         $old_coupons $p->getCoupons();
  1553.                         foreach($old_coupons as $coupon) {
  1554.                             if($coupon->getProductType() == Coupon::PRODUCT_TYPE_MEMBERSHIP
  1555.                                 && ($coupon->getRecurringType() == Coupon::RECURRING_UNLIMITED
  1556.                                 || ($coupon->getRecurringType() == Coupon::RECURRING_SET_MONTHS && $coupon->getMonthsRecurring() > $item->getMonthsRenewed()))
  1557.                             ) {
  1558.                                 switch ($coupon->getType()) {
  1559.                 
  1560.                                     case Coupon::TYPE_DISCOUNT:
  1561.                                         $amount $coupon->getAmount();
  1562.                                         if (strpos($amount".") === false) {
  1563.                                             $amount "{$amount}00";
  1564.                                         }
  1565.                                         $amount preg_replace("/[^0-9]*/"""$amount);
  1566.                                         $renewal_price $renewal_price - (double)$amount;
  1567.                                         break;
  1568.                                         
  1569.                                     case Coupon::TYPE_PERCENTAGE:
  1570.                                         $amount $coupon->getAmount();
  1571.                                         $amount = (double) $amount 100;
  1572.                                         $amount = ($renewal_price $amount);
  1573.                                         $renewal_price $renewal_price $amount;
  1574.                                         break;
  1575.                                         
  1576.                                     case Coupon::TYPE_FREE_PRODUCT:
  1577.                                         $couponProducts $coupon->getProducts();
  1578.                                         if ($couponProducts->contains($membership_product)) {
  1579.                                             $renewal_price 0;
  1580.                                         }
  1581.                                         break;
  1582.                                 }
  1583.                                 break;
  1584.                             }
  1585.                         }
  1586.                     }
  1587.                 }
  1588.             }
  1589.         }
  1590.         else {
  1591.             //Get the most recent purchase item used to activate the user's membership
  1592.             $now = new \DateTime();
  1593.             foreach($purchases as $p) {
  1594.                 if(!$last_membership_item) {
  1595.                     $items $p->getItems();
  1596.                     foreach($items as $item) {
  1597.                         if(($item->getStatus() == PurchaseItem::STATUS_INACTIVE) && ($item->getType() == PurchaseItem::TYPE_MEMBERSHIP) && ($item->getExpiresAt() < $now)) {
  1598.                             $last_membership_item $item;
  1599.                             $last_membership_product $item->getProduct();
  1600.                             $renewal_price $last_membership_product->getPrice();
  1601.                             break;
  1602.                         }
  1603.                     }
  1604.                 }
  1605.             }
  1606.         }
  1607.         if($renewal_price) {
  1608.             if($renewal_price 0) {
  1609.                 $renewal_price 0;
  1610.             }
  1611.             $renewal_price "$" number_format(($renewal_price 100), 2);
  1612.         }
  1613.         
  1614.         $payment false;
  1615.         if($member->getUserMetaValueByKey("has_payment_info")) {
  1616.             $payment = [];
  1617.             $payment["firstname"] = $member->getUserMetaValueByKey("payment_first_name");
  1618.             $payment["lastname"] = $member->getUserMetaValueByKey("payment_last_name");
  1619.             $payment["company"] = $member->getUserMetaValueByKey("payment_company");
  1620.             $payment["address1"] = $member->getUserMetaValueByKey("payment_address_line_1");
  1621.             $payment["address2"] = $member->getUserMetaValueByKey("payment_address_line_2");
  1622.             $payment["city"] = $member->getUserMetaValueByKey("payment_city");
  1623.             $payment["state"] = $member->getUserMetaValueByKey("payment_state_province");
  1624.             $payment["zip"] = $member->getUserMetaValueByKey("payment_postal_code");
  1625.             $payment["country"] = $member->getUserMetaValueByKey("payment_country");
  1626.             $payment["email"] = $member->getUserMetaValueByKey("payment_email");
  1627.             $payment["phone"] = $member->getUserMetaValueByKey("payment_phone");
  1628.         }
  1629.         
  1630.         return $this->defaultRender("forms/account/admin-membership.html.twig", [
  1631.             "id" => $id,
  1632.             "member" => $member,
  1633.             "purchases" => $purchases,
  1634.             "purchase" => $purchase,
  1635.             "membership_item" => $membership_item,
  1636.             "membership_product" => $membership_product,
  1637.             "last_membership_item" => $last_membership_item,
  1638.             "last_membership_product" => $last_membership_product,
  1639.             "will_renew" => $will_renew,
  1640.             "renewal_price" => $renewal_price,
  1641.             "payment" => $payment,
  1642.         ]);
  1643.     }
  1644.     
  1645.     /**
  1646.      * @Route("/admin-account/membership-cancel", methods={"POST"}, name="post-admin-account-membership-cancel")
  1647.      */
  1648.     public function adminCancelAccountMembership (
  1649.         Request $request,
  1650.         UserHelper $userHelper,
  1651.         OrderHelper $orderHelper
  1652.     ) {
  1653.         //Admin check
  1654.         $access false;
  1655.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  1656.             $admin $this->getUser();
  1657.             if($admin) {
  1658.                 if($admin->isAdmin()) {
  1659.                     $access true;
  1660.                 }
  1661.             }
  1662.         }
  1663.         
  1664.         if(!$access) {
  1665.             $this->addFlash("warning""This page is only accessible to site administrators.");
  1666.             return $this->redirectToRoute("/");
  1667.         }
  1668.         $user_id $request->get("user_id");
  1669.         $user $userHelper->getUserById($user_id);
  1670.         
  1671.         $manager $this->getDoctrine()->getManager();
  1672.         $item $manager->getRepository(PurchaseItem::class)
  1673.             ->findOneBy([
  1674.                "id" => $request->get("item_id"),
  1675.             ]);
  1676.         
  1677.         $item->setStatus(PurchaseItem::STATUS_ACTIVE);
  1678.         $manager->persist($item);
  1679.         $manager->flush();
  1680.         
  1681.         $this->addFlash("success""Membership has been cancelled and will not auto-renew.");
  1682.         return $this->redirectToRoute("admin-account-membership", [
  1683.            "id" => $user_id,
  1684.         ]);
  1685.     }
  1686.     
  1687.     /**
  1688.      * @Route("/admin-account/membership-continue", methods={"POST"}, name="post-admin-account-membership-continue")
  1689.      */
  1690.     public function adminContinueAccountMembership (
  1691.         Request $request,
  1692.         UserHelper $userHelper,
  1693.         OrderHelper $orderHelper
  1694.     ) {
  1695.         //Admin check
  1696.         $access false;
  1697.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  1698.             $admin $this->getUser();
  1699.             if($admin) {
  1700.                 if($admin->isAdmin()) {
  1701.                     $access true;
  1702.                 }
  1703.             }
  1704.         }
  1705.         
  1706.         if(!$access) {
  1707.             $this->addFlash("warning""This page is only accessible to site administrators.");
  1708.             return $this->redirectToRoute("/");
  1709.         }
  1710.         $user_id $request->get("user_id");
  1711.         $user $userHelper->getUserById($user_id);
  1712.         
  1713.         $manager $this->getDoctrine()->getManager();
  1714.         $item $manager->getRepository(PurchaseItem::class)
  1715.             ->findOneBy([
  1716.                "id" => $request->get("item_id"),
  1717.             ]);
  1718.         
  1719.         $item->setStatus($item->getPaymentFailed() ? PurchaseItem::STATUS_ACTIVE_RENEWING_FINAL PurchaseItem::STATUS_ACTIVE_RENEWING);
  1720.         $manager->persist($item);
  1721.         $manager->flush();
  1722.         
  1723.         $this->addFlash("success""Membership has been re-activated and will now automatically renew.");
  1724.         return $this->redirectToRoute("admin-account-membership", [
  1725.            "id" => $user_id,
  1726.         ]);
  1727.     }
  1728.     
  1729.     /**
  1730.      * @Route("/admin-account/membership-retry", methods={"POST"}, name="post-admin-account-membership-retry")
  1731.      */
  1732.     public function adminRetryAccountMembership (
  1733.         Request $request,
  1734.         UserHelper $userHelper,
  1735.         OrderHelper $orderHelper,
  1736.         EmailHelper $emailHelper
  1737.     ) {
  1738.         //Admin check
  1739.         $access false;
  1740.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  1741.             $admin $this->getUser();
  1742.             if($admin) {
  1743.                 if($admin->isAdmin()) {
  1744.                     $access true;
  1745.                 }
  1746.             }
  1747.         }
  1748.         
  1749.         if(!$access) {
  1750.             $this->addFlash("warning""This page is only accessible to site administrators.");
  1751.             return $this->redirectToRoute("/");
  1752.         }
  1753.         $user_id $request->get("user_id");
  1754.         $user $userHelper->getUserById($user_id);
  1755.         
  1756.         $entityManager $this->getDoctrine()->getManager();
  1757.         $item $entityManager->getRepository(PurchaseItem::class)
  1758.             ->findOneBy([
  1759.                "id" => $request->get("item_id"),
  1760.             ]);
  1761.         
  1762.         /*
  1763.         $item->setStatus($item->getPaymentFailed() ? PurchaseItem::STATUS_ACTIVE_RENEWING_FINAL : PurchaseItem::STATUS_ACTIVE_RENEWING);
  1764.         $entityManager->persist($item);
  1765.         $entityManager->flush();
  1766.         */
  1767.         
  1768.         /* Modified copy of the OrderHelper's "updateExpiredPurchaseItems" function */
  1769.         //TODO: move this to the OrderHelper so code isn't repeated
  1770.         $currentStatus PurchaseItem::STATUS_ACTIVE_RENEWING;
  1771.                 
  1772.         //Do this first: in case there's an error, it won't keep trying to renew
  1773.         $item->setStatus(PurchaseItem::STATUS_INACTIVE);
  1774.         //$item->setExpiresAt(null); //might be useful to see when it expired
  1775.         $entityManager->persist($item);
  1776.         $entityManager->flush();
  1777.         
  1778.         $purchase_completed false;
  1779.         $product $item->getProduct();
  1780.         $purchase $item->getPurchase();
  1781.         if($purchase) {
  1782.             $user $purchase->getUser();
  1783.             if($product && $user) {
  1784.                 if($user->getUserMetaValueByKey("has_payment_info")) {
  1785.                     
  1786.                     $new_purchase = new Purchase();
  1787.                     
  1788.                     $newItem = new PurchaseItem();
  1789.                     
  1790.                     $newItem->setProduct($item->getProduct());
  1791.                     $newItem->setType($item->getType());
  1792.                     $newItem->setPurchase($new_purchase);
  1793.                     
  1794.                     $new_purchase->setStatus(Purchase::STATUS_FAILED); //default to failed (we don't ever want it 'active')
  1795.                     $new_purchase->setCurrentItem($newItem);
  1796.                     $new_purchase->setUser($user);
  1797.                     $new_purchase->setDiscount(0);
  1798.                     
  1799.                     //apply any coupons
  1800.                     $old_coupons $purchase->getCoupons();
  1801.                     foreach($old_coupons as $coupon) {
  1802.                         if($coupon->getProductType() == $product->getType()
  1803.                             && ($coupon->getRecurringType() == Coupon::RECURRING_UNLIMITED
  1804.                             || ($coupon->getRecurringType() == Coupon::RECURRING_SET_MONTHS && $coupon->getMonthsRecurring() > $item->getMonthsRenewed()))
  1805.                         ) {
  1806.                             $new_purchase->addCoupon($coupon);
  1807.                         }
  1808.                     }
  1809.                     
  1810.                     //renew the purchase item
  1811.                     $result $orderHelper->placeOrder(
  1812.                         $user->getUserMetaValueByKey("payment_first_name"),
  1813.                         $user->getUserMetaValueByKey("payment_last_name"),
  1814.                         $user->getUserMetaValueByKey("payment_company"),
  1815.                         $user->getUserMetaValueByKey("payment_address_line_1"),
  1816.                         $user->getUserMetaValueByKey("payment_address_line_2"),
  1817.                         $user->getUserMetaValueByKey("payment_city"),
  1818.                         $user->getUserMetaValueByKey("payment_state_province"),
  1819.                         $user->getUserMetaValueByKey("payment_postal_code"),
  1820.                         $user->getUserMetaValueByKey("payment_country"),
  1821.                         $user->getUserMetaValueByKey("payment_email"),
  1822.                         $user->getUserMetaValueByKey("payment_phone"),
  1823.                         ""//$_SERVER["REMOTE_ADDR"],
  1824.                         $new_purchase->getInvoiceNumber(),
  1825.                         $new_purchase->getTotalUsd(true),
  1826.                         $new_purchase->getTaxUsd(true),
  1827.                         ""//no card number
  1828.                         ""//no expiration date
  1829.                         ""//$user->getUserMetaValueByKey("payment_cvv2"),
  1830.                         false,
  1831.                         $user->getUserMetaValueByKey("payment_token")
  1832.                     );
  1833.                     
  1834.                     
  1835.                     $new_purchase->setFirstname($user->getUserMetaValueByKey("payment_first_name"));
  1836.                     $new_purchase->setLastname($user->getUserMetaValueByKey("payment_last_name"));
  1837.                     $new_purchase->setCompany($user->getUserMetaValueByKey("payment_company"));
  1838.                     $new_purchase->setAddressLine1($user->getUserMetaValueByKey("payment_address_line_1"));
  1839.                     $new_purchase->setAddressLine2($user->getUserMetaValueByKey("payment_address_line_2"));
  1840.                     $new_purchase->setCity($user->getUserMetaValueByKey("payment_city"));
  1841.                     $new_purchase->setStateProvince($user->getUserMetaValueByKey("payment_state_province"));
  1842.                     $new_purchase->setPostalCode($user->getUserMetaValueByKey("payment_postal_code"));
  1843.                     $new_purchase->setCountry($user->getUserMetaValueByKey("payment_country"));
  1844.                     $new_purchase->setEmail($user->getUserMetaValueByKey("payment_email"));
  1845.                     $new_purchase->setPhone($user->getUserMetaValueByKey("payment_phone"));
  1846.                     //$new_purchase->setLast4("");
  1847.                     //$new_purchase->setUserIP($_SERVER["REMOTE_ADDR"]);
  1848.                     //$new_purchase->setUserAgent($_SERVER["HTTP_USER_AGENT"]);
  1849.                     $new_purchase->setRawResponse(json_encode([
  1850.                         "body" => $result["raw"],
  1851.                         "request" => $result["request"],
  1852.                     ]));
  1853.                     
  1854.                     $purchaseNote = new PurchaseNote();
  1855.                     $purchaseNote->setAuthorName("RCS Payment Gateway");
  1856.                     $purchaseNote->setAuthorEmail("admin@rooferscoffeeshop.com");
  1857.                     if($result["result"] == "DECLINED 82") {
  1858.                         $result["result"] = "INVALID CAM\CVV";
  1859.                     }
  1860.                     
  1861.                     if (/*true || */$result["result"] == "APPROVAL" || $result["result"] == "APPROVED") {
  1862.                         
  1863.                         $purchaseNote->setDescription("Automatic payment attempt was successful. Response Code: {$result["code"]}. Response Message: {$result["result"]}");
  1864.                         $purchaseNote->setHiddenDescription(json_encode($result));
  1865.                         $new_purchase->addPurchaseNote($purchaseNote);
  1866.                         
  1867.                         // mark purchase items as processed...
  1868.                         $new_purchase->setStatus(Purchase::STATUS_PROCESSED); //< this updates all expiration dates based on product purchased...
  1869.                         
  1870.                         if($product->getPaymentRate() == Product::RENEW_YEARLY) {
  1871.                             $newItem->setMonthsRenewed($item->getMonthsRenewed() + 12);
  1872.                         }
  1873.                         else {
  1874.                             $newItem->setMonthsRenewed($item->getMonthsRenewed() + 1);
  1875.                         }
  1876.                         
  1877.                         $purchase_completed true;
  1878.                     }else{
  1879.                         $purchaseNote->setDescription("An error occurred while attempting to renew your purchase. Response Code: {$result["code"]}. Response Message: {$result["result"]}");
  1880.                         $purchaseNote->setHiddenDescription(json_encode($result));
  1881.                         $new_purchase->addPurchaseNote($purchaseNote);
  1882.                         
  1883.                         // mark purchase items as failed...
  1884.                         $new_purchase->setStatus(Purchase::STATUS_FAILED); //< this updates all expiration dates based on product purchased...
  1885.                     }
  1886.                     
  1887.                     $entityManager->persist($new_purchase);
  1888.                     $entityManager->flush();
  1889.                     
  1890.                 } 
  1891.                 else{
  1892.                     $purchaseNote = new PurchaseNote();
  1893.                     $purchaseNote->setAuthorName("RCS Payment Gateway");
  1894.                     $purchaseNote->setAuthorEmail("admin@rooferscoffeeshop.com");
  1895.                     $purchaseNote->setDescription("No Payment Information On Record.");
  1896.                     $purchase->addPurchaseNote($purchaseNote);
  1897.                     $purchase->setStatus(Purchase::STATUS_FAILED);
  1898.                 }
  1899.             }
  1900.         }
  1901.         
  1902.         if($purchase_completed) {
  1903.             //send purchase email
  1904.             $message = [];
  1905.             $message[] = ["p" => "Your R-Club membership has been successfully renewed for {$new_purchase->getTotalUsd()}."];
  1906.             $message[] = ["a" => ["href" => "rooferscoffeeshop.com/account""text" => "Go to your account page to update your membership settings at any time."]];
  1907.             
  1908.             $this->addFlash("success""Payment successful. Membership has been re-activated and will now automatically renew.");
  1909.             return $this->redirectToRoute("admin-account-membership", [
  1910.                 "id" => $user_id,
  1911.             ]);
  1912.         }
  1913.         else {
  1914.             
  1915.             $user->setMember(0);
  1916.             $entityManager->persist($user);
  1917.             $entityManager->flush();
  1918.             
  1919.             $this->addFlash("danger""An error occurred when attempting to renew this user's membership. Response Code: {$result["code"]}. Response Message: {$result["result"]}");
  1920.             return $this->redirectToRoute("admin-account-membership", [
  1921.                 "id" => $user_id,
  1922.             ]);
  1923.         }
  1924.         
  1925.     
  1926.         
  1927.         
  1928.         
  1929.     }
  1930.     /**
  1931.      * @Route("/admin-account/membership", methods={"POST"}, name="post-admin-account-membership")
  1932.      */
  1933.     public function adminUpdateAccountMembership (
  1934.         Request $request,
  1935.         UserHelper $userHelper,
  1936.         OrderHelper $orderHelper
  1937.     ) {
  1938.         //Admin check
  1939.         $access false;
  1940.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  1941.             $admin $this->getUser();
  1942.             if($admin) {
  1943.                 if($admin->isAdmin()) {
  1944.                     $access true;
  1945.                 }
  1946.             }
  1947.         }
  1948.         
  1949.         if(!$access) {
  1950.             $this->addFlash("warning""This page is only accessible to site administrators.");
  1951.             return $this->redirectToRoute("/");
  1952.         }
  1953.         
  1954.         $user_id $request->get("user_id");
  1955.         $user $userHelper->getUserById($user_id);
  1956.         
  1957.         $payment $request->get("payment");
  1958.         $card $request->get("card");
  1959.         
  1960.         //expiration date
  1961.         $card["card_expires"] = $card["card_expires_month"].$card["card_expires_year"];
  1962.         
  1963.         if (!$payment || !isset($payment["terms"])) {
  1964.             $this->addFlash("warning""You must accept the terms and conditions.");
  1965.             return $this->redirectToRoute("admin-account-membership", [
  1966.                 "id" => $user_id,
  1967.              ]);
  1968.         }
  1969.         
  1970.         $result $orderHelper->generateToken(
  1971.            $payment["firstname"],
  1972.            $payment["lastname"],
  1973.            $payment["company"],
  1974.            $payment["address1"],
  1975.            $payment["address2"],
  1976.            $payment["city"],
  1977.            $payment["state"],
  1978.            $payment["zip"],
  1979.            $payment["country"],
  1980.            $payment["email"],
  1981.            $payment["phone"],
  1982.            $_SERVER["REMOTE_ADDR"],
  1983.            $card["card_number"],
  1984.            $card["card_expires"],
  1985.            $card["card_csc"]
  1986.         );
  1987.         
  1988.         if ($result["result"] == "APPROVAL" || $result["result"] == "APPROVED") {
  1989.             
  1990.             $last4 $card["card_number"];
  1991.             $last4 preg_replace("/[^0-9]/"''$last4);
  1992.             $last4 substr($last4, -4);
  1993.             
  1994.             $user->setUsermetum("has_payment_info""1");
  1995.             $user->setUsermetum("payment_first_name"$payment["firstname"]);
  1996.             $user->setUsermetum("payment_last_name"$payment["lastname"]);
  1997.             $user->setUsermetum("payment_company"$payment["company"]);
  1998.             $user->setUsermetum("payment_address_line_1"$payment["address1"]);
  1999.             $user->setUsermetum("payment_address_line_2"$payment["address2"]);
  2000.             $user->setUsermetum("payment_city"$payment["city"]);
  2001.             $user->setUsermetum("payment_state_province"$payment["state"]);
  2002.             $user->setUsermetum("payment_postal_code"$payment["zip"]);
  2003.             $user->setUsermetum("payment_country"$payment["country"]);
  2004.             $user->setUsermetum("payment_email"$payment["email"]);
  2005.             $user->setUsermetum("payment_phone"$payment["phone"]);
  2006.             $user->setUsermetum("payment_last4"$last4);
  2007.             $user->setUsermetum("payment_exp"$card["card_expires"]);
  2008.             //$user->setUsermetum("payment_cvv2", $card["card_csc"]);
  2009.             $user->setUsermetum("payment_token"$result["token"]);
  2010.             $user->setUsermetum("payment_token_response"$result["token_response"]);
  2011.             
  2012.             $manager $this->getDoctrine()->getManager();
  2013.             $manager->persist($user);
  2014.             $manager->flush();
  2015.             
  2016.             $this->addFlash("success""Membership settings updated.");
  2017.             return $this->redirectToRoute("admin-account-membership", [
  2018.                 "id" => $user_id,
  2019.              ]);
  2020.         }
  2021.         else {
  2022.             $this->addFlash("warning""Their was an error while updating your payment information. Response: {$result["result"]}");
  2023.             return $this->redirectToRoute("admin-account-membership", [
  2024.                 "id" => $user_id,
  2025.              ]);
  2026.         }
  2027.         
  2028.         
  2029.         
  2030.     }
  2031.     
  2032. }