src/Controller/UsersController.php line 444

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\AuctionRegister;
  4. use App\Entity\Auctions;
  5. use App\Entity\Directors;
  6. use App\Entity\Documents;
  7. use App\Entity\MetaData;
  8. use App\Entity\Preferences;
  9. use App\Entity\Transactions;
  10. use App\Entity\User;
  11. use App\Entity\Users;
  12. use App\Form\CompanyDetailsFormType;
  13. use App\Form\ContactNumberFormType;
  14. use App\Form\RegisterFormType;
  15. use App\Form\UserTypeFormType;
  16. use App\Form\VerifyFormType;
  17. use App\Services\PaginationManager;
  18. use Doctrine\DBAL\Driver\AbstractDB2Driver;
  19. use Doctrine\ORM\EntityManagerInterface;
  20. use Dompdf\Dompdf;
  21. use Dompdf\Options;
  22. use Firebase\JWT\JWT;
  23. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  24. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  25. use Symfony\Component\EventDispatcher\EventDispatcher;
  26. use Symfony\Component\HttpFoundation\JsonResponse;
  27. use Symfony\Component\HttpFoundation\Request;
  28. use Symfony\Component\HttpFoundation\RequestStack;
  29. use Symfony\Component\HttpFoundation\Response;
  30. use Symfony\Component\HttpFoundation\Session\Session;
  31. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  32. use Symfony\Component\Mailer\MailerInterface;
  33. use Symfony\Component\Mime\Email;
  34. use Symfony\Component\Routing\Annotation\Route;
  35. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  36. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  37. use Symfony\Component\Security\Core\Exception\BadCredentialsException;
  38. class UsersController extends AbstractController
  39. {
  40.     private $session;
  41.     private $params;
  42.     private $endpoint;
  43.     private $access_token;
  44.     private $basic_token;
  45.     private $decoded;
  46.     private $key 'q7vuFtP@2WSsgWtJE5X+j6kHzp&R-5qXfq5jR5';
  47.     private $em;
  48.     private $requestStack;
  49.     // Email from and to addresses
  50.     const EMAIL_FROM 'Motus Auto Auctions <info@motusaa.co.za>';
  51.     const EMAIL_TO 'karsten@nerdw.com';
  52.     // Payment gateways keys
  53.     const PRIVATE_KEY 'biGBHjWvV9STEOD2BqE3hNmMsmIdCQ88';
  54.     const API_KEY 'vtjaNBlqfneVPn28APV2Cn0jGwGIvFow';
  55.     /* Defined user types */
  56.     const USER_REGISTER_TYPE_INDIVIDUAL 1;
  57.     const USER_REGISTER_TYPE_COMPANY 2;
  58.     const USER_REGISTER_TYPE_TRUST 3;
  59.     /* Defined user types array */
  60.     public $userRegisterTypeArrayOnly = [
  61.         self::USER_REGISTER_TYPE_INDIVIDUAL,
  62.         self::USER_REGISTER_TYPE_COMPANY,
  63.         self::USER_REGISTER_TYPE_TRUST
  64.     ];
  65.     public function __construct(PaginationManager $pageManagerParameterBagInterface $paramsEntityManagerInterface $emRequestStack $requestStack) {
  66.         $this->pageManager $pageManager;
  67.         $this->session = new Session();
  68.         $this->em $em;
  69.         $this->params $params;
  70.         $this->requestStack $requestStack;
  71.     }
  72.     /**
  73.      * @Route("/registerxxx", name="registerxxx")
  74.      */
  75.     public function registerAction(Request $request): Response
  76.     {
  77.         $meta_data $this->getDoctrine()->getRepository(MetaData::class)
  78.             ->find(7);
  79. //        $this->addFlash('success', 'testing flash');
  80.         $reg = new Users();
  81.         $form $this->createForm(RegisterFormType::class,$reg);
  82.         $form->handleRequest($request);
  83.         if ($form->isSubmitted()) {
  84.             // Check if spam bot
  85.             $post $request->request->get('register_form');
  86.             if(key_exists('contact_me_by_fax_only',$post)){
  87.                 return new Response('');
  88.             }
  89.             $task $form->getData();
  90.             $entityManager $this->getDoctrine()->getManager();
  91.             $entityManager->persist($task);
  92.             $entityManager->flush();
  93.             // Customer email notification
  94. //            $body = $this->thankYouCopy($submitted_data['First Name']);
  95. //
  96. //            $email = (new Email())
  97. //                ->from('Auto Pedigree <info@motusaa.co.za>')
  98. //                ->to($submitted_data['Email'])
  99. //                ->subject('Your enquiry has been received')
  100. //                ->html($body);
  101. //
  102. //            $mailer->send($email);
  103. //
  104. //            $referer = $_SERVER['HTTP_REFERER'];
  105.             return $this->redirectToRoute('register');
  106.         }
  107.         return $this->render('frontend/register.html.twig',
  108.             [
  109.                 'meta' => $meta_data,
  110.                 'form' => $form->createView()
  111.             ]
  112.         );
  113.     }
  114.     /**
  115.      * @Route("/user/dashboard", name="user_dashboard")
  116.      */
  117.     public function userDashboardAction(Request $request): Response
  118.     {
  119.         if($this->get('security.token_storage')->getToken() == null){
  120.             $this->addFlash('danger''Your session expired due to inactivity, please login.');
  121.             return $this->redirectToRoute('user_login');
  122.         }
  123.         $auction $this->getDoctrine()->getRepository(Auctions::class)->findOneBy(['status' => 2]);
  124.         $username $this->get('security.token_storage')->getToken()->getUser()->getUserIdentifier();
  125.         $user $this->getDoctrine()->getRepository(Users::class)->findOneBy(['login' => $username]);
  126.         $auction_register $this->getDoctrine()->getRepository(AuctionRegister::class)
  127.             ->findOneBy(['auction' => $auction'user' => $user]);
  128. //        $oldToken = $this->get('security.token_storage')->getToken();
  129. //        dd($oldToken);
  130.         $documents $user->getUser()->getUsers()->getDocuments()->toArray();
  131.         $auction_endpoint $this->getParameter('app.am_auction_endpoint');
  132.         $contact_number_form $this->createContactNumberForm();
  133.         $user_type_form $this->createUserTypeForm();
  134.         $verify_form $this->verifyUserTypeForm();
  135.         $company_details_form $this->companyDetailsTypeForm();
  136.         $profile_pic '';
  137.         $docs = [];
  138.         $dob '';
  139.         // Auction Register Link
  140.         if($auction_register == null){
  141.             if($user->getUser()->getUsers()->getWallet() > 0){
  142.                 $link '<a href="#" data-toggle="modal" data-target="#register-modal">Register</a>' "\n";
  143.             } else {
  144.                 $link '<a href="#" data-toggle="modal" data-target="#ozow-modal">Register</a>' "\n";
  145.             }
  146.         } else {
  147.             $link '<span class="label label-success"><i class="fas fa-check-square"></i></span>';
  148.             $link .= '<a href="https://'$_SERVER['HTTP_HOST'] .'/bidding-number" style="margin-left: 20px" title="Print Bidding Number"><i class="fas fa-print"></i></a>';
  149.         }
  150.         // Auction View Link
  151.         if(!empty($user->getApiId())){
  152.             $view '<a href="'$auction_endpoint .'/auctions/'$auction->getApiId() .'" target="_blank" class="" data-placement="top" data-toggle="tooltip" data-original-title="view"><i class="fa fa-eye"></i></a>' "\n";
  153.         } else {
  154.             $view '<a href="https://'$_SERVER['HTTP_HOST'] .'/auction/1" target="_blank" class="" data-placement="top" data-toggle="tooltip" data-original-title="view"><i class="fa fa-eye"></i></a>';
  155.         }
  156.         // Documents logic
  157.         $profile_pic null;
  158.         foreach($documents as $document){
  159.             // Expiry status
  160.             $modified $document->getModified()->format('Y-m-d');
  161.             $expiry_date  date('Y-m-d'strtotime("+3 months"strtotime($modified)));
  162.             $docs[]['status'] = 'Valid';
  163.             if($expiry_date $modified){
  164.                 $docs[]['status'] = 'Expired';
  165.             }
  166.             // Profile picture
  167.             if($document->getDocumentType() == 'Profile Picture'){
  168.                 $profile_pic $document->getFile();
  169.             }
  170.         }
  171.         $user_reg_type $this->getUserRegisterType();
  172.         $meta_data $this->getDoctrine()->getRepository(MetaData::class)
  173.             ->find(7);
  174.         $go_to_step '';
  175.         if($user->getMobile() == null && $user->getKycVerified() == && $user->getVerified() == 0) {
  176.             $go_to_step 'poid';
  177.         }
  178.         // Proof of ID
  179.         if($user->getIdNumber() != null){
  180.             $id $user->getIdNumber();
  181.             $year substr($id,0,2);
  182.             $month substr($id,2,2);
  183.             $day substr($id,4,2);
  184.             if($year substr(date('year'),-2)){
  185.                 $year '19' $year;
  186.             } else {
  187.                 $year '20' $year;
  188.             }
  189.             $dob $year .'-'$month .'-'$day;
  190.         }
  191.         $contact_number_form->handleRequest($request);
  192.         if($contact_number_form->isSubmitted()){
  193.             $data $contact_number_form->getData();
  194.             $user->setMobile($data->getMobile());
  195.             $this->em->persist($user);
  196.             $this->em->flush();
  197.             // Proof of Address
  198.             $extension pathinfo($_FILES['poa']['name'],PATHINFO_EXTENSION);
  199.             $file $user->getId() . '-'uniqid() .'.'$extension;
  200.             $target_file __DIR__ '/../../public/uploads/user-documents/' $file;
  201.             if(move_uploaded_file($_FILES['poa']['tmp_name'], $target_file)){
  202.                 $documents = new Documents();
  203.                 $documents->setFile($file);
  204.                 $documents->setDocumentType('Proof of Address');
  205.                 $documents->setUser($user);
  206.                 $this->em->persist($documents);
  207.                 $this->em->flush();
  208.                 $go_to_step 'user_types';
  209.             }
  210.             // Proof of ID
  211.             $extension pathinfo($_FILES['identity']['name'],PATHINFO_EXTENSION);
  212.             $file $user->getId() . '-'uniqid() .'.'$extension;
  213.             $target_file __DIR__ '/../../public/uploads/user-documents/' $file;
  214.             if(move_uploaded_file($_FILES['identity']['tmp_name'], $target_file)){
  215.                 $documents = new Documents();
  216.                 $documents->setFile($file);
  217.                 $documents->setDocumentType('Proof of Identity');
  218.                 $documents->setUser($user);
  219.                 $this->em->persist($documents);
  220.                 $this->em->flush();
  221.             }
  222.             $data $request->request->get('contact_number_form');
  223.             $entityManager $this->getDoctrine()->getManager();
  224.             $entityManager->persist($user);
  225.             $entityManager->flush();
  226.             $go_to_step 'user_types';
  227.         }
  228.         foreach($documents as $document){
  229.             if($user->getKycVerified() == && $user->getVerified() == && $user->getUserType() == null && ($document->getDocumentType() == 'Proof of Address' || $document->getDocumentType() == 'Proof of Identity')){
  230.                 $go_to_step 'user_types';
  231.                 break;
  232.             }
  233.         }
  234.         // User Type
  235.         $user_type_form->handleRequest($request);
  236.         if($user_type_form->isSubmitted() || ($user->getKycVerified() == && $user->getVerified() == && $user->getUserType() == null && $user->getMobile() != null)){
  237.             if($user_type_form->isSubmitted()) {
  238.                 $user_type $request->request->get('user-type');
  239.                 $user->setUserType($user_type);
  240.                 $this->em->persist($user);
  241.                 $this->em->flush();
  242.                 if($user_type == 1) {
  243.                     $go_to_step 'proof_of_bank_account';
  244.                 } elseif($user_type == 2){
  245.                     $go_to_step 'company_reg_no';
  246.                 } elseif($user_type == 3){
  247.                     $go_to_step 'trust_details';
  248.                 }
  249.             }
  250.         }
  251.         // Proof of bank account
  252.         $poba $_FILES['file-bank-account']['name'] ?? '';
  253.         if(!empty($poba) || ($user->getKycVerified() == && $user->getVerified() == && $user->getUserType() == && $user->getMobile() != null)) {
  254.             if(!empty($poba)) {
  255.                 $extension pathinfo($pobaPATHINFO_EXTENSION);
  256.                 $file $user->getId() . '-' uniqid() . '.' $extension;
  257.                 $target_file __DIR__ '/../../public/uploads/user-documents/' $file;
  258.                 if (move_uploaded_file($_FILES['file-bank-account']['tmp_name'], $target_file)) {
  259.                     $documents = new Documents();
  260.                     $documents->setFile($file);
  261.                     $documents->setDocumentType('Proof of Bank Account');
  262.                     $documents->setUser($user);
  263.                     $this->em->persist($documents);
  264.                     $this->em->flush();
  265.                 }
  266.             }
  267.             // Get the user documents
  268.             $documents $this->getDoctrine()->getRepository(Documents::class)->findBy(['user' => $user->getId()]);
  269.             foreach($documents as $document){
  270.                 if($document->getDocumentType() == 'Proof of Bank Account'){
  271.                     $go_to_step 'terms';
  272.                     break;
  273.                 }
  274.             }
  275.         }
  276.         // Company Details
  277.         $company_reg_no $request->get('company-reg-number') ?? '';
  278.         if(!empty($company_reg_no) || ($user->getKycVerified() == && $user->getVerified() == && $user->getUserType() == && $user->getMobile() != null)) {
  279.             $go_to_step 'company_reg_no';
  280.             if(!empty($company_reg_no)) {
  281.                 $company_details_form->handleRequest($request);
  282.                 if($company_details_form->isSubmitted()) {
  283.                     $data $company_details_form->getData();
  284.                 }
  285.             }
  286.             $documents $user->getUser()->getUsers()->getDocuments()->toArray();
  287.             foreach($documents as $document){
  288.                 if($document->getDocumentType() == 'Proof of Bank Account'){
  289.                     $go_to_step 'terms';
  290.                     break;
  291.                 }
  292.             }
  293.         }
  294.         $verify_form->handleRequest($request);
  295.         if($verify_form->isSubmitted()) {
  296.             $data $verify_form->getData();
  297.             $user->setVerified(1);
  298.             $user->setTerms(1);
  299.             $this->em->persist($user);
  300.             $this->em->flush();
  301.         }
  302.         return $this->render('frontend/user-dashboard.html.twig',
  303.             [
  304.                 'meta' => $meta_data,
  305.                 'user' => $user,
  306.                 'documents' => $documents,
  307.                 'profile_pic' => $profile_pic,
  308.                 'docs' => $docs,
  309.                 'auction' => $auction,
  310.                 'link' => $link,
  311.                 'view' => $view,
  312.                 'user_reg_type' => $user_reg_type,
  313.                 'contactNumberForm' => $contact_number_form->createView(),
  314.                 'go_to_step' => $go_to_step,
  315.                 'userTypeForm' => $user_type_form->createView(),
  316.                 'verifyFormType' => $verify_form->createView(),
  317.                 'dob' => $dob,
  318.                 'user_id' => $user->getId(),
  319.                 'company_details_form' => $company_details_form->createView(),
  320.                 'trustees' => $user->getDirectors()->toArray(),
  321.             ]
  322.         );
  323.     }
  324.     /**
  325.      * @Route("/validate-email", name="validate_email")
  326.      */
  327.     public function validateEmailAction(Request $requestEntityManagerInterface $entityManager): Response
  328.     {
  329.         $email $this->getDoctrine()->getRepository(Users::class)->findOneBy(['login' => $request->get('email')]);
  330.         $response 'false';
  331.         if($email == null){
  332.             $response 'true';
  333.         }
  334.         return new Response($response);
  335.     }
  336.     /**
  337.      * @Route("/preferences", name="preferences")
  338.      */
  339.     public function preferencesAction(Request $requestEntityManagerInterface $entityManager): Response
  340.     {
  341.         $email $this->getDoctrine()->getRepository(Preferences::class)->findAll();
  342.         $json = [];
  343.         foreach($email as $mail){
  344.             $json[] = [
  345.                 'id' => $mail->getId(),
  346.                 'text' => $mail->getPreference()
  347.             ];
  348.         }
  349.         return new JsonResponse($json);
  350.     }
  351.     private function amCreateCustomer()
  352.     {
  353.         $endpoint $this->getParameter('app.am_endpoint');
  354.         $basic_token $this->getParameter('app.am_basic_token');
  355.         $user $this->get('security.token_storage')->getToken()->getUser()->getUserIdentifier();
  356.         $user $this->getDoctrine()->getRepository(Users::class)->findOneBy(['login' => $user]);
  357.         $email $user->getLogin();
  358.         $first_name $user->getFirstName();
  359.         $last_name $user->getLastName();
  360.         $curl curl_init();
  361.         curl_setopt_array($curl, array(
  362.             CURLOPT_URL => $endpoint '/v5/integration/customer',
  363.             CURLOPT_RETURNTRANSFER => true,
  364.             CURLOPT_ENCODING => '',
  365.             CURLOPT_MAXREDIRS => 10,
  366.             CURLOPT_TIMEOUT => 0,
  367.             CURLOPT_FOLLOWLOCATION => true,
  368.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  369.             CURLOPT_CUSTOMREQUEST => 'POST',
  370.             CURLOPT_POSTFIELDS =>'{
  371.               "email_address": "'$email .'",
  372.               "is_external_record": true,
  373.               "integration_id": "'$user->getId() .'",
  374.               "given_name": "'$first_name .'",
  375.               "family_name": "'$last_name .'"
  376.             }',
  377.             CURLOPT_HTTPHEADER => array(
  378.                 'Authorization: Basic ' $basic_token,
  379.                 'Content-Type: application/json'
  380.             ),
  381.         ));
  382.         $response curl_exec($curl);
  383.         curl_close($curl);
  384.         $json json_decode($responsetrue);
  385.         $entityManager $this->getDoctrine()->getManager();
  386.         $user_id $user->getId();
  387.         $user $entityManager->getRepository(Users::class)->find($user_id);
  388.         $user->setApiId($json['response']['row_id']);
  389.         $entityManager->persist($user);
  390.         $entityManager->flush();
  391.     }
  392.     /**
  393.      * @Route("/auction-register", name="auction_register")
  394.      */
  395.     public function auctionRegisterAction(EntityManagerInterface $entityManager): Response
  396.     {
  397.         $auction_register = new AuctionRegister();
  398.         $auction $this->getDoctrine()->getRepository(Auctions::class)->findOneBy(['status' => 1]);
  399.         $user $this->get('security.token_storage')->getToken()->getUser()->getUserIdentifier();
  400.         $user $this->getDoctrine()->getRepository(Users::class)->findOneBy(['login' => $user]);
  401.         $auction_register->setUser($user);
  402.         $auction_register->setAuction($auction);
  403.         $entityManager->persist($auction_register);
  404.         $entityManager->flush();
  405.         // Get the auction registration id
  406.         $auction_reg $this->getDoctrine()->getRepository(AuctionRegister::class)
  407.             ->findOneBy(['auction' => $auction'user' => $user]);
  408.         if(empty($user->getApiId())){
  409.             $this->amCreateCustomer();
  410.         }
  411.         $this->amAuctionRegistration($user->getApiId(),$user->getId(),$auction->getApiId(),$auction->getId(),$auction->getBiddingPrefix(), $auction_reg->getId());
  412.         $endpoint $this->getParameter('app.am_auction_endpoint');
  413.         $view '<a href="'$endpoint .'/auctions/'$auction->getApiId() .'" target="_blank" class="" data-placement="top" data-toggle="tooltip" data-original-title="view"><i class="fa fa-eye"></i></a>' "\n";
  414.         $link '<span class="label label-success"><i class="fas fa-check-square"></i></span>';
  415.         $link .= '<a href="https://'$_SERVER['HTTP_HOST'] .'/bidding-number/'$user->getId() .'" target="_blank" style="margin-left: 20px" title="Print Bidding Number"><i class="fas fa-print"></i></a>';
  416.         return new JsonResponse([
  417.             'view' => $view,
  418.             'link' => $link,
  419.             'auction' => $auction->getId()
  420.         ]);
  421.     }
  422.     public function amAuctionRegistration($user_id$maa_user_id$auction_id$maa_auction_id$bidding_prefix$reg_id){
  423.         $endpoint $this->getParameter('app.am_endpoint');
  424.         $token $this->getParameter('app.am_access_token');
  425.         $url $endpoint '/v5/admin/customer/'$user_id .'/auction-registration';
  426.         $curl curl_init();
  427.         $post_data = [
  428.             'auction_id' => (string) $auction_id,
  429.             'approved' => 1,
  430.             'paddle' => $bidding_prefix $maa_user_id
  431.         ];
  432.         curl_setopt_array($curl, array(
  433.             CURLOPT_URL => $url,
  434.             CURLOPT_RETURNTRANSFER => true,
  435.             CURLOPT_ENCODING => '',
  436.             CURLOPT_MAXREDIRS => 10,
  437.             CURLOPT_TIMEOUT => 0,
  438.             CURLOPT_FOLLOWLOCATION => true,
  439.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  440.             CURLOPT_CUSTOMREQUEST => 'POST',
  441.             CURLOPT_POSTFIELDS => json_encode($post_data),
  442.             CURLOPT_HTTPHEADER => array(
  443.                 'Authorization: Bearer '$token,
  444.                 'Content-Type: application/json'
  445.             ),
  446.         ));
  447.         $response curl_exec($curl);
  448.         // $response
  449.         $json json_decode($responsetrue);
  450.         dump($json);
  451.         $entityManager $this->getDoctrine()->getManager();
  452.         $auction_reg $entityManager->getRepository(AuctionRegister::class)->find($reg_id);
  453.         dump($json['response']['row_id']);
  454.         $auction_reg->setApiId($json['response']['row_id']);
  455.         $entityManager->flush();
  456.         curl_close($curl);
  457.     }
  458.     /**
  459.      * @Route("/bidding-number", name="bidding_number")
  460.      */
  461.     public function generatePdf()
  462.     {
  463.         if(!empty($this->get('security.token_storage')->getToken()->getUser()->getUserIdentifier())) {
  464.             $user $this->get('security.token_storage')->getToken()->getUser()->getUserIdentifier();
  465.             $user $this->getDoctrine()->getRepository(Users::class)->findOneBy(['login' => $user]);
  466.             $auction $this->getDoctrine()->getRepository(Auctions::class)
  467.                 ->findOneBy(['status' => 2]);
  468.             $image $this->display(__DIR__ '/../../public/images/logo-pdf.png');
  469.             // Configure Dompdf according to your needs
  470.             $pdfOptions = new Options();
  471.             $pdfOptions->set('isRemoteEnabled'true);
  472.             $pdfOptions->set('defaultFont''Arial');
  473.             // Instantiate Dompdf with our options
  474.             $dompdf = new Dompdf($pdfOptions);
  475.             // Retrieve the HTML generated in our twig file
  476.             $html $this->renderView('frontend/bidding-number.html.twig', [
  477.                 'title' => "Motus Auto Auctions",
  478.                 'auction' => $auction,
  479.                 'user' => $user,
  480.                 'logo' => $image,
  481.             ]);
  482.             // Load HTML to Dompdf
  483.             $dompdf->loadHtml($html);
  484.             // (Optional) Setup the paper size and orientation 'portrait' or 'portrait'
  485.             $dompdf->setPaper('A4''portrait');
  486.             // Render the HTML as PDF
  487.             $dompdf->render();
  488.             // Output the generated PDF to Browser (force download)
  489.             $dompdf->stream('bidding-number-' $user->getId() . '.pdf', [
  490.                 "Attachment" => true
  491.             ]);
  492.             return new Response(''200, [
  493.                 'Content-Type' => 'application/pdf',
  494.             ]);
  495.         }
  496.         return new Response('Please login');
  497.     }
  498.     public static function display($path)
  499.     {
  500.         $image base64_encode(file_get_contents($path));
  501.         return "data:image/png;base64,$image";
  502.     }
  503.     /**
  504.      * @Route("/contactable-verified", name="contactable_verified")
  505.      */
  506.     public function contactableVerified()
  507.     {
  508.         $user $this->get('security.token_storage')->getToken()->getUser()->getUserIdentifier();
  509.         $user $this->getDoctrine()->getRepository(Users::class)->findBy(['login' => $user]);
  510.         return new Response($user[0]->getKycVerified());
  511.     }
  512.     /**
  513.      * @Route("/kyc", name="kyc")
  514.      */
  515.     public function kycAction()
  516.     {
  517.         $json file_get_contents('php://input');
  518.         $request json_decode($jsontrue);
  519.         // Sanitise data
  520.         if($request['action'] == 'get'){
  521.             $username filter_var($request['username'], FILTER_SANITIZE_STRING);
  522.             $password filter_var($request['password'], FILTER_SANITIZE_STRING);
  523.             $organisation filter_var($request['organisation_code'], FILTER_SANITIZE_STRING);
  524.             // Get JWT Token
  525.             return new JsonResponse($this->getJwtToken($username$password$organisation));
  526.         }
  527.         // Validate JWT Token & save data
  528.         if($request['action'] == 'put'){
  529.             $this->validJWT($request);
  530.         }
  531.         return new Response('');
  532.     }
  533.     // sends signed token in email to user if the user exists
  534.     private function getJwtToken($username$password$organisation){
  535.         // check if the user exists
  536.         if($api_user $this->getApiUser($username$password$organisation)){
  537.             // generate JSON web token and store as variable
  538.             $token $this->genJWT($username);
  539.             $response = [
  540.                 'message' => 'Success',
  541.                 'jwt_token' => $token
  542.             ];
  543.             return $response;
  544.         } else {
  545.             $response = [
  546.                 'message' => 'Authentication failed'
  547.             ];
  548.             return $response;
  549.         }
  550.     }
  551.     private function genJWT($username){
  552.         $payload = [
  553.             "username" => $username,
  554.             // Expires
  555.             "exp" => time() + 10 60
  556.         ];
  557.         /**
  558.          * IMPORTANT:
  559.          * You must specify supported algorithms for your application. See
  560.          * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
  561.          * for a list of spec-compliant algorithms.
  562.          */
  563.         return JWT::encode($payload$this->key);
  564.     }
  565.     private function getApiUser($username$password$organisation)
  566.     {
  567.         $api_user = [
  568.             'username' => 'contactable@nerdware',
  569.             'password' => 'Jes#%3eTxre5wXD&^G^7Pc@8PCbuAwv&q=bD=Q',
  570.             'organisation_code' => 'contactable'
  571.         ];
  572.         if($username == $api_user['username'] && $password == $api_user['password'] && $organisation == $api_user['organisation_code']){
  573.             $user = [
  574.                 'username' => $api_user['username'],
  575.                 'password' => $api_user['password'],
  576.                 'organisation_code' => $api_user['organisation_code']
  577.             ];
  578.             return $user;
  579.         }
  580.         return false;
  581.     }
  582.     public function validJWT($request){
  583.         // Validate the token
  584.         $tokenVal $this->validToken($request);
  585.         // If the token is valid
  586.         if($tokenVal['0']){
  587.             if($request['data']['userId'] > 0) {
  588.                 $user_id $request['data']['userId'];
  589.                 $id_no $request['data']['identityNumber'];
  590.                 $year substr(0,2,$id_no);
  591.                 $month substr(2,2,$id_no);
  592.                 $day substr(4,2,$id_no);
  593.                 $dob $year .'-'$month .'-'$day;
  594.                 $users $this->getDoctrine()->getRepository(Users::class)->find($user_id);
  595.                 // Update user acc with contactable data
  596.                 $users->setIdNumber($id_no);
  597.                 $users->getDob($dob);
  598.                 $users->setFirstName($request['data']['firstName']);
  599.                 $users->setLastName($request['data']['lastName']);
  600.                 $users->setAddress1($request['data']['address1']);
  601.                 $users->setAddress2($request['data']['address2']);
  602.                 $users->setAddress3($request['data']['address3']);
  603.                 $users->setKycVerified(1);
  604.                 $users->setVerified(0);
  605.                 $_SESSION["customer-name"] = '';
  606.                 if (empty($request['data']['firstName'])) {
  607.                     $_SESSION["customer-name"] = $request['data']['firstName'] . ' ' $request['data']['lastName'];
  608.                 }
  609.                 if (count($request) > 1) {
  610.                     $this->em->persist($users);
  611.                     $this->em->flush();
  612.                     // Update user acc with contactable data
  613.                     $response = [
  614.                         'message' => 'Authenticated',
  615.                         'jwt_token' => $request['jwt_token'],
  616.                         'username' => $this->decoded->username,
  617.                         'expires' => date('Y-m-d H;i:s'$this->decoded->exp),
  618.                         'user_data' => $request['data']['userId']
  619.                     ];
  620.                     if (!empty($request['data']['auditCertificatePdfBase64']) || !empty($request['data']['selfieBase64'])) {
  621.                         if (!empty($request['data']['auditCertificatePdfBase64'])) {
  622.                             $this->zip $request['data']['auditCertificatePdfBase64'];
  623.                             $this->getFilesFromString($request['data']['userId'], $request);
  624.                         }
  625.                         if (!empty($request['data']['selfieBase64'])) {
  626.                             $file $request['data']['userId'] . '_' mt_rand() . '.png';
  627.                             $base64_string $request['data']['selfieBase64'];
  628.                             $output_file __DIR__ '/../../public/uploads/user-documents/' $file;
  629.                             $this->base64ToImage($base64_string$output_file);
  630.                             $docs = new Documents();
  631.                             $docs->setUser($users);
  632.                             $docs->setDocumentType('Profile Picture');
  633.                             $docs->setFile($file);
  634.                             $this->em->persist($docs);
  635.                             $this->em->flush();
  636.                         }
  637.                     }
  638.                     echo json_encode($response);
  639.                 } else {
  640.                     $response = [
  641.                         'message' => 'Error: Insufficient data.',
  642.                         'jwt_token' => $this->token
  643.                     ];
  644.                     echo json_encode($response);
  645.                 }
  646.             } else {
  647.                 $response = [
  648.                     'message' => 'Invalid user'
  649.                 ];
  650.             }
  651.         } else {
  652.             $response = [
  653.                 'message' => 'Authentication failed'
  654.             ];
  655.             echo json_encode($response);
  656.         }
  657.     }
  658.     // Validates a given JWT from the user email
  659.     private function validToken($response) {
  660.         $res = [false''];
  661.         // using a try and catch to verify
  662.         try {
  663.             $this->decoded JWT::decode($response['jwt_token'], $this->key, array('HS256'));
  664.             $res['0'] = true;
  665.             $res['1'] = (array) $this->decoded;
  666.             return $res;
  667.         } catch (Exception $e){
  668.             throw new BadCredentialsException($e->getMessage(), 0$e);
  669.         }
  670.     }
  671.     private function getFilesFromString($user_id$api_response)
  672.     {
  673.         $tmp $user_id mt_rand();
  674.         file_put_contents(__DIR__ '/../../public/uploads/user-documents/'$tmp '.log'$api_response['data']['auditCertificatePdfBase64']);
  675.         $base64_string base64_decode(file_get_contents(__DIR__ '/../../public/uploads/user-documents/'$tmp '.log'));
  676.         $fp fopen(__DIR__ '/../../public/uploads/user-documents/'$tmp .'.zip'"w+");
  677.         fwrite($fp$base64_string);
  678.         $zip = new \ZipArchive();
  679.         $zip_path __DIR__ '/../../public/uploads/user-documents/'$tmp .'.zip';
  680.         if($zip->open($zip_path) === TRUE){
  681.             $this->files = [];
  682.             for($i 0$i $zip->numFiles$i++){
  683.                 $filename $zip->getNameIndex($i);
  684.                 $ext pathinfo($filenamePATHINFO_EXTENSION);
  685.                 $new $api_response['data']['userId'] . '_'mt_rand() .'.'$ext;
  686.                 $this->files[] = $new;
  687.                 $zip->renameName($filename,$new);
  688.                 if($i == 0){
  689.                     $document_type 'Validation Certificate';
  690.                 } else {
  691.                     $document_type 'Livliness Test';
  692.                 }
  693.                 $docs = new Documents();
  694.                 $user $this->getDoctrine()->getRepository(Users::class)->find($user_id);
  695.                 $docs->setDocumentType($document_type);
  696.                 $docs->setFile($new);
  697.                 $docs->setUser($user);
  698.                 $this->em->persist($docs);
  699.                 $this->em->flush();
  700.             }
  701.             $zip->extractTo(__DIR__ "/../../public/uploads/user-documents/");
  702.             $zip->close();
  703.         } else {
  704.             return false;
  705.         }
  706.         if($zip->open($zip_path) === TRUE){
  707.             $zip->extractTo(__DIR__ "/../../public/uploads/user-documents/");
  708.             $zip->close();
  709.             return true;
  710.         } else {
  711.             return false;
  712.         }
  713.     }
  714.     private function base64ToImage($base64_string$output_file)
  715.     {
  716.         $file fopen($output_file"wb");
  717.         $data explode(','$base64_string);
  718.         fwrite($filebase64_decode($base64_string));
  719.         fclose($file);
  720.         return $output_file;
  721.     }
  722.     /* Set user register type value or label */
  723.     public function getUserRegisterType()
  724.     {
  725.         return $userRegisterTypeValues = [
  726.             self::USER_REGISTER_TYPE_INDIVIDUAL => 'Individual',
  727.             self::USER_REGISTER_TYPE_COMPANY => 'Company',
  728.             self::USER_REGISTER_TYPE_TRUST => 'Trust',
  729.         ];
  730.     }
  731.     protected function createContactNumberForm()
  732.     {
  733.         $users = new Users();
  734.         return  $this->createForm(ContactNumberFormType::class,
  735.             $users,
  736.             [
  737.                 'method' => 'POST',
  738.                 'action' => $this->generateUrl('user_dashboard')
  739.             ]
  740.         );
  741.     }
  742.     protected function createUserTypeForm()
  743.     {
  744.         $users = new Users();
  745.         return  $this->createForm(UserTypeFormType::class,
  746.             $users,
  747.             [
  748.                 'method' => 'POST',
  749.                 'action' => $this->generateUrl('user_dashboard')
  750.             ]
  751.         );
  752.     }
  753.     protected function verifyUserTypeForm()
  754.     {
  755.         $users = new Users();
  756.         return  $this->createForm(VerifyFormType::class,
  757.             $users,
  758.             [
  759.                 'method' => 'POST',
  760.                 'action' => $this->generateUrl('user_dashboard')
  761.             ]
  762.         );
  763.     }
  764.     protected function companyDetailsTypeForm()
  765.     {
  766.         $users = new Users();
  767.         return  $this->createForm(CompanyDetailsFormType::class,
  768.             $users,
  769.             [
  770.                 'method' => 'POST',
  771.                 'action' => $this->generateUrl('user_dashboard')
  772.             ]
  773.         );
  774.     }
  775.     /**
  776.      * @Route("/update-personal-details", name="update_personal_details")
  777.      */
  778.     public function updatePersonalDetailsAction(Request $requestTokenStorageInterface $tokenStorage)
  779.     {
  780.         $data $request->request;
  781.         $message '';
  782.         $is_valid 0;
  783.         if(!empty($data->get('value'))) {
  784.             $users $this->getDoctrine()->getRepository(Users::class)->find($data->get('user_id'));
  785.             if($data->get('key') == 'Contact number'){
  786.                 $users->setMobile($data->get('value'));
  787.                 $message '<b><i class="fas fa-check-circle"></i> REQUEST SENT</b><br>Contact number updated';
  788.                 $is_valid 1;
  789.             } elseif($data->get('key') == 'Email address') {
  790.                 $user $this->getDoctrine()->getRepository(User::class)->find($users->getUser());
  791.                 $users->setLogin($data->get('value'));
  792.                 $user->setUsername($data->get('value'));
  793.                 $user->setUsers($users);
  794.                 $this->em->persist($user);
  795.                 $this->em->flush();
  796.                 $request->getSession()->invalidate();
  797.                 $tokenStorage->setToken(null);
  798.                 $this->addFlash('success''<b><i class="fas fa-check-circle"></i> Email address updated</b><br>Please login using your new email address');
  799.                 return new JsonResponse([
  800.                     'value' => $data->get('value'),
  801.                     'message' => $message,
  802.                     'is_valid' => 1,
  803.                 ]);
  804.             }
  805.             $this->em->persist($users);
  806.             $this->em->flush();
  807.         } else {
  808.             $message $data->get('key') . ' cannot be empty!';
  809.             $is_valid 0;
  810.         }
  811.         return new JsonResponse([
  812.             'value' => $data->get('value'),
  813.             'message' => $message,
  814.             'is_valid' => $is_valid,
  815.         ]);
  816.     }
  817.     /**
  818.      * @Route("/update-trust-contact-details", name="update_trust_contact_details")
  819.      */
  820.     public function updateTrustDetailsAction(Request $requestTokenStorageInterface $tokenStorage)
  821.     {
  822.         $data $request->request;
  823.         $message '';
  824.         $is_valid 0;
  825.         if(!empty($data->get('value'))) {
  826.             $users $this->getDoctrine()->getRepository(Users::class)->find($data->get('user_id'));
  827.             if($data->get('key') == 'Contact Number'){
  828.                 $users->setTrustContactNumber($data->get('value'));
  829.                 $this->em->persist($users);
  830.                 $this->em->flush();
  831.                 $message '<b><i class="fas fa-check-circle"></i> Request Sent</b><br>Trust contact number updated';
  832.                 return new JsonResponse([
  833.                     'value' => $data->get('value'),
  834.                     'message' => $message,
  835.                     'is_valid' => 1,
  836.                 ]);
  837.             } elseif($data->get('key') == 'Email address') {
  838.                 $users->setTrustEmail($data->get('value'));
  839.                 $this->em->persist($users);
  840.                 $this->em->flush();
  841.                 $message '<b><i class="fas fa-check-circle"></i> Request Sent</b><br>Trust email address updated.';
  842.                 return new JsonResponse([
  843.                     'value' => $data->get('value'),
  844.                     'message' => $message,
  845.                     'is_valid' => 1,
  846.                 ]);
  847.             }
  848.         } else {
  849.             $message $data->get('key') . ' cannot be empty!';
  850.             $is_valid 0;
  851.         }
  852.         return new JsonResponse([
  853.             'value' => $data->get('value'),
  854.             'message' => $message,
  855.             'is_valid' => $is_valid,
  856.         ]);
  857.     }
  858.     /**
  859.      * @Route("/get-cipc-report", name="get_cipc_report")
  860.      */
  861.     public function getCipcBasicReport(Request $request)
  862.     {
  863.         $company_reg_no $request->get('company_reg_no');
  864.         // Get JWT
  865.         $parameters = [
  866.             'Username' => 'motusactions@contactable',
  867.             'Password' => 'ad641fd2-6102-42cb-9ec4-3af89ef47d64!X',
  868.             'Organization_code' => 'motus_auctions'
  869.         ];
  870.         $endpoint curl_init('https://oem-gway-kyccompany-integrate.kyc.business/1.0.0/integrationgateway/post_BearerToken');
  871.         curl_setopt($endpointCURLOPT_POSTFIELDS$parameters);
  872.         curl_setopt($endpointCURLOPT_RETURNTRANSFERtrue);
  873.         $response curl_exec($endpoint);
  874.         curl_close($endpoint);
  875.         // Response
  876.         $json json_decode($response);
  877.         // DEFINE our cipher
  878.         define('AES_256_CBC''aes-256-cbc');
  879.         // Generate a 256-bit encryption key
  880.         // This should be stored somewhere instead of recreating it each time
  881.         $encryption_key 'gkmxhsKfZUA7tEqoFJhiVoOrcykGzy8wAiQdsmVbhaKE7iaCvTr3ta04Vfre4n7DdnazN6OsJNkpzxAbau3StM5aNaV936n4cS1ORt7g5aB';
  882.         // Generate an initialization vector
  883.         // This *MUST* be available for decryption as well
  884.         //$iv = 'UHLbqQYb97LoyM2FobOtoGTx6HGrdQ69Gf467aRtFu3fCnK2w2V5W4';
  885.         $iv 'UHLbqQYb97LoyM2F';
  886.         // Encrypt $data using aes-256-cbc cipher with the given encryption key and
  887.         // our initialization vector. The 0 gives us the default options, but can
  888.         // be changed to OPENSSL_RAW_DATA or OPENSSL_ZERO_PADDING
  889.         $encrypted openssl_encrypt($company_reg_noAES_256_CBC$encryption_key0$iv);
  890.         $token $json->response_object->jwt_token;
  891.         $curl curl_init();
  892.         curl_setopt_array($curl, array(
  893.             CURLOPT_URL => 'https://oem-gway-kyccompany-integrate.kyc.business/1.0.0/IntegrationGateway/RetrieveBasicCICPReport',
  894.             CURLOPT_RETURNTRANSFER => true,
  895.             CURLOPT_ENCODING => '',
  896.             CURLOPT_MAXREDIRS => 10,
  897.             CURLOPT_TIMEOUT => 0,
  898.             CURLOPT_FOLLOWLOCATION => true,
  899.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  900.             CURLOPT_CUSTOMREQUEST => 'POST',
  901.             CURLOPT_POSTFIELDS =>'{
  902.             "company_registration_number" : "'$encrypted .'"
  903.         }',
  904.             CURLOPT_HTTPHEADER => array(
  905.                 'Authorization: Bearer '$token,
  906.                 'Content-Type: application/json'
  907.             ),
  908.         ));
  909.         $response curl_exec($curl);
  910.         // $response
  911.         $json json_decode($response);
  912.         $decrypted openssl_decrypt($json->response_object->encrypted_responseAES_256_CBC$encryption_key0$iv);
  913.         $array json_decode($decryptedtrue);
  914.         // Save to file
  915.         $user_id $request->get('user_id');
  916.         $user $this->getDoctrine()->getRepository(Users::class)->find($user_id);
  917.         $rand $user_id .'_'mt_rand();
  918.         $fp fopen(__DIR__ '/../../public/uploads/user-documents/cipc/'$rand .'.txt'"w+");
  919.         fwrite($fpserialize($array));
  920.         fclose($fp);
  921.         $user->setcompany_cicp_file($rand '.txt');
  922.         $this->em->persist($user);
  923.         $this->em->flush();
  924.         // Business Info
  925.         $company_name $array['commercial']['commercialBusinessInformation']['commercialName'];
  926.         $company_reg_no $array['commercial']['commercialBusinessInformation']['registrationNo'];
  927.         $company_financial_year_end $array['commercial']['commercialBusinessInformation']['financialYearEnd'];
  928.         $company_start_date $array['commercial']['commercialBusinessInformation']['businessStartDate'];
  929.         $company_tax_no $array['commercial']['commercialBusinessInformation']['taxNo'];
  930.         $company_type $array['commercial']['commercialBusinessInformation']['commercialType'];
  931.         $company_vat_no $array['commercial']['commercialBusinessInformation']['vatNo'];
  932.         // Addresses
  933.         $address_array $this->arraySortByColumn($array['commercial']['commercialAddressInformation'], 'lastUpdatedDate');
  934.         $company_physical_address $address_array[0]['address1'] .' '$address_array[0]['address2'] .' '$address_array[0]['address3'] .' '$address_array[0]['address4'] .' '$address_array[0]['postalCode'];
  935.         $company_postal_address $address_array[0]['address1'] .' '$address_array[0]['address2'] .' '$address_array[0]['address3'] .' '$address_array[0]['address4'] .' '$address_array[0]['postalCode'];
  936.         // Directors
  937.         $directors '';
  938.         $director_count 0;
  939.         $hidden_fields '';
  940.         foreach($array['commercial']['commercialDirectorInformation'] as $director){
  941.             $director_count++;
  942.             $directors .= '<div class="col-4 d-flex  p-b15">
  943.                         <div class="file btn btn-primary w-100 mr-1" style="position: relative; overflow: hidden;">
  944.                             <div class="call_back_error_msg hidden_msg" id="error_director_proof_of_address_'$director_count .'" style="color: #d98f77">
  945.                                 Required Field
  946.                             </div>
  947.                             <span id="string-director-poa'$director_count .'">Director Proof of Address</span>
  948.                             <input type="file" name="file-director-poa[]" id="file-director-poa'$director_count .'" style="position: absolute; font-size: 50px; opacity: 0; right: 0; top: 0;" />
  949.                         </div>
  950.                         <button type="button" data-html="true" class="btn-tooltip" data-toggle="tooltip" data-placement="top" title="Upload a certified copy of the director\'s proof of address">
  951.                             <i class="fas fa-info-circle"></i>
  952.                         </button>
  953.                     </div>
  954.                     <div class="col-4 d-flex  p-b15">
  955.                         <div class="file btn btn-primary w-100 mr-1" style="position: relative; overflow: hidden;">
  956.                             <div class="call_back_error_msg hidden_msg" id="error_director_id_'$director_count .'" style="color: #d98f77">
  957.                                 Required Field
  958.                             </div>
  959.                             <span id="string-director-id'$director_count .'">Director Identity Document</span>
  960.                             <input type="file" name="file-director-id[]" id="file-director-id'$director_count .'" style="position: absolute; font-size: 50px; opacity: 0; right: 0; top: 0;" />
  961.                         </div>
  962.                         <button type="button" data-html="true" class="btn-tooltip" data-toggle="tooltip" data-placement="top" title="Please upload a copy of the director\'s ID document">
  963.                             <i class="fas fa-info-circle"></i>
  964.                         </button>
  965.                     </div>';
  966.             $hidden_fields .= '<input type="hidden" name="director_first_name[]" value="'$director['firstName'] .'">' "\n";
  967.             $hidden_fields .= '<input type="hidden" name="director_last_name[]" value="'$director['surname'] .'">' "\n";
  968.             $hidden_fields .= '<input type="hidden" name="director_address[]" value="'$director['physicalAddress'] .'">' "\n";
  969.             $hidden_fields .= '<input type="hidden" name="director_id[]" value="'$director['idNo'] .'">' "\n";
  970.         }
  971.         $company_arr = [
  972.             $company_name,
  973.             $company_reg_no,
  974.             $company_start_date,
  975.             $company_financial_year_end,
  976.             $company_type,
  977.             $company_tax_no,
  978.             $company_physical_address,
  979.             $company_postal_address,
  980.             $company_vat_no,
  981.             stripslashes($directors),
  982.             $director_count,
  983.             $hidden_fields
  984.         ];
  985.         return new JsonResponse($company_arr);
  986.     }
  987.     private function arraySortByColumn(&$array$column$direction SORT_DESC)
  988.     {
  989.         $reference_array = [];
  990.         foreach($array as $key => $row){
  991.             $reference_array[$key] = $row[$column];
  992.         }
  993.         array_multisort($reference_array$direction$array);
  994.         return $array;
  995.     }
  996.     /**
  997.      * @Route("/update-company-details", name="update_company_details")
  998.      */
  999.     public function updateCompanyDetails(Request $request)
  1000.     {
  1001.         $files $request->files->keys();
  1002.         $username $this->get('security.token_storage')->getToken()->getUser()->getUserIdentifier();
  1003.         $user $this->getDoctrine()->getRepository(Users::class)->findOneBy(['login' => $username]);
  1004.         $user_id $user->getId();
  1005.         $response false;
  1006.         // Upload files
  1007.         foreach($files as $file_name) {
  1008.             // Directors files are arrays
  1009.             if($file_name == 'file-director-poa' || $file_name == 'file-director-id'){
  1010.                 for($i 0$i count($_FILES[$file_name]['name']); $i++){
  1011.                     $extension pathinfo($_FILES[$file_name]['name'][$i], PATHINFO_EXTENSION);
  1012.                     $file $user_id '-' uniqid() . '.' $extension;
  1013.                     $target_file __DIR__ '/../../public/uploads/user-documents/' $file;
  1014.                     if (move_uploaded_file($_FILES[$file_name]['tmp_name'][$i], $target_file)) {
  1015.                         $user $this->getDoctrine()->getRepository(Users::class)->find($user_id);
  1016.                         $documents = new Documents();
  1017.                         $documents->setFile($file);
  1018.                         $documents->setDocumentType($file_name);
  1019.                         $documents->setUser($user);
  1020.                         $this->em->persist($documents);
  1021.                         $this->em->flush();
  1022.                         $response true;
  1023.                     }
  1024.                 }
  1025.             } else {
  1026.                 $extension $request->files->get($file_name)->guessExtension();
  1027.                 $file $user_id '-' uniqid() . '.' $extension;
  1028.                 $target_file __DIR__ '/../../public/uploads/user-documents/' $file;
  1029.                 if (move_uploaded_file($_FILES[$file_name]['tmp_name'], $target_file)) {
  1030.                     $user $this->getDoctrine()->getRepository(Users::class)->find($user_id);
  1031.                     $documents = new Documents();
  1032.                     $documents->setFile($file);
  1033.                     $documents->setDocumentType($file_name);
  1034.                     $documents->setUser($user);
  1035.                     $this->em->persist($documents);
  1036.                     $this->em->flush();
  1037.                     $response true;
  1038.                 }
  1039.             }
  1040.         }
  1041.         // Update company details
  1042.         $data $request->request->get('company_details_form');
  1043.         if(is_array($data) && count($data) > 0){
  1044.             // Company data
  1045.             $user->setCompanyName($data['companyName']);
  1046.             $user->setCompanyRegNo($data['companyRegNo']);
  1047.             $user->setCompanyStartDate($data['companyStartDate']);
  1048.             $user->setCompanyFinancialYearEnd($data['companyFinancialYearEnd']);
  1049.             $user->setCompanyType($data['companyType']);
  1050.             $user->setCompanyTaxNo($data['companyTaxNo']);
  1051.             $user->setCompanyPhysicalAddress($data['companyPhysicalAddress']);
  1052.             $user->setCompanyPostalAddress($data['companyPostalAddress']);
  1053.             $user->setCompanyVatNo($data['companyVatNo']);
  1054.             $this->em->persist($user);
  1055.             $this->em->flush();
  1056.             $response true;
  1057.         }
  1058.         $data['director_first_name'] = $request->request->get('director_first_name');
  1059.         $data['director_last_name'] = $request->request->get('director_last_name');
  1060.         $data['director_address'] = $request->request->get('director_address');
  1061.         $data['director_id'] = $request->request->get('director_id');
  1062.         if(is_array($data['director_first_name']) && count($data['director_first_name']) > 0){
  1063.             // Directors data
  1064.             for($i=0;$i<count($data['director_first_name']);$i++){
  1065.                 $director = new Directors();
  1066.                 $director->setUser($user);
  1067.                 $director->setFirstName($data['director_first_name'][$i]);
  1068.                 $director->setLastName($data['director_last_name'][$i]);
  1069.                 $director->setAddress($data['director_address'][$i]);
  1070.                 $director->setIdNo($data['director_id'][$i]);
  1071.                 $this->em->persist($director);
  1072.                 $this->em->flush();
  1073.             }
  1074.         }
  1075.         return new JsonResponse($response);
  1076.     }
  1077.     /**
  1078.      * @Route("/update-trust-details", name="update_trust_details")
  1079.      */
  1080.     public function updateTrustDetails(Request $request)
  1081.     {
  1082.         $files $request->files->keys();
  1083.         $username $this->get('security.token_storage')->getToken()->getUser()->getUserIdentifier();
  1084.         $user $this->getDoctrine()->getRepository(Users::class)->findOneBy(['login' => $username]);
  1085.         $user_id $user->getId();
  1086.         $response '';
  1087.         $data $request->request;
  1088.         // Upload files
  1089.         foreach($files as $file_name) {
  1090.             // Trustee files are arrays
  1091.             if($file_name == 'file_trustee_proof_id' || $file_name == 'file_trustee_proof_of_address' || $file_name == 'file_trustee_contact_particulars'){
  1092.                 for($i 0$i count($_FILES[$file_name]['name']); $i++){
  1093.                     $extension pathinfo($_FILES[$file_name]['name'][$i], PATHINFO_EXTENSION);
  1094.                     $file $user_id '-' uniqid() . '.' $extension;
  1095.                     $target_file __DIR__ '/../../public/uploads/user-documents/' $file;
  1096.                     if (move_uploaded_file($_FILES[$file_name]['tmp_name'][$i], $target_file)) {
  1097.                         $user $this->getDoctrine()->getRepository(Users::class)->find($user_id);
  1098.                         $documents = new Documents();
  1099.                         $documents->setFile($file);
  1100.                         $documents->setDocumentType(substr(ucwords(str_replace('_',' ',$file_name)),5));
  1101.                         $documents->setUser($user);
  1102.                         $this->em->persist($documents);
  1103.                         $this->em->flush();
  1104.                         $response true;
  1105.                     }
  1106.                 }
  1107.             } else {
  1108.                 $extension $request->files->get($file_name)->guessExtension();
  1109.                 $file $user_id '-' uniqid() . '.' $extension;
  1110.                 $target_file __DIR__ '/../../public/uploads/user-documents/' $file;
  1111.                 if (move_uploaded_file($_FILES[$file_name]['tmp_name'], $target_file)) {
  1112.                     $user $this->getDoctrine()->getRepository(Users::class)->find($user_id);
  1113.                     $documents = new Documents();
  1114.                     $documents->setFile($file);
  1115.                     $documents->setDocumentType(substr(ucwords(str_replace('_',' ',$file_name)),5));
  1116.                     $documents->setUser($user);
  1117.                     $this->em->persist($documents);
  1118.                     $this->em->flush();
  1119.                     $response true;
  1120.                 }
  1121.             }
  1122.         }
  1123.         // Trustee details
  1124.         $trustee_name $data->get('trustee_name');
  1125.         $trustee_surname $data->get('trustee_surname');
  1126.         $trustee_id_no $data->get('trustee_id');
  1127.         $trustee_email $data->get('trustee_email');
  1128.         for($i 0$i count($trustee_name); $i++){
  1129.             $trustee = new Directors();
  1130.             $trustee->setUser($user);
  1131.             $trustee->setFirstName($trustee_name[$i]);
  1132.             $trustee->setLastName($trustee_surname[$i]);
  1133.             $trustee->setIdNo($trustee_id_no[$i]);
  1134.             $trustee->setEmail($trustee_email[$i]);
  1135.             $this->em->persist($trustee);
  1136.             $this->em->flush();
  1137.         }
  1138.         // Update trust details
  1139.         if(count($data) > && !empty($data->get('trust_name'))){
  1140.             $user->setTrustName($data->get('trust_name'));
  1141.             $user->setTrustContactNumber($data->get('trust_contact_number'));
  1142.             $user->setTrustAddress($data->get('trust_address'));
  1143.             $user->setTrustEmail($data->get('trust_email'));
  1144.             $user->setTrustTaxNumber($data->get('trust_tax_no'));
  1145.             $this->em->persist($user);
  1146.             $this->em->flush();
  1147.             $response true;
  1148.         }
  1149.         return new JsonResponse($response);
  1150.     }
  1151.     /**
  1152.      * @Route("/update-trustee-details", name="update_trustee_details")
  1153.      */
  1154.     public function updateTrusteeDetails(Request $request)
  1155.     {
  1156.         $data $request->request;
  1157.         $trustee $this->getDoctrine()->getRepository(Directors::class)->find($data->get('trustee_id'));
  1158.         // Trustee details
  1159.         if(filter_var($data->get('trustee_email'), FILTER_VALIDATE_EMAIL)) {
  1160.             $trustee->setFirstName($data->get('trustee_first_name'));
  1161.             $trustee->setLastName($data->get('trustee_last_name'));
  1162.             $trustee->setIdNo($data->get('trustee_id_no'));
  1163.             $trustee->setEmail($data->get('trustee_email'));
  1164.             $trustee->setAddress($data->get('trustee_address'));
  1165.             $this->em->persist($trustee);
  1166.             $this->em->flush();
  1167.             $message 'Trustee updated';
  1168.             $is_valid true;
  1169.         } else {
  1170.             $message '<b>Error:</b> Email address is invalid';
  1171.             $is_valid false;
  1172.         }
  1173.         return new JsonResponse([
  1174.             'message' => $message,
  1175.             'is_valid' => $is_valid,
  1176.             'id' => $data->get('trustee_id'),
  1177.             'first_name' => $data->get('trustee_first_name'),
  1178.             'last_name' => $data->get('trustee_last_name'),
  1179.             'id_no' => $data->get('trustee_id_no'),
  1180.             'email' => $data->get('trustee_email'),
  1181.             'address' => $data->get('trustee_address')
  1182.         ]);
  1183.     }
  1184.     /**
  1185.      * @Route("/send-message", name="send_message")
  1186.      */
  1187.     public function sendMessageAction(MailerInterface $mailerRequest $request)
  1188.     {
  1189.         $email = (new Email())
  1190.             ->from(self::EMAIL_FROM)
  1191.             ->to(self::EMAIL_TO)
  1192.             ->subject($request->request->get('subject'))
  1193.             ->html($request->request->get('message'));
  1194.         try {
  1195.             $mailer->send($email);
  1196.             $is_valid true;
  1197.             $message '<b><i class="fas fa-check-circle"></i> Message Sent</b><br>Your message has been sent to the website administrator';
  1198.         } catch(TransportExceptionInterface $exception){
  1199.             $is_valid false;
  1200.             $message 'Message not sent, please try again';
  1201.         }
  1202.         return new JsonResponse([
  1203.             'is_valid' => $is_valid,
  1204.             'message' => $message
  1205.         ]);
  1206.     }
  1207.     /**
  1208.      * @Route("/request-refund-deposit", name="request_refund_deposit")
  1209.      */
  1210.     public function requestRefundDepositAction(MailerInterface $mailerRequest $request)
  1211.     {
  1212.         $user $this->getDoctrine()->getRepository(Users::class)->find($request->get('user_id'));
  1213.         $host $this->generateUrl('refund_deposit',['user_id' => $request->get('user_id')],UrlGeneratorInterface::ABSOLUTE_URL);
  1214.         $body  'Hi Esias,';
  1215.         $body .= '<br><br>';
  1216.         $body .= 'Please could you refund my deposit.';
  1217.         $body .= '<br><br>';
  1218.         $body .= 'User ID: ' $user->getId();
  1219.         $body .= '<br>';
  1220.         $body .= 'Name: ' $user->getFirstName() .' '$user->getLastName();
  1221.         $body .= '<br><br>';
  1222.         $body .= '<a href="'$host .'">Update Deposit</a>';
  1223.         $email = (new Email())
  1224.             ->from(self::EMAIL_FROM)
  1225.             ->to(self::EMAIL_TO)
  1226.             ->subject('Request Deposit Refund')
  1227.             ->html($body);
  1228.         try {
  1229.             $mailer->send($email);
  1230.             $is_valid true;
  1231.             $message '<b><i class="fas fa-check-circle"></i> REQUEST SENT</b><br>Your request to have your deposit refunded has been sent.';
  1232.         } catch(TransportExceptionInterface $exception){
  1233.             $is_valid false;
  1234.             $message 'Message not sent, please try again';
  1235.         }
  1236.         return new JsonResponse([
  1237.             'is_valid' => $is_valid,
  1238.             'message' => $message
  1239.         ]);
  1240.     }
  1241.     /**
  1242.      * @Route("/refund-deposit/{user_id}", name="refund_deposit")
  1243.      */
  1244.     public function refundDepositAction(MailerInterface $mailerRequest $request)
  1245.     {
  1246.         $user $this->getDoctrine()->getRepository(Users::class)->find($request->get('user_id'));
  1247.         $host $this->generateUrl('empty_wallet',['user_id' => $request->get('user_id')],UrlGeneratorInterface::ABSOLUTE_URL);
  1248.         $body  'Hi Esias,';
  1249.         $body .= '<br><br>';
  1250.         $body .= 'Please use my depost as part payment.';
  1251.         $body .= '<br><br>';
  1252.         $body .= 'User ID: ' $request->get('user_id');
  1253.         $body .= '<br>';
  1254.         $body .= 'Name: ' $user->getFirstName() .' '$user->getLastName();
  1255.         $body .= '<br>';
  1256.         $body .= 'Balance: R'number_format($user->getWallet());
  1257.         $body .= '<br><br>';
  1258.         $body .= '<a href="'$host .'">Update Deposit</a>';
  1259.         $email = (new Email())
  1260.             ->from(self::EMAIL_FROM)
  1261.             ->to(self::EMAIL_TO)
  1262.             ->subject('Motus Auto Auctions Request Payment')
  1263.             ->html($body);
  1264.         try {
  1265.             $mailer->send($email);
  1266.             $is_valid true;
  1267.             $message '<b><i class="fas fa-check-circle"></i> REQUEST SENT</b><br>Your request to use your deposit as part payment has been sent.';
  1268.         } catch(TransportExceptionInterface $exception){
  1269.             $is_valid false;
  1270.             $message 'Message not sent, please try again';
  1271.         }
  1272.         return new JsonResponse([
  1273.             'is_valid' => $is_valid,
  1274.             'message' => $message
  1275.         ]);
  1276.     }
  1277.     /**
  1278.      * @Route("/empty-wallet/{user_id}", name="empty_wallet")
  1279.      */
  1280.     public function emptyWalletAction(Request $request)
  1281.     {;
  1282.         $user $this->getDoctrine()->getRepository(Users::class)->find($request->get('user_id'));
  1283.         $user->setWallet('0.00');
  1284.         $this->em->persist($user);
  1285.         $this->em->flush();
  1286.         return $this->render('frontend/test.html.twig');
  1287.     }
  1288.     /**
  1289.      * @Route("/payment", name="payment")
  1290.      */
  1291.     public function getPaymentLinkModelAction(Request $request)
  1292.     {;
  1293.         $siteCode 'MOT-MOT-004';
  1294.         $privateKey self::PRIVATE_KEY;
  1295.         $apiKey self::API_KEY;
  1296.         $auction_id 0;
  1297.         $user_id $request->get('user_id');
  1298.         if(isset($this->auction_id)){
  1299.             $auction_id $this->auction_id;
  1300.         }
  1301.         $transaction_id $this->insertTransactionAction($user_id,$request->get('hash'));
  1302.         $postData = [
  1303.             'SiteCode' => $siteCode,
  1304.             'CountryCode' => 'ZA',
  1305.             'CurrencyCode' => 'ZAR',
  1306.             'Amount' => 5000.00,
  1307.             'TransactionReference' => 'Motus Auctions Deposit #' $user_id,
  1308.             'BankReference' => 'Motus Auc Deposit',
  1309.             'Optional1' => $auction_id,
  1310.             'Optional2' => $transaction_id,
  1311.             'Optional3' => $user_id,
  1312.             'CancelUrl' => $this->generateUrl('ozow_response',[],UrlGeneratorInterface::ABSOLUTE_URL).'/cancel',
  1313.             'ErrorUrl' => $this->generateUrl('ozow_response',[],UrlGeneratorInterface::ABSOLUTE_URL).'/error',
  1314.             'SuccessUrl' => $this->generateUrl('ozow_response',[],UrlGeneratorInterface::ABSOLUTE_URL).'/accept',
  1315.             'NotifyUrl' => $this->generateUrl('ozow_response',[],UrlGeneratorInterface::ABSOLUTE_URL).'/pending',
  1316.             'IsTest' => 'true'
  1317.         ];
  1318.         $hashString strtolower(implode(''$postData) . $privateKey);
  1319.         $hashCheck hash('sha512'$hashString);
  1320.         $postData['HashCheck'] = $hashCheck;
  1321.         $this->hash_check $hashCheck;
  1322.         $session $this->requestStack->getSession();
  1323.         $session->set('transaction_id'$transaction_id);
  1324.         $jsonRequest json_encode($postData);
  1325.         $ch curl_init();
  1326.         curl_setopt($chCURLOPT_HTTPHEADER, array(
  1327.             'Accept: application/json',
  1328.             'ApiKey:' $apiKey,
  1329.             'Content-Type: application/json'
  1330.         ));
  1331.         curl_setopt($chCURLOPT_POSTtrue);
  1332.         curl_setopt($chCURLOPT_POSTFIELDS$jsonRequest);
  1333.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  1334.         curl_setopt($chCURLOPT_URL'https://api.ozow.com/postpaymentrequest');
  1335.         curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
  1336.         $requestResult curl_exec($ch);
  1337.         if ($requestResult === false){
  1338.             $message 'Error generating Ozow URL: curl error';
  1339.             return new JsonResponse([
  1340.                 'is_valid' => false,
  1341.                 'message' => $message
  1342.             ]);
  1343.         } else {
  1344.             $transaction $this->getDoctrine()->getRepository(Transactions::class)->find($transaction_id);
  1345.             $respone json_decode($requestResulttrue);
  1346.             $transaction->setHash($respone['paymentRequestId']);
  1347.             $this->em->persist($transaction);
  1348.             $this->em->flush();
  1349.             return new JsonResponse([
  1350.                     'url' => $respone['url'],
  1351.                     'is_valid' => true
  1352.                 ]);
  1353.         }
  1354.         return json_decode($requestResult);
  1355.     }
  1356.     private function insertTransactionAction($user_id$hash)
  1357.     {
  1358.         $user $this->getDoctrine()->getRepository(Users::class)->find($user_id);
  1359.         $transaction = new Transactions();
  1360.         $transaction->setUser($user);
  1361.         $this->em->persist($transaction);
  1362.         $this->em->flush();
  1363.         $transaction $this->getDoctrine()->getRepository(Transactions::class)->findOneBy([], ['id' => 'desc']);
  1364.         $transaction_id $transaction->getId();
  1365.         return $transaction_id;
  1366.     }
  1367.     /**
  1368.      * @Route("/ozow-response", name="ozow_response_action")
  1369.      */
  1370.     public function getOzowResponseAction(MailerInterface $mailerRequest $request)
  1371.     {
  1372.         if(!empty($request->get('TransactionId')) && !empty($request->get('Optional2'))){
  1373.             $transaction $this->getDoctrine()->getRepository(Transactions::class)->find($request->get('Optional2'));
  1374.             if($transaction->getStatus() != 'Complete') {
  1375.                 $transaction->setSiteCode($request->get('SiteCode'));
  1376.                 $transaction->setTransactionId($request->get('TransactionId'));
  1377.                 $transaction->setTransactionReference($request->get('TransactionReference'));
  1378.                 $transaction->setAmount($request->get('Amount'));
  1379.                 $transaction->setStatus($request->get('Status'));
  1380.                 $transaction->setCurrencyCode($request->get('CurrencyCode'));
  1381.                 $transaction->setStatusMessage($request->get('StatusMessage'));
  1382.                 $transaction->setHash($request->get('Hash'));
  1383.                 $this->em->persist($transaction);
  1384.                 $this->em->flush();
  1385.                 // Update wallet on success
  1386.                 if ($request->get('Status') == 'Complete') {
  1387.                     $user_id $request->get('Optional3');
  1388.                     $user $this->getDoctrine()->getRepository(Users::class)->find($user_id);
  1389.                     $wallet = (float)$user->getWallet() + (float)$request->get('Amount');
  1390.                     $user->setWallet($wallet);
  1391.                     $this->em->persist($user);
  1392.                     $this->em->flush();
  1393.                     // Send the customer email
  1394.                     $body 'Hi ' $user->getFirstName();
  1395.                     $body .= '<br><br>';
  1396.                     $body .= 'We have received your payment of R5000.00.';
  1397.                     $body .= '<br>';
  1398.                     $body .= 'Your wallet balance is now R' number_format($wallet2) . '.';
  1399.                     $body .= '<br><br>';
  1400.                     $body .= 'Esias Van Der Westhuizen<br>General Manager';
  1401.                     $email = (new Email())
  1402.                         ->from(self::EMAIL_FROM)
  1403.                         ->to($user->getLogin())
  1404.                         ->subject('Motus Auto Auctions Payment')
  1405.                         ->html($body);
  1406.                     try {
  1407.                         $mailer->send($email);
  1408.                         $message '<b><i class="fas fa-check-circle"></i> Email Sent</b><br>A confirmation email has been sent to yuor inbox';
  1409.                     } catch (TransportExceptionInterface $exception) {
  1410.                         $message '<b><i class="fas fa-check-circle"></i> Email Failed</b><br>Unable to send confirmation email';
  1411.                     }
  1412.                     $this->addFlash('success'$message);
  1413.                     // Register for an auction
  1414.                     if ($request->get('Optional1') > 0) {
  1415.                         $auction_register = new AuctionRegister();
  1416.                         $auction $this->getDoctrine()->getRepository(Auctions::class)->find($request->get('Optional1'));
  1417.                         $auction_register->setAuction($auction);
  1418.                         $auction_register->setUser($user);
  1419.                         $this->em->persist($auction_register);
  1420.                         $this->em->flush();
  1421.                     }
  1422.                     return new JsonResponse([
  1423.                         'message' => $message,
  1424.                         'mail_sent' => true,
  1425.                     ]);
  1426.                 }
  1427.             }
  1428.             return new JsonResponse([
  1429.                 'mail_sent' => false,
  1430.             ]);
  1431.         }
  1432.     }
  1433.     /**
  1434.      * @Route("/test", name="test")
  1435.      */
  1436.     public function test()
  1437.     {
  1438.         return $this->render('frontend/test.html.twig');
  1439.     }
  1440. }