src/Controller/RCS/AuthController.php line 124

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