<?php
namespace App\Controller;
use App\Entity\AuctionRegister;
use App\Entity\Auctions;
use App\Entity\Directors;
use App\Entity\Documents;
use App\Entity\MetaData;
use App\Entity\Preferences;
use App\Entity\Transactions;
use App\Entity\User;
use App\Entity\Users;
use App\Form\CompanyDetailsFormType;
use App\Form\ContactNumberFormType;
use App\Form\RegisterFormType;
use App\Form\UserTypeFormType;
use App\Form\VerifyFormType;
use App\Services\PaginationManager;
use Doctrine\DBAL\Driver\AbstractDB2Driver;
use Doctrine\ORM\EntityManagerInterface;
use Dompdf\Dompdf;
use Dompdf\Options;
use Firebase\JWT\JWT;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
class UsersController extends AbstractController
{
private $session;
private $params;
private $endpoint;
private $access_token;
private $basic_token;
private $decoded;
private $key = 'q7vuFtP@2WSsgWtJE5X+j6kHzp&R-5qXfq5jR5';
private $em;
private $requestStack;
// Email from and to addresses
const EMAIL_FROM = 'Motus Auto Auctions <info@motusaa.co.za>';
const EMAIL_TO = 'karsten@nerdw.com';
// Payment gateways keys
const PRIVATE_KEY = 'biGBHjWvV9STEOD2BqE3hNmMsmIdCQ88';
const API_KEY = 'vtjaNBlqfneVPn28APV2Cn0jGwGIvFow';
/* Defined user types */
const USER_REGISTER_TYPE_INDIVIDUAL = 1;
const USER_REGISTER_TYPE_COMPANY = 2;
const USER_REGISTER_TYPE_TRUST = 3;
/* Defined user types array */
public $userRegisterTypeArrayOnly = [
self::USER_REGISTER_TYPE_INDIVIDUAL,
self::USER_REGISTER_TYPE_COMPANY,
self::USER_REGISTER_TYPE_TRUST
];
public function __construct(PaginationManager $pageManager, ParameterBagInterface $params, EntityManagerInterface $em, RequestStack $requestStack) {
$this->pageManager = $pageManager;
$this->session = new Session();
$this->em = $em;
$this->params = $params;
$this->requestStack = $requestStack;
}
/**
* @Route("/registerxxx", name="registerxxx")
*/
public function registerAction(Request $request): Response
{
$meta_data = $this->getDoctrine()->getRepository(MetaData::class)
->find(7);
// $this->addFlash('success', 'testing flash');
$reg = new Users();
$form = $this->createForm(RegisterFormType::class,$reg);
$form->handleRequest($request);
if ($form->isSubmitted()) {
// Check if spam bot
$post = $request->request->get('register_form');
if(key_exists('contact_me_by_fax_only',$post)){
return new Response('');
}
$task = $form->getData();
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($task);
$entityManager->flush();
// Customer email notification
// $body = $this->thankYouCopy($submitted_data['First Name']);
//
// $email = (new Email())
// ->from('Auto Pedigree <info@motusaa.co.za>')
// ->to($submitted_data['Email'])
// ->subject('Your enquiry has been received')
// ->html($body);
//
// $mailer->send($email);
//
// $referer = $_SERVER['HTTP_REFERER'];
return $this->redirectToRoute('register');
}
return $this->render('frontend/register.html.twig',
[
'meta' => $meta_data,
'form' => $form->createView()
]
);
}
/**
* @Route("/user/dashboard", name="user_dashboard")
*/
public function userDashboardAction(Request $request): Response
{
if($this->get('security.token_storage')->getToken() == null){
$this->addFlash('danger', 'Your session expired due to inactivity, please login.');
return $this->redirectToRoute('user_login');
}
$auction = $this->getDoctrine()->getRepository(Auctions::class)->findOneBy(['status' => 2]);
$username = $this->get('security.token_storage')->getToken()->getUser()->getUserIdentifier();
$user = $this->getDoctrine()->getRepository(Users::class)->findOneBy(['login' => $username]);
$auction_register = $this->getDoctrine()->getRepository(AuctionRegister::class)
->findOneBy(['auction' => $auction, 'user' => $user]);
// $oldToken = $this->get('security.token_storage')->getToken();
// dd($oldToken);
$documents = $user->getUser()->getUsers()->getDocuments()->toArray();
$auction_endpoint = $this->getParameter('app.am_auction_endpoint');
$contact_number_form = $this->createContactNumberForm();
$user_type_form = $this->createUserTypeForm();
$verify_form = $this->verifyUserTypeForm();
$company_details_form = $this->companyDetailsTypeForm();
$profile_pic = '';
$docs = [];
$dob = '';
// Auction Register Link
if($auction_register == null){
if($user->getUser()->getUsers()->getWallet() > 0){
$link = '<a href="#" data-toggle="modal" data-target="#register-modal">Register</a>' . "\n";
} else {
$link = '<a href="#" data-toggle="modal" data-target="#ozow-modal">Register</a>' . "\n";
}
} else {
$link = '<span class="label label-success"><i class="fas fa-check-square"></i></span>';
$link .= '<a href="https://'. $_SERVER['HTTP_HOST'] .'/bidding-number" style="margin-left: 20px" title="Print Bidding Number"><i class="fas fa-print"></i></a>';
}
// Auction View Link
if(!empty($user->getApiId())){
$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";
} else {
$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>';
}
// Documents logic
$profile_pic = null;
foreach($documents as $document){
// Expiry status
$modified = $document->getModified()->format('Y-m-d');
$expiry_date = date('Y-m-d', strtotime("+3 months", strtotime($modified)));
$docs[]['status'] = 'Valid';
if($expiry_date < $modified){
$docs[]['status'] = 'Expired';
}
// Profile picture
if($document->getDocumentType() == 'Profile Picture'){
$profile_pic = $document->getFile();
}
}
$user_reg_type = $this->getUserRegisterType();
$meta_data = $this->getDoctrine()->getRepository(MetaData::class)
->find(7);
$go_to_step = '';
if($user->getMobile() == null && $user->getKycVerified() == 1 && $user->getVerified() == 0) {
$go_to_step = 'poid';
}
// Proof of ID
if($user->getIdNumber() != null){
$id = $user->getIdNumber();
$year = substr($id,0,2);
$month = substr($id,2,2);
$day = substr($id,4,2);
if($year > substr(date('year'),-2)){
$year = '19' . $year;
} else {
$year = '20' . $year;
}
$dob = $year .'-'. $month .'-'. $day;
}
$contact_number_form->handleRequest($request);
if($contact_number_form->isSubmitted()){
$data = $contact_number_form->getData();
$user->setMobile($data->getMobile());
$this->em->persist($user);
$this->em->flush();
// Proof of Address
$extension = pathinfo($_FILES['poa']['name'],PATHINFO_EXTENSION);
$file = $user->getId() . '-'. uniqid() .'.'. $extension;
$target_file = __DIR__ . '/../../public/uploads/user-documents/' . $file;
if(move_uploaded_file($_FILES['poa']['tmp_name'], $target_file)){
$documents = new Documents();
$documents->setFile($file);
$documents->setDocumentType('Proof of Address');
$documents->setUser($user);
$this->em->persist($documents);
$this->em->flush();
$go_to_step = 'user_types';
}
// Proof of ID
$extension = pathinfo($_FILES['identity']['name'],PATHINFO_EXTENSION);
$file = $user->getId() . '-'. uniqid() .'.'. $extension;
$target_file = __DIR__ . '/../../public/uploads/user-documents/' . $file;
if(move_uploaded_file($_FILES['identity']['tmp_name'], $target_file)){
$documents = new Documents();
$documents->setFile($file);
$documents->setDocumentType('Proof of Identity');
$documents->setUser($user);
$this->em->persist($documents);
$this->em->flush();
}
$data = $request->request->get('contact_number_form');
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
$go_to_step = 'user_types';
}
foreach($documents as $document){
if($user->getKycVerified() == 1 && $user->getVerified() == 0 && $user->getUserType() == null && ($document->getDocumentType() == 'Proof of Address' || $document->getDocumentType() == 'Proof of Identity')){
$go_to_step = 'user_types';
break;
}
}
// User Type
$user_type_form->handleRequest($request);
if($user_type_form->isSubmitted() || ($user->getKycVerified() == 1 && $user->getVerified() == 0 && $user->getUserType() == null && $user->getMobile() != null)){
if($user_type_form->isSubmitted()) {
$user_type = $request->request->get('user-type');
$user->setUserType($user_type);
$this->em->persist($user);
$this->em->flush();
if($user_type == 1) {
$go_to_step = 'proof_of_bank_account';
} elseif($user_type == 2){
$go_to_step = 'company_reg_no';
} elseif($user_type == 3){
$go_to_step = 'trust_details';
}
}
}
// Proof of bank account
$poba = $_FILES['file-bank-account']['name'] ?? '';
if(!empty($poba) || ($user->getKycVerified() == 1 && $user->getVerified() == 0 && $user->getUserType() == 1 && $user->getMobile() != null)) {
if(!empty($poba)) {
$extension = pathinfo($poba, PATHINFO_EXTENSION);
$file = $user->getId() . '-' . uniqid() . '.' . $extension;
$target_file = __DIR__ . '/../../public/uploads/user-documents/' . $file;
if (move_uploaded_file($_FILES['file-bank-account']['tmp_name'], $target_file)) {
$documents = new Documents();
$documents->setFile($file);
$documents->setDocumentType('Proof of Bank Account');
$documents->setUser($user);
$this->em->persist($documents);
$this->em->flush();
}
}
// Get the user documents
$documents = $this->getDoctrine()->getRepository(Documents::class)->findBy(['user' => $user->getId()]);
foreach($documents as $document){
if($document->getDocumentType() == 'Proof of Bank Account'){
$go_to_step = 'terms';
break;
}
}
}
// Company Details
$company_reg_no = $request->get('company-reg-number') ?? '';
if(!empty($company_reg_no) || ($user->getKycVerified() == 1 && $user->getVerified() == 0 && $user->getUserType() == 2 && $user->getMobile() != null)) {
$go_to_step = 'company_reg_no';
if(!empty($company_reg_no)) {
$company_details_form->handleRequest($request);
if($company_details_form->isSubmitted()) {
$data = $company_details_form->getData();
}
}
$documents = $user->getUser()->getUsers()->getDocuments()->toArray();
foreach($documents as $document){
if($document->getDocumentType() == 'Proof of Bank Account'){
$go_to_step = 'terms';
break;
}
}
}
$verify_form->handleRequest($request);
if($verify_form->isSubmitted()) {
$data = $verify_form->getData();
$user->setVerified(1);
$user->setTerms(1);
$this->em->persist($user);
$this->em->flush();
}
return $this->render('frontend/user-dashboard.html.twig',
[
'meta' => $meta_data,
'user' => $user,
'documents' => $documents,
'profile_pic' => $profile_pic,
'docs' => $docs,
'auction' => $auction,
'link' => $link,
'view' => $view,
'user_reg_type' => $user_reg_type,
'contactNumberForm' => $contact_number_form->createView(),
'go_to_step' => $go_to_step,
'userTypeForm' => $user_type_form->createView(),
'verifyFormType' => $verify_form->createView(),
'dob' => $dob,
'user_id' => $user->getId(),
'company_details_form' => $company_details_form->createView(),
'trustees' => $user->getDirectors()->toArray(),
]
);
}
/**
* @Route("/validate-email", name="validate_email")
*/
public function validateEmailAction(Request $request, EntityManagerInterface $entityManager): Response
{
$email = $this->getDoctrine()->getRepository(Users::class)->findOneBy(['login' => $request->get('email')]);
$response = 'false';
if($email == null){
$response = 'true';
}
return new Response($response);
}
/**
* @Route("/preferences", name="preferences")
*/
public function preferencesAction(Request $request, EntityManagerInterface $entityManager): Response
{
$email = $this->getDoctrine()->getRepository(Preferences::class)->findAll();
$json = [];
foreach($email as $mail){
$json[] = [
'id' => $mail->getId(),
'text' => $mail->getPreference()
];
}
return new JsonResponse($json);
}
private function amCreateCustomer()
{
$endpoint = $this->getParameter('app.am_endpoint');
$basic_token = $this->getParameter('app.am_basic_token');
$user = $this->get('security.token_storage')->getToken()->getUser()->getUserIdentifier();
$user = $this->getDoctrine()->getRepository(Users::class)->findOneBy(['login' => $user]);
$email = $user->getLogin();
$first_name = $user->getFirstName();
$last_name = $user->getLastName();
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $endpoint . '/v5/integration/customer',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"email_address": "'. $email .'",
"is_external_record": true,
"integration_id": "'. $user->getId() .'",
"given_name": "'. $first_name .'",
"family_name": "'. $last_name .'"
}',
CURLOPT_HTTPHEADER => array(
'Authorization: Basic ' . $basic_token,
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
$json = json_decode($response, true);
$entityManager = $this->getDoctrine()->getManager();
$user_id = $user->getId();
$user = $entityManager->getRepository(Users::class)->find($user_id);
$user->setApiId($json['response']['row_id']);
$entityManager->persist($user);
$entityManager->flush();
}
/**
* @Route("/auction-register", name="auction_register")
*/
public function auctionRegisterAction(EntityManagerInterface $entityManager): Response
{
$auction_register = new AuctionRegister();
$auction = $this->getDoctrine()->getRepository(Auctions::class)->findOneBy(['status' => 1]);
$user = $this->get('security.token_storage')->getToken()->getUser()->getUserIdentifier();
$user = $this->getDoctrine()->getRepository(Users::class)->findOneBy(['login' => $user]);
$auction_register->setUser($user);
$auction_register->setAuction($auction);
$entityManager->persist($auction_register);
$entityManager->flush();
// Get the auction registration id
$auction_reg = $this->getDoctrine()->getRepository(AuctionRegister::class)
->findOneBy(['auction' => $auction, 'user' => $user]);
if(empty($user->getApiId())){
$this->amCreateCustomer();
}
$this->amAuctionRegistration($user->getApiId(),$user->getId(),$auction->getApiId(),$auction->getId(),$auction->getBiddingPrefix(), $auction_reg->getId());
$endpoint = $this->getParameter('app.am_auction_endpoint');
$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";
$link = '<span class="label label-success"><i class="fas fa-check-square"></i></span>';
$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>';
return new JsonResponse([
'view' => $view,
'link' => $link,
'auction' => $auction->getId()
]);
}
public function amAuctionRegistration($user_id, $maa_user_id, $auction_id, $maa_auction_id, $bidding_prefix, $reg_id){
$endpoint = $this->getParameter('app.am_endpoint');
$token = $this->getParameter('app.am_access_token');
$url = $endpoint . '/v5/admin/customer/'. $user_id .'/auction-registration';
$curl = curl_init();
$post_data = [
'auction_id' => (string) $auction_id,
'approved' => 1,
'paddle' => $bidding_prefix . $maa_user_id
];
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => json_encode($post_data),
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer '. $token,
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
// $response
$json = json_decode($response, true);
dump($json);
$entityManager = $this->getDoctrine()->getManager();
$auction_reg = $entityManager->getRepository(AuctionRegister::class)->find($reg_id);
dump($json['response']['row_id']);
$auction_reg->setApiId($json['response']['row_id']);
$entityManager->flush();
curl_close($curl);
}
/**
* @Route("/bidding-number", name="bidding_number")
*/
public function generatePdf()
{
if(!empty($this->get('security.token_storage')->getToken()->getUser()->getUserIdentifier())) {
$user = $this->get('security.token_storage')->getToken()->getUser()->getUserIdentifier();
$user = $this->getDoctrine()->getRepository(Users::class)->findOneBy(['login' => $user]);
$auction = $this->getDoctrine()->getRepository(Auctions::class)
->findOneBy(['status' => 2]);
$image = $this->display(__DIR__ . '/../../public/images/logo-pdf.png');
// Configure Dompdf according to your needs
$pdfOptions = new Options();
$pdfOptions->set('isRemoteEnabled', true);
$pdfOptions->set('defaultFont', 'Arial');
// Instantiate Dompdf with our options
$dompdf = new Dompdf($pdfOptions);
// Retrieve the HTML generated in our twig file
$html = $this->renderView('frontend/bidding-number.html.twig', [
'title' => "Motus Auto Auctions",
'auction' => $auction,
'user' => $user,
'logo' => $image,
]);
// Load HTML to Dompdf
$dompdf->loadHtml($html);
// (Optional) Setup the paper size and orientation 'portrait' or 'portrait'
$dompdf->setPaper('A4', 'portrait');
// Render the HTML as PDF
$dompdf->render();
// Output the generated PDF to Browser (force download)
$dompdf->stream('bidding-number-' . $user->getId() . '.pdf', [
"Attachment" => true
]);
return new Response('', 200, [
'Content-Type' => 'application/pdf',
]);
}
return new Response('Please login');
}
public static function display($path)
{
$image = base64_encode(file_get_contents($path));
return "data:image/png;base64,$image";
}
/**
* @Route("/contactable-verified", name="contactable_verified")
*/
public function contactableVerified()
{
$user = $this->get('security.token_storage')->getToken()->getUser()->getUserIdentifier();
$user = $this->getDoctrine()->getRepository(Users::class)->findBy(['login' => $user]);
return new Response($user[0]->getKycVerified());
}
/**
* @Route("/kyc", name="kyc")
*/
public function kycAction()
{
$json = file_get_contents('php://input');
$request = json_decode($json, true);
// Sanitise data
if($request['action'] == 'get'){
$username = filter_var($request['username'], FILTER_SANITIZE_STRING);
$password = filter_var($request['password'], FILTER_SANITIZE_STRING);
$organisation = filter_var($request['organisation_code'], FILTER_SANITIZE_STRING);
// Get JWT Token
return new JsonResponse($this->getJwtToken($username, $password, $organisation));
}
// Validate JWT Token & save data
if($request['action'] == 'put'){
$this->validJWT($request);
}
return new Response('');
}
// sends signed token in email to user if the user exists
private function getJwtToken($username, $password, $organisation){
// check if the user exists
if($api_user = $this->getApiUser($username, $password, $organisation)){
// generate JSON web token and store as variable
$token = $this->genJWT($username);
$response = [
'message' => 'Success',
'jwt_token' => $token
];
return $response;
} else {
$response = [
'message' => 'Authentication failed'
];
return $response;
}
}
private function genJWT($username){
$payload = [
"username" => $username,
// Expires
"exp" => time() + 10 * 60
];
/**
* IMPORTANT:
* You must specify supported algorithms for your application. See
* https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
* for a list of spec-compliant algorithms.
*/
return JWT::encode($payload, $this->key);
}
private function getApiUser($username, $password, $organisation)
{
$api_user = [
'username' => 'contactable@nerdware',
'password' => 'Jes#%3eTxre5wXD&^G^7Pc@8PCbuAwv&q=bD=Q',
'organisation_code' => 'contactable'
];
if($username == $api_user['username'] && $password == $api_user['password'] && $organisation == $api_user['organisation_code']){
$user = [
'username' => $api_user['username'],
'password' => $api_user['password'],
'organisation_code' => $api_user['organisation_code']
];
return $user;
}
return false;
}
public function validJWT($request){
// Validate the token
$tokenVal = $this->validToken($request);
// If the token is valid
if($tokenVal['0']){
if($request['data']['userId'] > 0) {
$user_id = $request['data']['userId'];
$id_no = $request['data']['identityNumber'];
$year = substr(0,2,$id_no);
$month = substr(2,2,$id_no);
$day = substr(4,2,$id_no);
$dob = $year .'-'. $month .'-'. $day;
$users = $this->getDoctrine()->getRepository(Users::class)->find($user_id);
// Update user acc with contactable data
$users->setIdNumber($id_no);
$users->getDob($dob);
$users->setFirstName($request['data']['firstName']);
$users->setLastName($request['data']['lastName']);
$users->setAddress1($request['data']['address1']);
$users->setAddress2($request['data']['address2']);
$users->setAddress3($request['data']['address3']);
$users->setKycVerified(1);
$users->setVerified(0);
$_SESSION["customer-name"] = '';
if (empty($request['data']['firstName'])) {
$_SESSION["customer-name"] = $request['data']['firstName'] . ' ' . $request['data']['lastName'];
}
if (count($request) > 1) {
$this->em->persist($users);
$this->em->flush();
// Update user acc with contactable data
$response = [
'message' => 'Authenticated',
'jwt_token' => $request['jwt_token'],
'username' => $this->decoded->username,
'expires' => date('Y-m-d H;i:s', $this->decoded->exp),
'user_data' => $request['data']['userId']
];
if (!empty($request['data']['auditCertificatePdfBase64']) || !empty($request['data']['selfieBase64'])) {
if (!empty($request['data']['auditCertificatePdfBase64'])) {
$this->zip = $request['data']['auditCertificatePdfBase64'];
$this->getFilesFromString($request['data']['userId'], $request);
}
if (!empty($request['data']['selfieBase64'])) {
$file = $request['data']['userId'] . '_' . mt_rand() . '.png';
$base64_string = $request['data']['selfieBase64'];
$output_file = __DIR__ . '/../../public/uploads/user-documents/' . $file;
$this->base64ToImage($base64_string, $output_file);
$docs = new Documents();
$docs->setUser($users);
$docs->setDocumentType('Profile Picture');
$docs->setFile($file);
$this->em->persist($docs);
$this->em->flush();
}
}
echo json_encode($response);
} else {
$response = [
'message' => 'Error: Insufficient data.',
'jwt_token' => $this->token
];
echo json_encode($response);
}
} else {
$response = [
'message' => 'Invalid user'
];
}
} else {
$response = [
'message' => 'Authentication failed'
];
echo json_encode($response);
}
}
// Validates a given JWT from the user email
private function validToken($response) {
$res = [false, ''];
// using a try and catch to verify
try {
$this->decoded = JWT::decode($response['jwt_token'], $this->key, array('HS256'));
$res['0'] = true;
$res['1'] = (array) $this->decoded;
return $res;
} catch (Exception $e){
throw new BadCredentialsException($e->getMessage(), 0, $e);
}
}
private function getFilesFromString($user_id, $api_response)
{
$tmp = $user_id . mt_rand();
file_put_contents(__DIR__ . '/../../public/uploads/user-documents/'. $tmp . '.log', $api_response['data']['auditCertificatePdfBase64']);
$base64_string = base64_decode(file_get_contents(__DIR__ . '/../../public/uploads/user-documents/'. $tmp . '.log'));
$fp = fopen(__DIR__ . '/../../public/uploads/user-documents/'. $tmp .'.zip', "w+");
fwrite($fp, $base64_string);
$zip = new \ZipArchive();
$zip_path = __DIR__ . '/../../public/uploads/user-documents/'. $tmp .'.zip';
if($zip->open($zip_path) === TRUE){
$this->files = [];
for($i = 0; $i < $zip->numFiles; $i++){
$filename = $zip->getNameIndex($i);
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$new = $api_response['data']['userId'] . '_'. mt_rand() .'.'. $ext;
$this->files[] = $new;
$zip->renameName($filename,$new);
if($i == 0){
$document_type = 'Validation Certificate';
} else {
$document_type = 'Livliness Test';
}
$docs = new Documents();
$user = $this->getDoctrine()->getRepository(Users::class)->find($user_id);
$docs->setDocumentType($document_type);
$docs->setFile($new);
$docs->setUser($user);
$this->em->persist($docs);
$this->em->flush();
}
$zip->extractTo(__DIR__ . "/../../public/uploads/user-documents/");
$zip->close();
} else {
return false;
}
if($zip->open($zip_path) === TRUE){
$zip->extractTo(__DIR__ . "/../../public/uploads/user-documents/");
$zip->close();
return true;
} else {
return false;
}
}
private function base64ToImage($base64_string, $output_file)
{
$file = fopen($output_file, "wb");
$data = explode(',', $base64_string);
fwrite($file, base64_decode($base64_string));
fclose($file);
return $output_file;
}
/* Set user register type value or label */
public function getUserRegisterType()
{
return $userRegisterTypeValues = [
self::USER_REGISTER_TYPE_INDIVIDUAL => 'Individual',
self::USER_REGISTER_TYPE_COMPANY => 'Company',
self::USER_REGISTER_TYPE_TRUST => 'Trust',
];
}
protected function createContactNumberForm()
{
$users = new Users();
return $this->createForm(ContactNumberFormType::class,
$users,
[
'method' => 'POST',
'action' => $this->generateUrl('user_dashboard')
]
);
}
protected function createUserTypeForm()
{
$users = new Users();
return $this->createForm(UserTypeFormType::class,
$users,
[
'method' => 'POST',
'action' => $this->generateUrl('user_dashboard')
]
);
}
protected function verifyUserTypeForm()
{
$users = new Users();
return $this->createForm(VerifyFormType::class,
$users,
[
'method' => 'POST',
'action' => $this->generateUrl('user_dashboard')
]
);
}
protected function companyDetailsTypeForm()
{
$users = new Users();
return $this->createForm(CompanyDetailsFormType::class,
$users,
[
'method' => 'POST',
'action' => $this->generateUrl('user_dashboard')
]
);
}
/**
* @Route("/update-personal-details", name="update_personal_details")
*/
public function updatePersonalDetailsAction(Request $request, TokenStorageInterface $tokenStorage)
{
$data = $request->request;
$message = '';
$is_valid = 0;
if(!empty($data->get('value'))) {
$users = $this->getDoctrine()->getRepository(Users::class)->find($data->get('user_id'));
if($data->get('key') == 'Contact number'){
$users->setMobile($data->get('value'));
$message = '<b><i class="fas fa-check-circle"></i> REQUEST SENT</b><br>Contact number updated';
$is_valid = 1;
} elseif($data->get('key') == 'Email address') {
$user = $this->getDoctrine()->getRepository(User::class)->find($users->getUser());
$users->setLogin($data->get('value'));
$user->setUsername($data->get('value'));
$user->setUsers($users);
$this->em->persist($user);
$this->em->flush();
$request->getSession()->invalidate();
$tokenStorage->setToken(null);
$this->addFlash('success', '<b><i class="fas fa-check-circle"></i> Email address updated</b><br>Please login using your new email address');
return new JsonResponse([
'value' => $data->get('value'),
'message' => $message,
'is_valid' => 1,
]);
}
$this->em->persist($users);
$this->em->flush();
} else {
$message = $data->get('key') . ' cannot be empty!';
$is_valid = 0;
}
return new JsonResponse([
'value' => $data->get('value'),
'message' => $message,
'is_valid' => $is_valid,
]);
}
/**
* @Route("/update-trust-contact-details", name="update_trust_contact_details")
*/
public function updateTrustDetailsAction(Request $request, TokenStorageInterface $tokenStorage)
{
$data = $request->request;
$message = '';
$is_valid = 0;
if(!empty($data->get('value'))) {
$users = $this->getDoctrine()->getRepository(Users::class)->find($data->get('user_id'));
if($data->get('key') == 'Contact Number'){
$users->setTrustContactNumber($data->get('value'));
$this->em->persist($users);
$this->em->flush();
$message = '<b><i class="fas fa-check-circle"></i> Request Sent</b><br>Trust contact number updated';
return new JsonResponse([
'value' => $data->get('value'),
'message' => $message,
'is_valid' => 1,
]);
} elseif($data->get('key') == 'Email address') {
$users->setTrustEmail($data->get('value'));
$this->em->persist($users);
$this->em->flush();
$message = '<b><i class="fas fa-check-circle"></i> Request Sent</b><br>Trust email address updated.';
return new JsonResponse([
'value' => $data->get('value'),
'message' => $message,
'is_valid' => 1,
]);
}
} else {
$message = $data->get('key') . ' cannot be empty!';
$is_valid = 0;
}
return new JsonResponse([
'value' => $data->get('value'),
'message' => $message,
'is_valid' => $is_valid,
]);
}
/**
* @Route("/get-cipc-report", name="get_cipc_report")
*/
public function getCipcBasicReport(Request $request)
{
$company_reg_no = $request->get('company_reg_no');
// Get JWT
$parameters = [
'Username' => 'motusactions@contactable',
'Password' => 'ad641fd2-6102-42cb-9ec4-3af89ef47d64!X',
'Organization_code' => 'motus_auctions'
];
$endpoint = curl_init('https://oem-gway-kyccompany-integrate.kyc.business/1.0.0/integrationgateway/post_BearerToken');
curl_setopt($endpoint, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($endpoint, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($endpoint);
curl_close($endpoint);
// Response
$json = json_decode($response);
// DEFINE our cipher
define('AES_256_CBC', 'aes-256-cbc');
// Generate a 256-bit encryption key
// This should be stored somewhere instead of recreating it each time
$encryption_key = 'gkmxhsKfZUA7tEqoFJhiVoOrcykGzy8wAiQdsmVbhaKE7iaCvTr3ta04Vfre4n7DdnazN6OsJNkpzxAbau3StM5aNaV936n4cS1ORt7g5aB';
// Generate an initialization vector
// This *MUST* be available for decryption as well
//$iv = 'UHLbqQYb97LoyM2FobOtoGTx6HGrdQ69Gf467aRtFu3fCnK2w2V5W4';
$iv = 'UHLbqQYb97LoyM2F';
// Encrypt $data using aes-256-cbc cipher with the given encryption key and
// our initialization vector. The 0 gives us the default options, but can
// be changed to OPENSSL_RAW_DATA or OPENSSL_ZERO_PADDING
$encrypted = openssl_encrypt($company_reg_no, AES_256_CBC, $encryption_key, 0, $iv);
$token = $json->response_object->jwt_token;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://oem-gway-kyccompany-integrate.kyc.business/1.0.0/IntegrationGateway/RetrieveBasicCICPReport',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"company_registration_number" : "'. $encrypted .'"
}',
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer '. $token,
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
// $response
$json = json_decode($response);
$decrypted = openssl_decrypt($json->response_object->encrypted_response, AES_256_CBC, $encryption_key, 0, $iv);
$array = json_decode($decrypted, true);
// Save to file
$user_id = $request->get('user_id');
$user = $this->getDoctrine()->getRepository(Users::class)->find($user_id);
$rand = $user_id .'_'. mt_rand();
$fp = fopen(__DIR__ . '/../../public/uploads/user-documents/cipc/'. $rand .'.txt', "w+");
fwrite($fp, serialize($array));
fclose($fp);
$user->setcompany_cicp_file($rand . '.txt');
$this->em->persist($user);
$this->em->flush();
// Business Info
$company_name = $array['commercial']['commercialBusinessInformation']['commercialName'];
$company_reg_no = $array['commercial']['commercialBusinessInformation']['registrationNo'];
$company_financial_year_end = $array['commercial']['commercialBusinessInformation']['financialYearEnd'];
$company_start_date = $array['commercial']['commercialBusinessInformation']['businessStartDate'];
$company_tax_no = $array['commercial']['commercialBusinessInformation']['taxNo'];
$company_type = $array['commercial']['commercialBusinessInformation']['commercialType'];
$company_vat_no = $array['commercial']['commercialBusinessInformation']['vatNo'];
// Addresses
$address_array = $this->arraySortByColumn($array['commercial']['commercialAddressInformation'], 'lastUpdatedDate');
$company_physical_address = $address_array[0]['address1'] .' '. $address_array[0]['address2'] .' '. $address_array[0]['address3'] .' '. $address_array[0]['address4'] .' '. $address_array[0]['postalCode'];
$company_postal_address = $address_array[0]['address1'] .' '. $address_array[0]['address2'] .' '. $address_array[0]['address3'] .' '. $address_array[0]['address4'] .' '. $address_array[0]['postalCode'];
// Directors
$directors = '';
$director_count = 0;
$hidden_fields = '';
foreach($array['commercial']['commercialDirectorInformation'] as $director){
$director_count++;
$directors .= '<div class="col-4 d-flex p-b15">
<div class="file btn btn-primary w-100 mr-1" style="position: relative; overflow: hidden;">
<div class="call_back_error_msg hidden_msg" id="error_director_proof_of_address_'. $director_count .'" style="color: #d98f77">
Required Field
</div>
<span id="string-director-poa'. $director_count .'">Director Proof of Address</span>
<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;" />
</div>
<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">
<i class="fas fa-info-circle"></i>
</button>
</div>
<div class="col-4 d-flex p-b15">
<div class="file btn btn-primary w-100 mr-1" style="position: relative; overflow: hidden;">
<div class="call_back_error_msg hidden_msg" id="error_director_id_'. $director_count .'" style="color: #d98f77">
Required Field
</div>
<span id="string-director-id'. $director_count .'">Director Identity Document</span>
<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;" />
</div>
<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">
<i class="fas fa-info-circle"></i>
</button>
</div>';
$hidden_fields .= '<input type="hidden" name="director_first_name[]" value="'. $director['firstName'] .'">' . "\n";
$hidden_fields .= '<input type="hidden" name="director_last_name[]" value="'. $director['surname'] .'">' . "\n";
$hidden_fields .= '<input type="hidden" name="director_address[]" value="'. $director['physicalAddress'] .'">' . "\n";
$hidden_fields .= '<input type="hidden" name="director_id[]" value="'. $director['idNo'] .'">' . "\n";
}
$company_arr = [
$company_name,
$company_reg_no,
$company_start_date,
$company_financial_year_end,
$company_type,
$company_tax_no,
$company_physical_address,
$company_postal_address,
$company_vat_no,
stripslashes($directors),
$director_count,
$hidden_fields
];
return new JsonResponse($company_arr);
}
private function arraySortByColumn(&$array, $column, $direction = SORT_DESC)
{
$reference_array = [];
foreach($array as $key => $row){
$reference_array[$key] = $row[$column];
}
array_multisort($reference_array, $direction, $array);
return $array;
}
/**
* @Route("/update-company-details", name="update_company_details")
*/
public function updateCompanyDetails(Request $request)
{
$files = $request->files->keys();
$username = $this->get('security.token_storage')->getToken()->getUser()->getUserIdentifier();
$user = $this->getDoctrine()->getRepository(Users::class)->findOneBy(['login' => $username]);
$user_id = $user->getId();
$response = false;
// Upload files
foreach($files as $file_name) {
// Directors files are arrays
if($file_name == 'file-director-poa' || $file_name == 'file-director-id'){
for($i = 0; $i < count($_FILES[$file_name]['name']); $i++){
$extension = pathinfo($_FILES[$file_name]['name'][$i], PATHINFO_EXTENSION);
$file = $user_id . '-' . uniqid() . '.' . $extension;
$target_file = __DIR__ . '/../../public/uploads/user-documents/' . $file;
if (move_uploaded_file($_FILES[$file_name]['tmp_name'][$i], $target_file)) {
$user = $this->getDoctrine()->getRepository(Users::class)->find($user_id);
$documents = new Documents();
$documents->setFile($file);
$documents->setDocumentType($file_name);
$documents->setUser($user);
$this->em->persist($documents);
$this->em->flush();
$response = true;
}
}
} else {
$extension = $request->files->get($file_name)->guessExtension();
$file = $user_id . '-' . uniqid() . '.' . $extension;
$target_file = __DIR__ . '/../../public/uploads/user-documents/' . $file;
if (move_uploaded_file($_FILES[$file_name]['tmp_name'], $target_file)) {
$user = $this->getDoctrine()->getRepository(Users::class)->find($user_id);
$documents = new Documents();
$documents->setFile($file);
$documents->setDocumentType($file_name);
$documents->setUser($user);
$this->em->persist($documents);
$this->em->flush();
$response = true;
}
}
}
// Update company details
$data = $request->request->get('company_details_form');
if(is_array($data) && count($data) > 0){
// Company data
$user->setCompanyName($data['companyName']);
$user->setCompanyRegNo($data['companyRegNo']);
$user->setCompanyStartDate($data['companyStartDate']);
$user->setCompanyFinancialYearEnd($data['companyFinancialYearEnd']);
$user->setCompanyType($data['companyType']);
$user->setCompanyTaxNo($data['companyTaxNo']);
$user->setCompanyPhysicalAddress($data['companyPhysicalAddress']);
$user->setCompanyPostalAddress($data['companyPostalAddress']);
$user->setCompanyVatNo($data['companyVatNo']);
$this->em->persist($user);
$this->em->flush();
$response = true;
}
$data['director_first_name'] = $request->request->get('director_first_name');
$data['director_last_name'] = $request->request->get('director_last_name');
$data['director_address'] = $request->request->get('director_address');
$data['director_id'] = $request->request->get('director_id');
if(is_array($data['director_first_name']) && count($data['director_first_name']) > 0){
// Directors data
for($i=0;$i<count($data['director_first_name']);$i++){
$director = new Directors();
$director->setUser($user);
$director->setFirstName($data['director_first_name'][$i]);
$director->setLastName($data['director_last_name'][$i]);
$director->setAddress($data['director_address'][$i]);
$director->setIdNo($data['director_id'][$i]);
$this->em->persist($director);
$this->em->flush();
}
}
return new JsonResponse($response);
}
/**
* @Route("/update-trust-details", name="update_trust_details")
*/
public function updateTrustDetails(Request $request)
{
$files = $request->files->keys();
$username = $this->get('security.token_storage')->getToken()->getUser()->getUserIdentifier();
$user = $this->getDoctrine()->getRepository(Users::class)->findOneBy(['login' => $username]);
$user_id = $user->getId();
$response = '';
$data = $request->request;
// Upload files
foreach($files as $file_name) {
// Trustee files are arrays
if($file_name == 'file_trustee_proof_id' || $file_name == 'file_trustee_proof_of_address' || $file_name == 'file_trustee_contact_particulars'){
for($i = 0; $i < count($_FILES[$file_name]['name']); $i++){
$extension = pathinfo($_FILES[$file_name]['name'][$i], PATHINFO_EXTENSION);
$file = $user_id . '-' . uniqid() . '.' . $extension;
$target_file = __DIR__ . '/../../public/uploads/user-documents/' . $file;
if (move_uploaded_file($_FILES[$file_name]['tmp_name'][$i], $target_file)) {
$user = $this->getDoctrine()->getRepository(Users::class)->find($user_id);
$documents = new Documents();
$documents->setFile($file);
$documents->setDocumentType(substr(ucwords(str_replace('_',' ',$file_name)),5));
$documents->setUser($user);
$this->em->persist($documents);
$this->em->flush();
$response = true;
}
}
} else {
$extension = $request->files->get($file_name)->guessExtension();
$file = $user_id . '-' . uniqid() . '.' . $extension;
$target_file = __DIR__ . '/../../public/uploads/user-documents/' . $file;
if (move_uploaded_file($_FILES[$file_name]['tmp_name'], $target_file)) {
$user = $this->getDoctrine()->getRepository(Users::class)->find($user_id);
$documents = new Documents();
$documents->setFile($file);
$documents->setDocumentType(substr(ucwords(str_replace('_',' ',$file_name)),5));
$documents->setUser($user);
$this->em->persist($documents);
$this->em->flush();
$response = true;
}
}
}
// Trustee details
$trustee_name = $data->get('trustee_name');
$trustee_surname = $data->get('trustee_surname');
$trustee_id_no = $data->get('trustee_id');
$trustee_email = $data->get('trustee_email');
for($i = 0; $i < count($trustee_name); $i++){
$trustee = new Directors();
$trustee->setUser($user);
$trustee->setFirstName($trustee_name[$i]);
$trustee->setLastName($trustee_surname[$i]);
$trustee->setIdNo($trustee_id_no[$i]);
$trustee->setEmail($trustee_email[$i]);
$this->em->persist($trustee);
$this->em->flush();
}
// Update trust details
if(count($data) > 0 && !empty($data->get('trust_name'))){
$user->setTrustName($data->get('trust_name'));
$user->setTrustContactNumber($data->get('trust_contact_number'));
$user->setTrustAddress($data->get('trust_address'));
$user->setTrustEmail($data->get('trust_email'));
$user->setTrustTaxNumber($data->get('trust_tax_no'));
$this->em->persist($user);
$this->em->flush();
$response = true;
}
return new JsonResponse($response);
}
/**
* @Route("/update-trustee-details", name="update_trustee_details")
*/
public function updateTrusteeDetails(Request $request)
{
$data = $request->request;
$trustee = $this->getDoctrine()->getRepository(Directors::class)->find($data->get('trustee_id'));
// Trustee details
if(filter_var($data->get('trustee_email'), FILTER_VALIDATE_EMAIL)) {
$trustee->setFirstName($data->get('trustee_first_name'));
$trustee->setLastName($data->get('trustee_last_name'));
$trustee->setIdNo($data->get('trustee_id_no'));
$trustee->setEmail($data->get('trustee_email'));
$trustee->setAddress($data->get('trustee_address'));
$this->em->persist($trustee);
$this->em->flush();
$message = 'Trustee updated';
$is_valid = true;
} else {
$message = '<b>Error:</b> Email address is invalid';
$is_valid = false;
}
return new JsonResponse([
'message' => $message,
'is_valid' => $is_valid,
'id' => $data->get('trustee_id'),
'first_name' => $data->get('trustee_first_name'),
'last_name' => $data->get('trustee_last_name'),
'id_no' => $data->get('trustee_id_no'),
'email' => $data->get('trustee_email'),
'address' => $data->get('trustee_address')
]);
}
/**
* @Route("/send-message", name="send_message")
*/
public function sendMessageAction(MailerInterface $mailer, Request $request)
{
$email = (new Email())
->from(self::EMAIL_FROM)
->to(self::EMAIL_TO)
->subject($request->request->get('subject'))
->html($request->request->get('message'));
try {
$mailer->send($email);
$is_valid = true;
$message = '<b><i class="fas fa-check-circle"></i> Message Sent</b><br>Your message has been sent to the website administrator';
} catch(TransportExceptionInterface $exception){
$is_valid = false;
$message = 'Message not sent, please try again';
}
return new JsonResponse([
'is_valid' => $is_valid,
'message' => $message
]);
}
/**
* @Route("/request-refund-deposit", name="request_refund_deposit")
*/
public function requestRefundDepositAction(MailerInterface $mailer, Request $request)
{
$user = $this->getDoctrine()->getRepository(Users::class)->find($request->get('user_id'));
$host = $this->generateUrl('refund_deposit',['user_id' => $request->get('user_id')],UrlGeneratorInterface::ABSOLUTE_URL);
$body = 'Hi Esias,';
$body .= '<br><br>';
$body .= 'Please could you refund my deposit.';
$body .= '<br><br>';
$body .= 'User ID: ' . $user->getId();
$body .= '<br>';
$body .= 'Name: ' . $user->getFirstName() .' '. $user->getLastName();
$body .= '<br><br>';
$body .= '<a href="'. $host .'">Update Deposit</a>';
$email = (new Email())
->from(self::EMAIL_FROM)
->to(self::EMAIL_TO)
->subject('Request Deposit Refund')
->html($body);
try {
$mailer->send($email);
$is_valid = true;
$message = '<b><i class="fas fa-check-circle"></i> REQUEST SENT</b><br>Your request to have your deposit refunded has been sent.';
} catch(TransportExceptionInterface $exception){
$is_valid = false;
$message = 'Message not sent, please try again';
}
return new JsonResponse([
'is_valid' => $is_valid,
'message' => $message
]);
}
/**
* @Route("/refund-deposit/{user_id}", name="refund_deposit")
*/
public function refundDepositAction(MailerInterface $mailer, Request $request)
{
$user = $this->getDoctrine()->getRepository(Users::class)->find($request->get('user_id'));
$host = $this->generateUrl('empty_wallet',['user_id' => $request->get('user_id')],UrlGeneratorInterface::ABSOLUTE_URL);
$body = 'Hi Esias,';
$body .= '<br><br>';
$body .= 'Please use my depost as part payment.';
$body .= '<br><br>';
$body .= 'User ID: ' . $request->get('user_id');
$body .= '<br>';
$body .= 'Name: ' . $user->getFirstName() .' '. $user->getLastName();
$body .= '<br>';
$body .= 'Balance: R'. number_format($user->getWallet());
$body .= '<br><br>';
$body .= '<a href="'. $host .'">Update Deposit</a>';
$email = (new Email())
->from(self::EMAIL_FROM)
->to(self::EMAIL_TO)
->subject('Motus Auto Auctions Request Payment')
->html($body);
try {
$mailer->send($email);
$is_valid = true;
$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.';
} catch(TransportExceptionInterface $exception){
$is_valid = false;
$message = 'Message not sent, please try again';
}
return new JsonResponse([
'is_valid' => $is_valid,
'message' => $message
]);
}
/**
* @Route("/empty-wallet/{user_id}", name="empty_wallet")
*/
public function emptyWalletAction(Request $request)
{;
$user = $this->getDoctrine()->getRepository(Users::class)->find($request->get('user_id'));
$user->setWallet('0.00');
$this->em->persist($user);
$this->em->flush();
return $this->render('frontend/test.html.twig');
}
/**
* @Route("/payment", name="payment")
*/
public function getPaymentLinkModelAction(Request $request)
{;
$siteCode = 'MOT-MOT-004';
$privateKey = self::PRIVATE_KEY;
$apiKey = self::API_KEY;
$auction_id = 0;
$user_id = $request->get('user_id');
if(isset($this->auction_id)){
$auction_id = $this->auction_id;
}
$transaction_id = $this->insertTransactionAction($user_id,$request->get('hash'));
$postData = [
'SiteCode' => $siteCode,
'CountryCode' => 'ZA',
'CurrencyCode' => 'ZAR',
'Amount' => 5000.00,
'TransactionReference' => 'Motus Auctions Deposit #' . $user_id,
'BankReference' => 'Motus Auc Deposit',
'Optional1' => $auction_id,
'Optional2' => $transaction_id,
'Optional3' => $user_id,
'CancelUrl' => $this->generateUrl('ozow_response',[],UrlGeneratorInterface::ABSOLUTE_URL).'/cancel',
'ErrorUrl' => $this->generateUrl('ozow_response',[],UrlGeneratorInterface::ABSOLUTE_URL).'/error',
'SuccessUrl' => $this->generateUrl('ozow_response',[],UrlGeneratorInterface::ABSOLUTE_URL).'/accept',
'NotifyUrl' => $this->generateUrl('ozow_response',[],UrlGeneratorInterface::ABSOLUTE_URL).'/pending',
'IsTest' => 'true'
];
$hashString = strtolower(implode('', $postData) . $privateKey);
$hashCheck = hash('sha512', $hashString);
$postData['HashCheck'] = $hashCheck;
$this->hash_check = $hashCheck;
$session = $this->requestStack->getSession();
$session->set('transaction_id', $transaction_id);
$jsonRequest = json_encode($postData);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'ApiKey:' . $apiKey,
'Content-Type: application/json'
));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonRequest);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'https://api.ozow.com/postpaymentrequest');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$requestResult = curl_exec($ch);
if ($requestResult === false){
$message = 'Error generating Ozow URL: curl error';
return new JsonResponse([
'is_valid' => false,
'message' => $message
]);
} else {
$transaction = $this->getDoctrine()->getRepository(Transactions::class)->find($transaction_id);
$respone = json_decode($requestResult, true);
$transaction->setHash($respone['paymentRequestId']);
$this->em->persist($transaction);
$this->em->flush();
return new JsonResponse([
'url' => $respone['url'],
'is_valid' => true
]);
}
return json_decode($requestResult);
}
private function insertTransactionAction($user_id, $hash)
{
$user = $this->getDoctrine()->getRepository(Users::class)->find($user_id);
$transaction = new Transactions();
$transaction->setUser($user);
$this->em->persist($transaction);
$this->em->flush();
$transaction = $this->getDoctrine()->getRepository(Transactions::class)->findOneBy([], ['id' => 'desc']);
$transaction_id = $transaction->getId();
return $transaction_id;
}
/**
* @Route("/ozow-response", name="ozow_response_action")
*/
public function getOzowResponseAction(MailerInterface $mailer, Request $request)
{
if(!empty($request->get('TransactionId')) && !empty($request->get('Optional2'))){
$transaction = $this->getDoctrine()->getRepository(Transactions::class)->find($request->get('Optional2'));
if($transaction->getStatus() != 'Complete') {
$transaction->setSiteCode($request->get('SiteCode'));
$transaction->setTransactionId($request->get('TransactionId'));
$transaction->setTransactionReference($request->get('TransactionReference'));
$transaction->setAmount($request->get('Amount'));
$transaction->setStatus($request->get('Status'));
$transaction->setCurrencyCode($request->get('CurrencyCode'));
$transaction->setStatusMessage($request->get('StatusMessage'));
$transaction->setHash($request->get('Hash'));
$this->em->persist($transaction);
$this->em->flush();
// Update wallet on success
if ($request->get('Status') == 'Complete') {
$user_id = $request->get('Optional3');
$user = $this->getDoctrine()->getRepository(Users::class)->find($user_id);
$wallet = (float)$user->getWallet() + (float)$request->get('Amount');
$user->setWallet($wallet);
$this->em->persist($user);
$this->em->flush();
// Send the customer email
$body = 'Hi ' . $user->getFirstName();
$body .= '<br><br>';
$body .= 'We have received your payment of R5000.00.';
$body .= '<br>';
$body .= 'Your wallet balance is now R' . number_format($wallet, 2) . '.';
$body .= '<br><br>';
$body .= 'Esias Van Der Westhuizen<br>General Manager';
$email = (new Email())
->from(self::EMAIL_FROM)
->to($user->getLogin())
->subject('Motus Auto Auctions Payment')
->html($body);
try {
$mailer->send($email);
$message = '<b><i class="fas fa-check-circle"></i> Email Sent</b><br>A confirmation email has been sent to yuor inbox';
} catch (TransportExceptionInterface $exception) {
$message = '<b><i class="fas fa-check-circle"></i> Email Failed</b><br>Unable to send confirmation email';
}
$this->addFlash('success', $message);
// Register for an auction
if ($request->get('Optional1') > 0) {
$auction_register = new AuctionRegister();
$auction = $this->getDoctrine()->getRepository(Auctions::class)->find($request->get('Optional1'));
$auction_register->setAuction($auction);
$auction_register->setUser($user);
$this->em->persist($auction_register);
$this->em->flush();
}
return new JsonResponse([
'message' => $message,
'mail_sent' => true,
]);
}
}
return new JsonResponse([
'mail_sent' => false,
]);
}
}
/**
* @Route("/test", name="test")
*/
public function test()
{
return $this->render('frontend/test.html.twig');
}
}