<?php
namespace App\Controller;
use App\Entity\AppelSujet;
use App\Entity\Apprenant;
use App\Entity\Rdv;
use App\Entity\Utilisateur;
use App\Form\RdvType;
use App\Service\GoogleCalendre;
use Google_Client;
use Google_Service_Calendar;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* Reporting controller.
*
* @Route("rdv")
*
*/
class RdvController extends AbstractController
{
/**
* @Route("/OP", name="rdv_index")
*/
public function rdv_index()
{
$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
$calendre = new GoogleCalendre($this->getDoctrine());
$calendre->itemsEvents();
$client = new Google_Client();
$client->setAuthConfig('ideodashcalendar.json');
$client->setApplicationName('IdeoCalendar');
$client->addScope(Google_Service_Calendar::CALENDAR_EVENTS);
$service = new Google_Service_Calendar($client);
$calendarId = $user->getCalendarId();
if (!empty($calendarId)) {
$optParams = array(
'maxResults' => 100,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c', strtotime(" -100 days")),
);
$results = $service->events->listEvents($calendarId, $optParams);
$items = $results->getItems();
// Mettre à jour la liste des Rdv Calendly
$this->updateCalendyEvents($em, $user, $items);
}
// $rdvs = $em->getRepository(Rdv::class)->findBy(array('agentRecepteur' => $user));
$rdvs = $em->getRepository(Rdv::class)->findBy([], ["id" => "DESC"], 301);
$agents = $em->getRepository(Utilisateur::class)->findBy(['id' => [100, 97, 84, 52]]);
return $this->render('rdv/index.html.twig', [
'rdvs' => $rdvs,
'agents' => $agents,
]);
}
function extractZoomLink($text)
{
// Pattern to match Zoom links with meeting ID and password
$pattern = '/https:\/\/us\d+web\.zoom\.us\/j\/\d+\?pwd=[a-zA-Z0-9]+\.[0-9]/';
// Perform the match
if (preg_match($pattern, $text, $matches)) {
return $matches[0];
}
return null;
}
/**
* @Route("/mine/OP", name="rdv_mine")
*/
public function rdv_mine()
{
$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
$calendre = new GoogleCalendre($this->getDoctrine());
$calendre->itemsEvents();
$client = new Google_Client();
$client->setAuthConfig('ideodashcalendar.json');
$client->setApplicationName('IdeoCalendar');
$client->addScope(Google_Service_Calendar::CALENDAR_EVENTS);
$service = new Google_Service_Calendar($client);
$calendarId = $user->getCalendarId();
if (!empty($calendarId)) {
$optParams = array(
'maxResults' => 300,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c', strtotime(" -30 days")),
'timeMax' => date('c', strtotime(" +30 days")),
);
$results = $service->events->listEvents($calendarId, $optParams);
$items = $results->getItems();
// Mettre à jour la liste des Rdv Calendly
$this->updateCalendyEvents($em, $user, $items);
}
$rdvs = $this->getDoctrine()->getRepository(Rdv::class)->findBy(array('agentRecepteur' => $user));
if ($user->getRoles()[0] == 'ROLE_OP') {
return $this->render('rdv/coach/todayRdv.html.twig', [
'rdvs' => $rdvs,
]);
}
$agents = $em->getRepository(Utilisateur::class)->findBy(['id' => [100, 97, 84, 52]]);
return $this->render('rdv/index.html.twig', [
'rdvs' => $rdvs,
'agents' => $agents,
]);
}
/**
* @Route("/byUser/{user}/OP", name="rdv_user_id")
*/
public function rdv_user_id(Utilisateur $user)
{
$em = $this->getDoctrine()->getManager();
$calendre = new GoogleCalendre($this->getDoctrine());
$calendre->itemsEvents();
$client = new Google_Client();
$client->setAuthConfig('ideodashcalendar.json');
$client->setApplicationName('IdeoCalendar');
$client->addScope(Google_Service_Calendar::CALENDAR_EVENTS);
$service = new Google_Service_Calendar($client);
$calendarId = $user->getCalendarId();
if (!empty($calendarId)) {
$optParams = array(
'maxResults' => 300,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c', strtotime(" -30 days")),
'timeMax' => date('c', strtotime(" +30 days")),
);
$results = $service->events->listEvents($calendarId, $optParams);
$items = $results->getItems();
// Mettre à jour la liste des Rdv Calendly
$this->updateCalendyEvents($em, $user, $items);
}
$rdvs = $this->getDoctrine()->getRepository(Rdv::class)->findBy(array('agentRecepteur' => $user));
if ($user->getRoles()[0] == 'ROLE_OP') {
return $this->render('rdv/coach/todayRdv.html.twig', [
'rdvs' => $rdvs,
]);
}
$agents = $em->getRepository(Utilisateur::class)->findBy(['id' => [100, 97, 84, 52]]);
return $this->render('rdv/index.html.twig', [
'rdvs' => $rdvs,
'agents' => $agents,
'currentAgentId' => $user->getId(),
]);
}
/**
* @Route("/annule/OP", name="rdv_annule")
*/
public function rdv_annule()
{
$rdvs = $this->getDoctrine()->getRepository(Rdv::class)->findBy(["statut" => 2], ['id' => "DESC"], 100);
return $this->render('rdv/rdv_annule.html.twig', ['rdvs' => $rdvs]);
}
/**
* @Route("/injoignable/OP", name="rdv_injoignable")
*/
public function rdv_injoignable()
{
$rdvs = $this->getDoctrine()->getRepository(Rdv::class)->findBy(["statut" => 3], ['id' => "DESC"], 100);
return $this->render('rdv/rdv_injoignable.html.twig', ['rdvs' => $rdvs]);
}
/**
* @Route("/{id}/edit/OP", name="rdv_edit")
*/
public function editAction(Request $request, Rdv $rdv)
{
$em = $this->getDoctrine()->getManager();
$utilisateurs = $em->getRepository(Utilisateur::class)->findCPSPOP();
$editForm = $this->createForm(RdvType::class, $rdv);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->getDoctrine()->getManager()->flush();
$this->addFlash('success', 'Rdv a été modifié');
return $this->redirectToRoute('rdv_index');
}
return $this->render('rdv/edit.html.twig', array(
'utilisateurs' => $utilisateurs,
'rdv' => $rdv,
'form' => $editForm->createView(),
));
}
/**
* @Route("/{id}/validate/OP", name="rdv_validate")
*/
public function validateAction(rdv $rdv)
{
$em = $this->getDoctrine()->getManager();
$rdv->setStatut(1);
$em->persist($rdv);
$em->flush();
return $this->redirectToRoute('rdv_index');
}
/**
* Lists all rdv entities today.
* @Route("/mine-today/OP", name="rdv_mine_today")
*/
public function mineTodayAction()
{
$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
$client = new Google_Client();
$client->setAuthConfig('ideodashcalendar.json');
$client->setApplicationName('IdeoCalendar');
$client->addScope(Google_Service_Calendar::CALENDAR_EVENTS);
$service = new Google_Service_Calendar($client);
$calendarId = $user->getCalendarId();
if (!empty($calendarId)) {
$optParams = array(
'maxResults' => 100,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c', strtotime(" -10 days")),
);
$results = $service->events->listEvents($calendarId, $optParams);
$items = $results->getItems();
// Mettre à jour la liste des Rdv Calendly
$this->updateCalendyEvents($em, $user, $items);
}
$today = date('Y-m-d', strtotime('today'));
$todayStart = $today . "T00:00";
$todayEnd = $today . "T23:59";
$rdvs = $em->getRepository(Rdv::class)->findAllMyRdvByDate($user, $todayStart, $todayEnd);
return $this->render('rdv/coach/todayRdv.html.twig', [
'rdvs' => $rdvs,
]);
}
// recupperer l'ID de l'evenement de Callendly
public function getCalendlyRdvId($text)
{
if (str_contains($text, "EventId")) {
$ArrayExplode = explode(" ", $text);
foreach ($ArrayExplode as $result) {
$ArrayExplode2 = explode("\n", $result);
foreach ($ArrayExplode2 as $result2) {
if (str_contains($result2, "EventId")) {
$calendlyRdvId = explode('EventId:', str_replace(" ", "", $result2));
$calendlyRdvId = $calendlyRdvId[1];
return $calendlyRdvId;
}
}
}
} elseif (str_contains($text, "reschedulings")) {
$ArrayExplode = explode(" ", $text);
foreach ($ArrayExplode as $result) {
$ArrayExplode2 = explode("\n", $result);
foreach ($ArrayExplode2 as $result2) {
if (str_contains($result2, "reschedulings")) {
$calendlyRdvId = explode("/reschedulings/", str_replace(" ", "", $result2));
$calendlyRdvId = $calendlyRdvId[1];
return $calendlyRdvId;
}
}
}
} elseif (str_contains($text, "uuid=")) {
$ArrayExplode = explode(" ", $text);
foreach ($ArrayExplode as $result) {
$ArrayExplode2 = explode("\n", $result);
foreach ($ArrayExplode2 as $result2) {
if (str_contains($result2, "uuid=")) {
$calendlyRdvId = explode("uuid=", str_replace(" ", "", $result2));
$calendlyRdvId = $calendlyRdvId[1];
return $calendlyRdvId;
}
}
}
} else {
return "Ko!";
}
}
// Metre à jour les evenements Calendly par Agent/Coach
public function updateCalendyEvents($em, $user, $items)
{
$today = date("Y-m-d") . 'T';
$rdvsToDelete = $em->createQuery(
'SELECT r FROM App\Entity\Rdv r WHERE r.appel is null AND r.agentEmetteur = 12 AND r.agentRecepteur IN (100,97,84,52) AND r.date LIKE :today'
)->setParameter('today', $today . '%')
->getResult();
foreach ($rdvsToDelete as $rdvToDelete) {
$em->remove($rdvToDelete);
}
if (!empty($rdvsToDelete)) {
$em->flush();
}
foreach ($items as $item) {
$calendlyRdvId = "";
$descrption = $item->description;
$summary = $item->summary;
if (str_contains($summary, 'Canceled:')) {
$start = ($item->start->dateTime) ? explode(':', $item->start->dateTime)[0] . ':' . explode(':', $item->start->dateTime)[1] : "";
$rdvBd = $em->getRepository(Rdv::class)->findBy(array('date' => $start, 'agentRecepteur' => $user));
if (!empty($rdvBd)) {
$em->remove($rdvBd[0]);
$em->flush();
}
continue;
}
if ($this->getCalendlyRdvId($descrption) != "Ko!") {
$calendlyRdvId = $this->getCalendlyRdvId($descrption);
}
$etat = explode(' :', $item->getSummary());
$start = ($item->start->dateTime) ? explode(':', $item->start->dateTime)[0] . ':' . explode(':', $item->start->dateTime)[1] : "";
$rdvBd = $em->getRepository(Rdv::class)->findBy(array('date' => $start, 'agentRecepteur' => $user));
if (!$rdvBd) {
if ($etat[0] != 'Annulé') {
if (isset($item->attendees[0]) and !empty($item->attendees[0]['email']) and $item->attendees[0]['email'] != "elearning@ideolearning.com") {
// dump($item);
$email = $item->attendees[0]['email'];
$apprenant = $em->getRepository(Apprenant::class)->findOneByUsername($email);
if (empty($apprenant) and isset($item->attendees[0]) and !empty($item->attendees[0]['email']) and $item->attendees[0]['email'] != "elearning@ideolearning.com") {
$email = $item->attendees[0]['email'];
$apprenant = $em->getRepository(Apprenant::class)->findOneByEmail($email);
}
if (empty($apprenant) and isset($item->attendees[1]) and !empty($item->attendees[1]['email']) and $item->attendees[1]['email'] != "elearning@ideolearning.com") {
$email = $item->attendees[1]['email'];
$apprenant = $em->getRepository(Apprenant::class)->findOneByEmail($email);
}
}
if (empty($apprenant)) {
if (array_key_exists(1, explode('(Ex: a.alaoui@YourCompany.com): ', $descrption))) {
$username2 = explode('(Ex: a.alaoui@YourCompany.com): ', $descrption)[1];
$username2 = explode(chr(10), $username2)[0];
$apprenant = $em->getRepository(Apprenant::class)->findOneByUsername($username2);
if (empty($apprenant))
$apprenant = $em->getRepository(Apprenant::class)->findOneByEmail($username2);
}
}
if (!empty($apprenant)) {
$rdvBd = new rdv();
$prof = $em->getRepository(Utilisateur::class)->findById($user);
$rdvBd->setAgentRecepteur($prof[0]);
$maj = $em->getRepository(Utilisateur::class)->findById(12);
$rdvBd->setAgentEmetteur($maj[0]);
$appelSujet = $em->getRepository(AppelSujet::class)->findOneById(3);
$rdvBd->setSujet($appelSujet);
$rdvBd->setStatut(0);
$rdvBd->setCalendlyRdvId($calendlyRdvId);
$rdvBd->setDate($start);
$rdvBd->setApprenant($apprenant);
$rdvBd->setCommentaire($item->getSummary());
$zoomLink = $this->extractZoomLink(isset($item->description) ? $item->description : "");
if ($zoomLink) {
$rdvBd->setZoomLink($zoomLink);
}
$rdvBd->setDateInsert(date("Y-m-d\TH:i:s", strtotime("+1 hour")));
$rdvBd->setEtat(2);
$em->persist($rdvBd);
$em->flush();
}
}
} elseif ($etat[0] == 'Annulé') {
$rdvBd[0]->setStatut(2);
$rdvBd[0]->setCalendlyRdvId($calendlyRdvId);
$em->persist($rdvBd[0]);
$em->flush();
} else {
$rdvBd[0]->setCalendlyRdvId($calendlyRdvId);
$em->persist($rdvBd[0]);
$em->flush();
}
}
}
/**
* @Route("/rdv-detail/{id}", name="rdv_detail")
* @return void
**/
public function rdv_detail(Rdv $rdv)
{
$response["topic"] = $rdv->getSujet()->getId();
$response["date"] = $rdv->getDate();
$response["status"] = $rdv->getStatut();
$response["agent"] = $rdv->getAgentRecepteur()->getId();
$resp = new Response(json_encode($response, JSON_UNESCAPED_UNICODE));
$resp->headers->set('Content-Type', 'application/json');
return $resp;
}
/**
* @Route("/rdv-edit/{id}/OP", name="edit-rdv-ajax")
*/
public function edit_rdvAction(Rdv $rdv)
{
try {
$em = $this->getDoctrine()->getManager();
$appelSujet = $em->getRepository(AppelSujet::class)->findOneById($_POST["rdv-topic"]);
$user = $em->getRepository(Utilisateur::class)->findOneById($_POST["rdv-agent"]);
$rdv->setSujet($appelSujet);
$rdv->setDate($_POST["rdv-date"]);
$rdv->setStatut($_POST["rdv-status"]);
$rdv->setAgentRecepteur($user);
$em->persist($rdv);
$em->flush();
$response["date"] = date_format(date_create($_POST["rdv-date"]), 'd/m/Y H:i:s');
} catch (\Throwable $th) {
$response["error"] = "an error has occurred";
}
$response["success"] = "Appointment has been edited successfully";
$resp = new Response(json_encode($response, JSON_UNESCAPED_UNICODE));
$resp->headers->set('Content-Type', 'application/json');
return $resp;
}
/**
* @Route("/rdvsrecepteur/OP", name="rdvs-recepteur-ajax")
*/
public function rdvsrecepteur()
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser()->getId();
$rdvs = $em->getRepository(Rdv::class)->findRdvByAgentRecepteur($user);
$rendvs = array();
foreach ($rdvs as $k => $rdv) {
$rendvs[$k]['id'] = $rdv->getId();
$rendvs[$k]['apprenant'] = $rdv->getapprenant()->getId();
$rendvs[$k]['date'] = $rdv->getDate();
$rendvs[$k]['username'] = $rdv->getapprenant()->getUsername();
}
$resp = new Response(json_encode($rendvs, JSON_UNESCAPED_UNICODE));
$resp->headers->set('Content-Type', 'application/json');
return $resp;
}
}