<?php
namespace App\Controller;
use Alma\API\Request as APIRequest;
use App\Entity\Answer;
use stdClass;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Entity\ExamDate;
use App\Entity\Pack;
use App\Entity\Question;
use App\Entity\Subscription;
use App\Entity\Course;
use App\Entity\Settings;
use App\Entity\Booking;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use App\Security\LoginFormAuthenticator;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
use Symfony\Component\Security\Guard\GuardAuthenticationProvider;
class FrontController extends AbstractController
{
private $client;
public function __construct(HttpClientInterface $client)
{
$this->client = $client;
}
/**
* @Route(
* "/{_locale}",
* name="front",
* requirements={
* "_locale": "en|fr|cn",
* },
* defaults = {"_locale" = "fr"}
* )
*/
public function index(): Response
{
$packs = $this->getDoctrine()->getRepository(Pack::class)->findBy(array('status'=>1));
// $today = date('Y-m-d');
// $em = $this->getDoctrine()->getManager();
// $query = $em->createQuery("SELECT e FROM App\Entity\ExamDate e WHERE e.status = 1 AND e.date >= :today"
// )->setParameter('today', $today);
// $examDates = $query->getResult();
$examMonths = array();
$begin = new \DateTime(date('Y-m').'-01');
$end = new \DateTime(date('Y-m-d'));
$end = $end->modify( '+2 years' );
$interval = \DateInterval::createFromDateString('+1 month');
$period = new \DatePeriod($begin, $interval, $end);
$formatter = new \IntlDateFormatter('fr_FR', \IntlDateFormatter::SHORT, \IntlDateFormatter::SHORT);
$formatter->setPattern('MMMM Y');
foreach ($period as $dt) {
$examMonths[] = array(
// 'readable' => $formatter->format($dt),
'readable' => $dt->format('m/Y'),
'date' => $dt->format('Y-m')
);
}
return $this->render('front/index.html.twig', [
'controller_name' => 'FrontController',
'packs' => $packs,
// 'examDates' => $examDates,
'examMonths' => $examMonths
]);
}
public function loginUser($user, $request, $loginAuthenticator, $guard){
// public function authenticateUserAndHandleSuccess(UserInterface $user, Request $request, AuthenticatorInterface $authenticator, string $providerKey): ?Response
return $guard->authenticateUserAndHandleSuccess(
$user,
$request,
$loginAuthenticator,
'main'
);
}
// methods={"POST"}
/**
* @Route("/checkout_login", name="checkout_login")
*/
public function checkout_login(Request $request, UserPasswordHasherInterface $userPasswordHasher, GuardAuthenticationProvider $authenticator, GuardAuthenticatorHandler $guard): Response
{
$isPartner = $user = false;
$checkEmailExists = $this->getDoctrine()->getRepository(User::class)->findOneBy(array('email' => $request->get('email')));
if($checkEmailExists){
$match = $userPasswordHasher->isPasswordValid($checkEmailExists, $request->get('password'));
$logged = $this->loginUser($checkEmailExists, $request, $authenticator, $guard);
if($match){
$user = $checkEmailExists;
}
if($this->getUser() && in_array('ROLE_PARTNER', $this->getUser()->getRoles())){
$isPartner = true;
}
}
return $this->json([
// 'user' => $this->getUser() ? $this->getUser()->getId(): null,
'isPartner' => $isPartner,
'emx' => $request->get('email'),
'user' => $user
]);
}
/**
* @Route("/checkout/{id}", name="checkout")
*/
public function checkout($id, Request $request, UserPasswordHasherInterface $userPasswordHasher, LoginFormAuthenticator $loginAuthenticator, GuardAuthenticatorHandler $guard): Response
{
$user = null;
if(!$this->getUser()){
if($request->get('login')){
return $this->render('front/checkout-login.html.twig', [
'controller_name' => 'FrontController',
'orderID' => $id,
'login' => $request->get('login'),
'password' => $request->get('password'),
'isIframe' => true
]);
// $checkEmailExists = $this->getDoctrine()->getRepository(User::class)->findOneBy(array('email' => $request->get('login')));
// if($checkEmailExists){
// $match = $userPasswordHasher->isPasswordValid($checkEmailExists, $request->get('password'));
// $logged = $this->loginUser($checkEmailExists, $request, $loginAuthenticator, $guard);
// var_dump($logged);
// if($match){
// $user = $checkEmailExists;
// }
// }
}
// if(!$user) return $this->redirectToRoute('login', array('redirect_to'=>'/checkout/'.$id));
} else {
$user = $this->getUser();
}
$subscription = $this->getDoctrine()->getRepository(Subscription::class)->findOneBy(array('id'=>(int)$id));
if(!$subscription || $subscription->getUser() != $user){
return $this->redirectToRoute('dashboard_front');
}
// else if($subscription->getStatus() != 0){
// return $this->json(['error']);
// }
$taken = false;
$errors = null;
$checkBookings = $this->getDoctrine()->getRepository(Booking::class)->findByTakenBookings($subscription->getBookings());
if($checkBookings){
if(isset($checkBookings['taken'])){
$paypalKey = null;
$stripeKey = null;
$almaPaymentUrl = null;
$edofEnabled = null;
$taken = true;
}
}
if(!$taken) {
$edofEnabled = true;
require_once $this->getParameter('kernel.project_dir') . "/vendor/alma-php-client/vendor/autoload.php";
if($this->getParameter('kernel.environment') == 'prod'){
$almaApiKey = $this->getDoctrine()->getRepository(Settings::class)->findOneByName('alma_token');
$alma = new \Alma\API\Client($almaApiKey, ['mode' => \Alma\API\Client::LIVE_MODE]);
} else {
$almaApiKey = 'sk_test_nq8s0vsTyaKEQSGA8oy4c4JL';
$alma = new \Alma\API\Client($almaApiKey, ['mode' => \Alma\API\Client::TEST_MODE]);
}
$email = $user->getEmail();
$almaArgs = array(
'origin' => 'online',
'payment' =>
[
'return_url' => 'https://esrautomoto.fr/',
'ipn_callback_url' => 'https://esrautomoto.fr/api/paymentOKAlma',
'purchase_amount' => (int)(round($subscription->getPack()->getPrice() * 100)),
// 'installments_count' => 4,
'custom_data' =>
[
// 'my_very_important_key' => 'the_context_custom_value',
],
'locale' => 'fr',
'billing_address' =>
[
// 'first_name' => 'John',
// 'last_name' => 'Doe',
// 'email' => $email,
// 'line1' => '1 rue de Rome',
// 'postal_code' => '75001',
// 'city' => 'Paris',
// 'country' => 'FR',
],
'shipping_address' =>
[
// 'first_name' => 'John',
// 'last_name' => 'Doe',
// 'email' => $email,
// 'line1' => '1 rue de Rome',
// 'postal_code' => '75001',
// 'city' => 'Paris',
// 'country' => 'FR',
],
],
'customer' =>
[
// 'first_name' => 'John',
// 'last_name' => 'Doe',
'email' => $email,
// 'phone' => '06 12 34 56 78',
// 'addresses' =>
// [
// [
// 'first_name' => 'John',
// 'last_name' => 'Doe',
// 'email' => $email,
// 'phone' => '06 12 34 56 78',
// ],
// ],
],
);
try {
$almaPayment = $alma->payments->create($almaArgs);
$almaPaymentUrl = $almaPayment->url;
} catch (\Exception $th) {
$errors[] = "Erreur Alma: ".$th->response->json['errors'][0]['message'];
$almaPaymentUrl = null;
}
$paypalKey = null;//$this->getDoctrine()->getRepository(Settings::class)->findOneByName('paypal_key');
$stripeKey = $this->getDoctrine()->getRepository(Settings::class)->findOneByName('stripe_key');
}
if($subscription->getPack()->getType() == 'online'){
$examCenter = $examDate = '';
$examDateStatus = null;
} elseif($subscription->getExamDate()){
$examDate = $subscription->getExamDate()->format('d-m-Y');
$examDateExpl = explode('-', $examDate);
$week = floor($examDateExpl[0] / 7);
if($week < 1) $week = 1;
$examDate = $examDateExpl[1].'-'.$examDateExpl[2].' semaine '.$week;
$examDateStatus = 2;
$examCenter = '';
} else {
$examDate = $subscription->getExam();
$examCenter = $examDate->getExamCenter()->getName();
$examDateStatus = $examDate->getStatus();
$examDate = $examDate->getDate()->format('d-m-Y').' à '.$examDate->getTime();
}
return $this->render('front/checkout.html.twig', [
'controller_name' => 'FrontController',
'subscription' => $subscription,
'paypalKey' => $paypalKey,
'stripeKey' => $stripeKey,
'examDate' => $examDate,
'examDateStatus' => $examDateStatus,
'examCenter' => $examCenter,
'almaPaymentUrl' => $almaPaymentUrl,
'edofEnabled' => $edofEnabled,
'checkBookings' => $checkBookings,
'isIframe' => isset($_GET['isIframe']) ? true : false,
'errors' => $errors
]);
}
/**
* @Route("/test", name="test")
*/
public function test(Request $request): Response
{
die;
$em = $this->getDoctrine()->getManager();
$query1 = "SELECT q.text, a.text as a_text, q.file FROM tts q LEFT JOIN tts a on a.type LIKE 'R' and a.file = q.file where q.type like 'Q' order by q.file2 asc";
$stmt = $em->getConnection()->prepare($query1);
$stmt->execute();
$tts = $stmt->fetchAll();
$course = $this->getDoctrine()->getRepository(Course::class)->findOneBy(array('id'=>1));
$qDate = new \DateTimeImmutable();
$posi = 1;
$alphaArray = array(
'A' => 1,
'B' => 2,
'C' => 3,
'D' => 4,
'E' => 5,
'F' => 6,
'G' => 7
);
foreach($tts as $ttsElem){
$ttsElemExpl = explode('|', $ttsElem['text']);
// var_dump($ttsElemExpl);
// echo '<br />';
// if()
$qTitle = trim(str_replace(':', '', $ttsElemExpl[0]));
$question = new Question();
$question->setTitle($qTitle);
$question->setContent(str_replace('|', '<br />', $ttsElem['text']));
$question->setActive(1);
$question->setCourse($course);
$question->setFile($ttsElem['file'].'.jpg');
$question->setCreatedAt($qDate);
$question->setUpdateAt($qDate);
$question->setPosition($ttsElem['file']);
$em->persist($question);
$em->flush();
$goodAnswer = explode('|', $ttsElem['a_text']);
$goodAnswer = str_replace(array('Bonne réponse', ':', ' ', '.', 'et'), '', $goodAnswer[0]);
$goodAnswerExpl = str_split($goodAnswer);
$qGoodAnswers = array();
if(sizeof($goodAnswerExpl) > 0){
foreach($goodAnswerExpl as $goodAnswerExplElem){
if(isset($alphaArray[$goodAnswerExplElem])) $qGoodAnswers[] = $alphaArray[$goodAnswerExplElem];
}
}
// var_dump($qGoodAnswers);
// echo '<hr />';
$ansPosi = 1;
foreach($ttsElemExpl as $ttsElemExplElemKey => $ttsElemExplElem){
if(strpos($ttsElemExplElem, 'Réponse') !== false && strpos($ttsElemExplElem, 'Réponse') == 0){
$trimTtsElemExplElem = trim($ttsElemExplElem);
// var_dump(strpos($trimTtsElemExplElem, 'Réponse'));
// echo '<br />'.$trimTtsElemExplElem.'<hr />';
$answer = new Answer();
$answer->setTitle($trimTtsElemExplElem);
$answer->setQuestion($question);
$correct = in_array($ansPosi, $qGoodAnswers) ? true : false;
$answer->setCorrect($correct);
$em->persist($answer);
$em->flush();
$ansPosi++;
}
}
$posi++;
// if($posi >= 10) break;
}
echo '<h1>Finished!</h1>';
// var_dump($posi);
die;
$partnerCode = $request->get('partnerCode');
$partnerCode = str_replace('BC', '', $partnerCode);
$partnerCode = substr($partnerCode, 0, -2);
$em = $this->getDoctrine()->getManager();
$conn = $em->getConnection();
$sql = "SELECT * FROM user u WHERE u.id = :partnerCode AND u.roles LIKE '%ROLE_PARTNER%' LIMIT 0, 1";
$stmt = $conn->prepare($sql);
$stmt->execute(array('partnerCode' => $partnerCode));
$partner = $stmt->fetch();
// $partner = $this->getDoctrine()->getRepository(User::class)->findOneBy(array('id' => $partnerCode));
}
/**
* @Route("/faq", name="faq")
*/
public function faq(): Response
{
return $this->render('front/faq.html.twig', [
'controller_name' => 'FrontController'
]);
}
/**
* @Route("/paiement-effectue/{subscriptionID}", name="thanks")
*/
public function thanks($subscriptionID): Response
{
return $this->render('front/thanks.html.twig', [
'controller_name' => 'FrontController',
'errors' => null,
'subscriptionID' => $subscriptionID
]);
}
/**
* @Route("/dates-examen", name="list_exam_dates")
*/
public function list_exam_dates(): Response
{
$today = date('Y-m-d');
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery("SELECT e FROM App\Entity\ExamDate e WHERE e.status = 1 AND e.date >= :today"
)->setParameter('today', $today);
$examDates = $query->getResult();
return $this->render('front/examdates.html.twig', [
'controller_name' => 'FrontController',
'errors' => null,
'examDates' => $examDates
]);
}
/**
* @Route("/dates-examen/{id}", name="exam_date")
*/
public function exam_date($id): Response
{
$today = date('Y-m-d');
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery("SELECT e FROM App\Entity\ExamDate e WHERE e.id = :id AND e.status = 1 AND e.date >= :today"
)->setParameter('today', $today)->setParameter('id', $id);
$examDate = $query->getOneOrNullResult();
$startDate = strtotime($examDate->getDate()->format('d-m-Y').' '.$examDate->getTime());
$endDate = date('c', strtotime("+1 day", $startDate));
$validFrom = date('c', strtotime("-10 days", $startDate));
$startDate = date('c', $startDate);
return $this->render('front/examdate.html.twig', [
'controller_name' => 'FrontController',
'errors' => null,
'examDate' => $examDate,
'startDate' => $startDate,
'endDate' => $endDate,
'validFrom' => $validFrom
]);
}
/**
* @Route("/code-de-la-route", name="landing_code")
*/
public function landing_code(): Response
{
return $this->render('front/landing-code.html.twig', [
'controller_name' => 'FrontController'
]);
}
}