<?php
namespace App\Controller\Pages;
use App\Controller\Objects\CampCourse;
use App\Controller\Objects\CampReg;
use App\Controller\Objects\CampSettings;
use App\Controller\System;
use App\Kernel;
use App\Controller\AbstractKasController;
use App\Controller\Database;
use App\Controller\PageInfo;
use Doctrine\DBAL\Exception;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\VarDumper;
use Symfony\Component\HttpFoundation\RedirectResponse;
class CampController extends AbstractKasController
{
private CampSettings $settings;
private string $link;
public function __construct(RequestStack $requestStack, Database $db, PageInfo $pageInfo)
{
parent::__construct($requestStack, $db, $pageInfo);
$this->request = $requestStack->getCurrentRequest();
$this->model = new CampModel($db);
$this->settings = $this->model->getSettings();
$link = $this->request->getRequestUri();
if (str_starts_with($link, '/aquasvet')) $this->link = '/aquasvet';
elseif (str_starts_with($link, '/mestska-sportovni-hala')) $this->link = '/mestska-sportovni-hala';
elseif (str_starts_with($link, '/kino-svet')) $this->link = '/kino-svet';
else $this->link = '';
}
/**
* @Route("/aquasvet/prazdniny/prihlaska-{eid}")
* @Route("/mestska-sportovni-hala/prazdniny/prihlaska-{eid}")
* @Route("/kino-svet/prazdniny/prihlaska-{eid}")
* @return Response
* @throws \Facebook\Exceptions\FacebookSDKException
*/
public function prihlaska_na_kurz(string $eid): Response
{
$model = new ObjectModel($this->db);
$objectinfo = $model->getObjectInfo('/aquasvet');
$objectinfo->setTitle('Přihláška na prázdniny');
$objectinfo->setButtons([]);
$id = System::decrypt($eid); //COURSES_2
//pokud nenalezeno, tak 404
if (!$objectinfo->isFound() || $eid=='' || !System::IsIntPosNum($id)) return $this->render('/pages/404.html.twig', [
'pageinfo' => $this->pageInfo
]);
$model = new HomeModel($this->db);
$top_events = $model->getTopEvents(); //dump($top_events);
$facebook_feed = $model->getFacebookFeed();
$course = $this->model->getCourse($id);
$termines = $this->model->getTermines($id);
if ($course->getName() == '' || count($termines)===0) {
return $this->render('/pages/404.html.twig', [
'pageinfo' => $this->pageInfo
]);
}
$objectinfo->setTitle($course->getName());
$objectinfo->setSubtitle('přihláška');
return $this->render('/pages/camp_form.html.twig', [
'eid' => $eid,
'link' => $this->link,
'course' => $course,
'termines' => $termines,
'settings' => $this->settings,
'pageinfo' => $this->pageInfo,
'objectinfo' => $objectinfo,
'top_events' => $top_events,
'facebook_feed' => $facebook_feed,
'g_site_key' => getenv('G_SITE_KEY')
]);
}
/**
* @Route("/aquasvet/prazdniny/datum", methods={"POST"})
* @Route("/mestska-sportovni-hala/prazdniny/datum", methods={"POST"})
* @Route("/kino-svet/prazdniny/datum", methods={"POST"})
* @return Response
*/
public function prihlaska_datum(): JsonResponse
{
$date = $this->request->get('date');
$eid = $this->request->get('eid');
$id = ($eid!='')?System::decrypt($eid):0;
$age = '0';
//validace
if ((int)$id===0) {
$message = 'chyba zpracování';
$focus = 'id-date';
}
elseif ($date=='') {
$message = 'zadejte datum narození';
$focus = 'id-date';
}
elseif (!System::isDateCZ($date)) {
$message = 'špatný formát data narození';
$focus = 'id-date';
}
elseif (self::isFutureDate($date)) {
$message = 'nenarozené účastníky nebereme';
$focus = 'id-date';
}
else {
$age = self::ageFromDate($date);
$course = $this->model->getCourse((int)$id);
if ($age >= $course->getAgeFrom() && $age <= $course->getAgeTo()) {
$message = 'OK';
$focus = 'id-firstname';
}
else {
$message = 'účastník nespadá do věkové kategorie '.$course->getAgeFrom().' - '.$course->getAgeTo().'';
$focus = 'id-date';
}
}
$return = ['message' => $message, 'age' => $age, 'focus' => $focus];
return new JsonResponse($return);
}
/**
* @Route("/aquasvet/prazdniny/kapacita", methods={"POST"})
* @Route("/mestska-sportovni-hala/prazdniny/kapacita", methods={"POST"})
* @Route("/kino-svet/prazdniny/kapacita", methods={"POST"})
* @return Response
*/
public function prihlaska_kapacita(): JsonResponse
{
$eid = $this->request->get('eid');
$id = ($eid!='')?System::decrypt($eid):0;
//validace
if ((int)$id===0) {
$message = 'chyba zpracování';
$focus = 'id-date';
}
else {
$course = $this->model->getCourse((int)$id);
//$course->setActual(5);
$message = ($course->getActual() < $course->getCapacity())?'OK':'SUBST';
$return = ['message' => $message, 'actual' => $course->getActual(), 'capacity' => $course->getCapacity(), 'actual_capacity' => $course->getActualCapacity()];
return new JsonResponse($return);
}
$return = ['message' => $message, 'focus' => $focus, 'actual' => 0, 'capacity' => 0, 'actual_capacity' => '?/?'];
return new JsonResponse($return);
}
/**
* @Route("/aquasvet/prazdniny/odeslani", methods={"POST"})
* @Route("/mestska-sportovni-hala/prazdniny/odeslani", methods={"POST"})
* @Route("/kino-svet/prazdniny/odeslani", methods={"POST"})
* @return Response
* @throws Exception
*/
public function prihlaska_odeslani(): JsonResponse
{
sleep(1);
$eid = $this->request->get('eid');
$id = ($eid!='')?System::decrypt($eid):0;
$message = '';
$reload = '';
$focus = '';
$error = '1';
$age = '0';
$ac = '';
$date = $this->request->get('date');
$firstname = $this->request->get('firstname');
$lastname = $this->request->get('lastname');
$firstname_par = $this->request->get('firstname-par');
$lastname_par = $this->request->get('lastname-par');
$email = $this->request->get('email');
$phone = $this->request->get('phone');
$phone2 = $this->request->get('phone2');
$subst = $this->request->get('subst');
$cond = $this->request->get('cond');
$gdpr = $this->request->get('gdpr');
$note = $this->request->get('note');
$leaving = $this->request->get('leaving');
$swimskill = $this->request->get('swimskill');
$hasmedrestr = $this->request->get('hasmedrestr');
$medrestrtext = $this->request->get('medrestrtext');
//validace
if (!isset($_SERVER['HTTP_REFERER']) || strpos($_SERVER['HTTP_REFERER'], getenv('APP_URL')) !==0 || (int)$id===0) {
$message = 'chyba zpracování';
}
elseif ($date=='') {
$message = 'zadejte datum narození';
$focus = 'id-date';
}
elseif (!System::isDateCZ($date)) {
$message = 'špatný formát data narození';
$focus = 'id-date';
}
elseif (self::isFutureDate($date)) {
$message = 'nenarozené účastníky nebereme';
$focus = 'id-date';
}
elseif ($firstname=='') {
$message = 'zadejte křestní jméno účastníka';
$focus = 'id-firstname';
}
elseif ($lastname=='') {
$message = 'zadejte příjmení účastníka';
$focus = 'id-lastname';
}
elseif ((int)$leaving===0) {
$message = 'vyberte odchod účastníka';
$focus = 'id-leaving';
}
elseif ((int)$swimskill===0) {
$message = 'vyberte plaveckou zdatnost';
$focus = 'id-swimskill';
}
elseif ((int)$hasmedrestr===0) {
$message = 'vyberte zdravotní omezení';
$focus = 'id-hasmedrestr';
}
elseif ((int)$hasmedrestr===2 && $medrestrtext=='') {
$message = 'vypiště včechna zdravotní omezení';
$focus = 'id-medrestrtext';
}
elseif ($firstname_par=='') {
$message = 'zadejte křestní jméno zákonného zástupce';
$focus = 'id-firstname-par';
}
elseif ($lastname_par=='') {
$message = 'zadejte příjmení zákonného zástupce';
$focus = 'id-lastname-par';
}
elseif ($email=='') {
$message = 'zadejte e-mail zákonného zástupce';
$focus = 'id-email';
}
elseif (!System::isEmail($email)) {
$message = 'chybný formát e-mailu';
$focus = 'id-email';
}
elseif ($phone=='') {
$message = 'zadejte 1. telefon zákonného zástupce';
$focus = 'id-phone';
}
elseif (!System::isPhone($phone)) {
$message = 'chybný formát 1. telefonního čísla';
$focus = 'id-phone';
}
elseif ($phone2=='') {
$message = 'zadejte 2. telefon zákonného zástupce';
$focus = 'id-phone2';
}
elseif (!System::isPhone($phone2)) {
$message = 'chybný formát 2. telefonního čísla';
$focus = 'id-phone2';
}
elseif ($phone==$phone2) {
$message = 'telefonní čísla se nesmí shodovat';
$focus = 'id-phone2';
}
elseif ((int)$cond!==1) {
$message = 'potvrďte souhlas s podmínkami plavecké školy';
$focus = 'id-cond';
}
elseif ((int)$gdpr!==1) {
$message = 'potvrďte souhlas se zpracováním osobních údajů';
$focus = 'id-gdpr';
}
else {
$age = self::ageFromDate($date);
$pin = self::generatePIN($date, $firstname, $lastname);
$course = $this->model->getCourse($id);
$ac = $course->getActualCapacity();
$reg = new CampReg();
$reg->setAge($age);
$reg->setPin($pin);
$reg->setFirstname($firstname);
$reg->setLastname($lastname);
$reg->setFirstnamePar($firstname_par);
$reg->setLastnamePar($lastname_par);
$reg->setEmail($email);
$reg->setPhone($phone);
$reg->setPhone2($phone2);
$reg->setCourseId($id);
$reg->setDate($date);
$reg->setNote($note);
$reg->setLeaving((int)$leaving);
$reg->setSwimskill((int)$swimskill);
$reg->setHasmedrestr((int)$hasmedrestr);
$reg->setMedrestrtext($medrestrtext);
$reg->setSubst(((int)$subst===1));
if ($this->model->isAlreadyIn($pin, $id)) {
$message = 'na tento tábor jste již registrovaným účastníkem';
}
elseif ($age < $course->getAgeFrom() || $age > $course->getAgeTo()) {
$message = 'účastník nespadá do věkové kategorie '.$course->getAgeFrom().' - '.$course->getAgeTo();
$focus = 'id-date';
}
elseif ($course->getActual() >= $course->getCapacity() && (int)$subst==0) {
$message = 'bohužel jste se nestihli rezervovat, můžete se zaregistrovat jako náhradník';
}
elseif ($course->getActualSubst() >= $course->getCapacitySubst() && (int)$subst==1) {
$message = 'bohužel byl již naplněn také limit pro náhradníky';
}
else {
//captcha
/*$result = file_get_contents( 'https://www.google.com/recaptcha/api/siteverify', false, stream_context_create( array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query( array(
'response' => $_POST['g-recaptcha-response'],
'secret' => getenv('G_SECRET_KEY'),
'remoteip' => $_SERVER['REMOTE_ADDR']
) ),
),
) ) );
$result = json_decode($result);
if ($result->success) {*/
if (1==1) {
//vse je OK, ulozeni
try {
$rid = 0;
$pincode = '';
$this->model->saveReg($reg, $rid, $pincode);
$message = 'úspěšně odesláno';
$error = 0;
$eid = System::encrypt($rid);
$reg->setEid($eid);
$reg->setPincode($pincode);
$termines = $this->model->getTermines($id);
$files = $this->model->getFiles($id);
//$info = $this->model->getResInfo($ids);
$subject = 'Přihláška na příměstský tábor';
$body = '<h2>PŘIHLÁŠKA PŘÍMĚSTSKÝ TÁBOR</h2>';
$body .= '<p>děkujeme za vyplnění přihlášky na příměstský tábor.</p>';
$this->sendMail($reg, $course, $termines, $files, $subject, $body, false);
} catch (Exception $e) {
$message = $e->getMessage();
$focus = 'id-submit';
}
}
else {
$message = 'chyba bezpečnostní kontroly';
}
}
}
$return = ['message' => $message, 'error' => $error, 'age' => $age, 'focus' => $focus, 'reload' => $reload, 'actual_capacity' => $ac];
return new JsonResponse($return);
}
/**
* @Route("/aquasvet/prihlaska-na-tabor-{eid}")
* @Route("/aquasvet/prazdniny/prihlaska-{eid}")
* @Route("/mestska-sportovni-hala/prihlaska-na-tabor-{eid}")
* @Route("/mestska-sportovni-hala/prazdniny/prihlaska-{eid}")
* @Route("/kino-svet/prihlaska-na-tabor-{eid}")
* @Route("/kino-svet/prazdniny/prihlaska-{eid}")
* @return Response
* @throws Exception
* @throws \Facebook\Exceptions\FacebookSDKException
*/
public function moje_prihlaska($eid): Response
{
$model = new ObjectModel($this->db);
$objectinfo = $model->getObjectInfo($this->link);
$objectinfo->setTitle('Moje přihláška');
$objectinfo->setButtons([]);
$id = System::decrypt($eid);
//pokud nenalezeno, tak 404
if (!$objectinfo->isFound() || $eid=='' || System::decrypt($eid)=='' || (int)$id==0) {
return $this->render('/pages/404.html.twig', [
'pageinfo' => $this->pageInfo
]);
}
$model = new HomeModel($this->db);
$top_events = $model->getTopEvents(); //dump($top_events);
$facebook_feed = $model->getFacebookFeed();
$reg = $this->model->getReg($id);
$course = $this->model->getCourse($reg->getCourseId());
$termines = $this->model->getTermines($reg->getCourseId());
if ($reg->getFirstname() == '' || $course->getName() == '' || count($termines)===0) {
return $this->render('/pages/404.html.twig', [
'pageinfo' => $this->pageInfo
]);
}
$objectinfo->setSubtitle($course->getName());
return $this->render('/pages/camp_mycourse.html.twig', [
'pageinfo' => $this->pageInfo,
'objectinfo' => $objectinfo,
'top_events' => $top_events,
'facebook_feed' => $facebook_feed,
'reg' => $reg,
'course' => $course,
'termines' => $termines,
'eid' => $eid
]);
}
/**
* @Route("/prihlaska-na-tabor-{eid}")
* @return Response
* @throws Exception
* @throws \Facebook\Exceptions\FacebookSDKException
*/
public function moje_puvodni_link($eid): Response|RedirectResponse
{
$id = System::decrypt($eid);
//pokud nenalezeno, tak 404
if ($eid=='' || System::decrypt($eid)=='' || (int)$id==0) {
return $this->render('/pages/404.html.twig', [
'pageinfo' => $this->pageInfo
]);
}
$link = $this->model->GetObjectLink($id);
if ($link=='') {
return $this->render('/pages/404.html.twig', [
'pageinfo' => $this->pageInfo
]);
}
else {
return new RedirectResponse($link.'/prihlaska-na-tabor-'.$eid);
}
return new RedirectResponse('/');
}
/**
* @Route("/aquasvet/prazdniny")
* @Route("/mestska-sportovni-hala/prazdniny")
* @Route("/kino-svet/prazdniny")
* @return Response
* @throws \Facebook\Exceptions\FacebookSDKException
*/
public function prazdniny(): Response
{
$model = new ObjectModel($this->db);
$objectinfo = $model->getObjectInfo($this->link);
//pokud nenalezeno, tak 404
if (!$objectinfo->isFound()) return $this->render('/pages/404.html.twig', [
'pageinfo' => $this->pageInfo
]);
$model = new HomeModel($this->db);
$top_events = $model->getTopEvents();
$facebook_feed = $model->getFacebookFeed();
$courses = $this->model->getCourses($objectinfo->getId());
return $this->render('/pages/camp_courses.html.twig', [
'link' => $this->link,
'courses' => $courses,
'pageinfo' => $this->pageInfo,
'objectinfo' => $objectinfo,
'top_events' => $top_events,
'facebook_feed' => $facebook_feed
]);
}
/**
* @param $date
* @return float
* @throws \Exception
*/
private static function ageFromDate($date):float {
if(strlen($date) >= 8 && strlen($date) <= 10 && System::isDateCZ($date)) {
$birthday = new \DateTime($date);
$birthday->modify('first day of this month');
$diff = $birthday->diff(new \DateTime());
$months = $diff->format('%m') + 12 * $diff->format('%y');
$months++; //vzdy se prihlasujeme na nasledujici mesic, musim se jakoby narodit o mesic driv
return $months/12;
}
return 0;
}
/**
* @param $date
* @return bool
*/
private static function isFutureDate($date):bool {
$testing_date = new \DateTime($date);
$current_date = new \DateTime();
return ($testing_date > $current_date);
}
/**
* @param string $date
* @param string $name
* @param string $surname
* @return string
*/
public static function generatePIN(string $date, string $name,string $surname):string
{
$name = str_replace(' ', '', System::removeAccents2($name));
$surname = str_replace(' ', '', System::removeAccents2($surname));
$sourceString = substr($name, 0, 3).$surname;
$sum = 0;
for ($i = 0; $i < strlen($sourceString); $i++) {
$sum += self::letterPosInAlphabet($sourceString[$i]) * $i;
}
$sum = $sum.'';
$sum = substr($sum, 0, 4);
while(strlen($sum) < 4) {
$sum = $sum.'0';
}
$dateArray = explode('.', $date);
$dateArray[0] = sprintf("%02d", $dateArray[0]);
$dateArray[1] = sprintf("%02d", $dateArray[1]);
// odstranění prvních dvou čísel u roku ( 2017 -> 17 )
$dateArray[2] = substr($dateArray[2], 2);
return implode('', $dateArray).$sum;
}
/**
* @param string $letterOfAlphabet
* @return int
*/
private static function letterPosInAlphabet(string $letterOfAlphabet):int {
return ord(strtoupper($letterOfAlphabet)) - ord('A') + 1;
}
/**
* @param CampReg $reg
* @param CampCourse $course
* @param array $termines
* @param array $files
* @param string $subject
* @param string $body
* @param bool $internal
* @return void
* @throws \PHPMailer\PHPMailer\Exception
*/
private function sendMail(CampReg $reg, CampCourse $course, array $termines, array $files, string $subject, string $body, bool $internal = false, bool $canceled = true):void {
$body = $this->renderView('/partials/campreg_mail.html.twig', [
'app_url' => getenv('APP_URL'),
'reg' => $reg,
'course' => $course,
'termines' => $termines,
'files' => $files,
'sign' => true,
'canceled' => $canceled
]);
System::sendMail($course->getMailbox(), $subject, $body, $reg->getEmail(), $internal);
}
/**
* @Route("/aquasvet/prihlaska-na-tabor/zruseni-terminu", methods={"POST"})
* @return Response
* @throws Exception
* @throws \PHPMailer\PHPMailer\Exception
*/
public function zruseni_terminu(): JsonResponse
{
sleep(1);
$message = '';
$reload = '';
$focus = '';
$error = 1;
$pincode = $this->request->get('pincode');
$eid = $this->request->get('eid');
$reason = $this->request->get('reason');
$reason2 = $this->request->get('reason2');
$r_date = date('Y-m-d H:i:s');
//validace
if (!isset($_SERVER['HTTP_REFERER']) || strpos($_SERVER['HTTP_REFERER'], getenv('APP_URL')) !==0) {
$message = 'chyba zpracování';
}
elseif ($eid=='' || (int)System::decrypt($eid)==0) {
$message = 'chyba zpracování [2]';
}
elseif ($pincode=='') {
$message = 'zadejte PIN';
}
elseif (strlen($pincode)!=4 || !System::IsIntPosNum($pincode)) {
$message = 'chybný formát PIN kódu';
}
elseif ($reason=='') {
$message = 'vyberte důvod';
}
elseif ($reason=='jiný důvod' && $reason2=='') {
$message = 'zadejte jiný důvod';
}
else {
$id = System::decrypt($eid);
//$message = System::decrypt($eid);
$db_pin = $this->model->getPIN($id);
if ($pincode!=$db_pin) {
$message = 'chybný PIN kód';
}
else {
if ($reason=='jiný důvod') {
$reason = $reason2;
}
try {
//zruseni prihlasky a poptani nahradniku
$subst_rids = $this->model->cancelReg($id, $reason, $this);
$message = 'přihláška byla zrušena, děkujeme za informaci ';
$error = 0;
$reg = $this->model->getReg($id);
$course = $this->model->getCourse($reg->getCourseId());
$termines = $this->model->getTermines($reg->getCourseId());
$files = $this->model->getFiles($reg->getCourseId());
//rusejicimu e-mail hned
$subject = 'Zrušení přihlášky';
$body = '<h2>ZRUŠENÍ ÚČASTI NA PŘÍMĚSTSKÉM TÁBORU</h2>';
$body .= '<p>Přihláška byla zrušena z důvodu "<b>'.$reason.'</b>", děkujeme za informaci.</p>';
$this->sendMail($reg, $course, $termines, $files, $subject, $body, false, true);
//odeslani e-mailu nahradnikum pres frontu
if (is_array($subst_rids) && count($subst_rids)>0) {
foreach ($subst_rids as $r_id) {
//mail pres frontu
$reg = $this->model->getReg($r_id);
$course = $this->model->getCourse($reg->getCourseId());
$termines = $this->model->getTermines($reg->getCourseId());
$files = $this->model->getFiles($reg->getCourseId());
$r_email = $reg->getEmail();
$r_subject = 'Uvolnění příměstského tábora';
$html = '<p>'.str_replace(PHP_EOL, '<br/>', $course->getMailNomintext()).'</p>';
$html .= '<h4>Vaše přihláška</h4>';
$html .= $this->renderView('/partials/campreg_mail.html.twig', [
'app_url' => getenv('APP_URL'),
'reg' => $reg,
'course' => $course,
'termines' => $termines,
'files' => $files,
'sign' => true,
'canceled' => false
]);
/*
1 kurzyplavani@kultura-sport.cz
2 prazdniny@kultura-sport.cz
3 prazdniny-miniskola@kultura-sport.cz
4 prazdniny-aquasvet@kultura-sport.cz
5 prazdniny-kino@kultura-sport.cz
*/
$this->model->mailToQueue($r_email, $r_subject, $html, $r_date, $course->getMailbox());
}
}
} catch (Exception $e) {
$message = $e->getMessage();
}
}
}
$return = ['message' => $message, 'error' => $error, 'focus' => $focus, 'reload' => $reload];
return new JsonResponse($return);
}
}
?>