<?php
namespace App\Controller;
use DateTime;
use ZipArchive;
use App\Entity\IctusCommande;
use App\Entity\FacturePatient;
use App\Entity\TarifParDefaut;
use App\Entity\CommandeSpecial;
use App\Services\DomPDFService;
use App\Services\FactureService;
use App\Services\MailerServices;
use App\Services\IctocoinService;
use App\Repository\UserRepository;
use App\Repository\ZoneRepository;
use App\Services\OrangeSmsService;
use App\Repository\AdresseRepository;
use App\Services\NotificationService;
use App\Repository\ParcoursRepository;
use App\Repository\QuartierRepository;
use App\Entity\IctusHistoriquePaiement;
use App\Repository\LivraisonRepository;
use App\Repository\TarifZoneRepository;
use Doctrine\ORM\EntityManagerInterface;
use App\Services\SocieteLivraisonService;
use App\Repository\ZoneQuartierRepository;
use App\Repository\IctusCommandeRepository;
use App\Repository\IctusPharmacieRepository;
use App\Repository\TarifParDefautRepository;
use App\Repository\CommandeSpecialRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mailer\MailerInterface;
use App\Repository\EtatPrisenchargeRepository;
use App\Repository\NonDisponibiliteRepository;
use App\Repository\SocieteLivraisonRepository;
use Symfony\Component\HttpFoundation\Response;
use App\Repository\IctusEtatPaiementRepository;
use App\Repository\IctusTypePaiementRepository;
use App\Repository\TarifKilometriqueRepository;
use Symfony\Component\Routing\Annotation\Route;
use App\Repository\HistoriqueReglementRepository;
use App\Repository\IctusMobileAppareilRepository;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Services\api\NotificationTwoPackagesService;
use App\Repository\IctusHistoriquePaiementRepository;
use App\Services\NotificationSocieteLivraisonService;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
/**
* @Route("/ictus/commande/patient", name="app_ictus_commande_patient_")
* @IsGranted("ROLE_PHARMACIE")
*/
class IctusCommandePatientController extends AbstractController
{
private $em;
private $params;
public function __construct(EntityManagerInterface $em, ParameterBagInterface $params)
{
$this->em = $em;
$this->params = $params;
}
/**
* @Route("/", name="liste")
*/
public function index(IctusCommandeRepository $commandeRepository): Response
{
$where = array(
"pharmacie" => $this->getUser()->getIctusPharmacie()
);
$order = array(
"createdAt" => "DESC"
);
return $this->render('ictus_commande/index.html.twig', [
'commandes' => $commandeRepository->findBy($where, $order),
'enAttente' => $commandeRepository->getCountEnAttente($this->getUser()->getIctusPharmacie())[0]["nb"],
'menuActive' => 3
]);
}
/**
* @Route("/liste-special", name="liste_special")
*/
public function listeSpecial(CommandeSpecialRepository $commandeRepository): Response
{
$where = array(
"pharmacie" => $this->getUser()->getIctusPharmacie()
);
$order = array(
"createdAt" => "DESC"
);
return $this->render('ictus_commande/liste-special.html.twig', [
'commandes' => $commandeRepository->findBy($where, $order),
'menuActive' => 4,
'enAttente' => 0
]);
}
/**
* @Route("/detail/{id}", name="detail")
*/
public function detail(IctusCommande $commande): Response
{
return $this->render('ictus_commande/detail.html.twig', [
'commande' => $commande,
'menuActive' => 3
]);
}
/**
* @Route("/detail-cmd-speciale/{id}", name="detail_special")
*/
public function detailCmdSpecial(CommandeSpecial $commande): Response
{
return $this->render('ictus_commande/detailSpecial.html.twig', [
'commande' => $commande,
]);
}
/**
* @Route("/update-statut-livraison/{id}", name="update_statut_livrer")
*/
public function updateStatLivraison($id, IctusCommande $commande, Request $request, IctusCommandeRepository $ictusCommandeRepo): Response
{
if ($request->isMethod('POST')) {
$commande->setIsLivrer($request->get('is_livrer'));
$this->em->flush();
return new JsonResponse('OK');
}
$ictusCommandeRepo->updateIctusCommande($id, 1);
return new JsonResponse('NOK');
}
/**
* @Route("/disponible-commandespecial-form/{id}", name="disponible_commandespecial_form")
*/
public function disponibleCommandespecialForm(CommandeSpecial $commande, Request $request, IctocoinService $ictocoinService, MailerServices $mailerServices, MailerInterface $mi): Response
{
if ($request->isMethod('POST')) {
foreach ($commande->getCommandeSpecialLines() as $line) {
if ($request->get('prixunitaire-' . $line->getId()) == 0 && $request->get('valide-' . $line->getId()) != null) {
$this->addFlash('success', 'Erreur prix non defini');
return $this->redirectToRoute('app_ictus_commande_patient_liste_special');
}
$quantite = $line->getQuantite();
$newQuantite = $request->get('quantite-' . $line->getId());
if ($newQuantite > $quantite) {
$newQuantite = $quantite;
}
$isValide = 0;
if ($request->get('valide-' . $line->getId()) != null) {
$isValide = 1;
}
$line->setIsValide($isValide)->setQuantite($newQuantite)->setPrixunitaire($request->get('prixunitaire-' . $line->getId()));
$this->em->persist($line);
}
$commande->setIsValidePharmacie(1)->setDaysLimit(1);
$this->em->persist($commande);
$this->em->flush();
$raison = 'Frais de gestion sur la commande du ' . date("d M Y") . ', Référence :/cmd {{' . $commande->getId() . '}}';
$ictocoinService->debiter($this->getUser()->getIctusPharmacie(), $commande->getPrixTotal(), $raison);
//Envoie mail patient pour paiement ou recuperation
$to = $commande->getUser()->getEmail();
$from = "siteweb@ictuspharma.com";
$subject = "COMMANDE SPECIAL DEJA DISPONIBLE";
$templateMail = 'emails/disponibleCommandeSpecial.html.twig';
$paramsMail = [
'dayslimit' => 1,
'link' => "https://ictuspharm.com/commande/historique/non-payer",
'numeroCommande' => "ICT_CMD_SP_" . $commande->getId(),
'pharmacy' => $commande->getPharmacie()->getDesignation()
];
$mailerServices->send($mi, $to, $from, $subject, $templateMail, $paramsMail);
return $this->redirectToRoute('app_ictus_commande_patient_liste_special');
}
}
/**
* @Route("/validate-commandespecial-form/{id}", name="validate_commandespecial_form")
*/
public function validateCommandespecialForm(CommandeSpecial $commande, Request $request, MailerServices $mailerServices, MailerInterface $mi): Response
{
if ($request->isMethod('POST')) {
foreach ($commande->getCommandeSpecialLines() as $line) {
$quantite = $line->getQuantite();
$newQuantite = $request->get('quantite-' . $line->getId());
if ($newQuantite > $quantite) {
$newQuantite = $quantite;
}
$isValide = 0;
if ($request->get('valide-' . $line->getId()) != null) {
$isValide = 1;
}
$line->setIsValide($isValide)->setQuantite($newQuantite);
$this->em->persist($line);
}
}
$grossiste = $this->getUser()->getGrossiste();
$commande->setIsValidePharmacie(true)->setGrossiste($grossiste);
$to = $grossiste->getEmail();
$from = "siteweb@ictuspharma.com";
$subject = "COMMANDE SPECIAL ICTUSPHARMA";
$templateMail = 'emails/commandeSpecialGrossiste.html.twig';
$paramsMail = [
'link' => "https://ictuspharm.com/grossiste/commandespecial/clients/detail/" . $commande->getId(),
'numeroCommande' => "ICT_CMD_SP_" . $commande->getId(),
'pharmacy' => $commande->getPharmacie()->getDesignation()
];
$mailerServices->send($mi, $to, $from, $subject, $templateMail, $paramsMail);
$this->em->persist($commande);
$this->em->flush();
return $this->redirectToRoute('app_ictus_commande_patient_liste_special');
}
//******icic */
/**
* @Route("/validate/{id}", name="validate_commande")
*/
public function validation(IctusCommande $commande, $etat, MailerServices $mailerServices, MailerInterface $mi): Response
{
$commande->setIsValide($etat);
$this->em->persist($commande);
$this->em->flush();
if ($etat == 0) {
$to = $commande->getUser()->getEmail();
$from = "siteweb@ictuspharma.com";
$subject = "COMMANDE REFUSEE";
$templateMail = 'emails/refusCommandeSpecial.html.twig';
$paramsMail = [
'numeroCommande' => "ICT_CMD_" . $commande->getId(),
'pharmacy' => $commande->getPharmacie()->getDesignation()
];
$mailerServices->send($mi, $to, $from, $subject, $templateMail, $paramsMail);
}
return $this->redirectToRoute('app_ictus_commande_patient_liste');
}
/**
* @Route("/refuscommande/{id}", name="refus_commande")
*/
public function refusCommande(
IctusCommande $commande,
MailerServices $mailerServices,
MailerInterface $mi,
Request $request,
NotificationTwoPackagesService $notificationService,
IctusMobileAppareilRepository $mobileAppareilRepo
): Response {
//REFUS
if ($request->isMethod('POST')) {
$commande->setIsValide(0)->setRaisonAnnulation($request->get('raison'));
$this->em->persist($commande);
$this->em->flush();
$to = $commande->getUser()->getEmail();
$from = "siteweb@ictuspharma.com";
$subject = "Commande refusée";
$templateMail = 'emails/refusCommandeSpecial.html.twig';
$paramsMail = [
'numeroCommande' => "ICTCMD_MG_" . $commande->getPharmacie()->getId() . "_" . $commande->getReference(),
'pharmacy' => $commande->getPharmacie()->getDesignation(),
'raison' => $request->get('raison')
];
$mailerServices->send($mi, $to, $from, $subject, $templateMail, $paramsMail);
//SEND NOTIFICATION DANS PATIENT
$notificationService->pushNotification($commande, $mobileAppareilRepo, $subject);
//Fin envoie notification
return $this->redirectToRoute('app_ictus_commande_patient_liste');
}
}
/**
* @Route("/validateCommande/{id}", name="validate_commande_form")
*/
public function validateCommande($id, OrangeSmsService $orangeSmsService, AdresseRepository $adresseRepo, IctusPharmacieRepository $ictusPharmacieRepo, ParcoursRepository $parcoursRepo, QuartierRepository $quartierRepo, ZoneRepository $zoneRepo, NonDisponibiliteRepository $nonDisponibiliteRepo, LivraisonRepository $livraisonRepo, TarifParDefautRepository $tarifParDefautRepo, ZoneQuartierRepository $zoneQuartierRepo, UserRepository $userRepo, TarifKilometriqueRepository $tarifKilometriqueRepo, TarifZoneRepository $tarifZoneRepo, SocieteLivraisonService $societeLivraisonService, SocieteLivraisonRepository $societeLivraisonRepo, IctusCommandeRepository $ictusCommandeRepo, IctusCommande $commande, Request $request, IctocoinService $ictocoinService, MailerServices $mailerServices, MailerInterface $mi, FactureService $factureService, /* NotificationTwoPackagesService $notificationService, */ IctusMobileAppareilRepository $mobileAppareilRepo, EtatPrisenchargeRepository $etatPrisenchargeRepo, IctusEtatPaiementRepository $ictusEtatPaiementRepo, NotificationSocieteLivraisonService $notificationSLService, NotificationService $notificationService): Response
{
if ($request->isMethod('POST')) {
$prisencharge = null;
foreach ($commande->getIctusCommandeLines() as $line) {
if ($line->getChanged() == null) {
$quantite = $line->getQuantite();
$remarque = null;
$isPrisencharge = null;
$newQuantite = $request->get('quantite-' . $line->getId());
$prix = $request->get('prix-' . $line->getId());
if ($request->get('remarque-' . $line->getId()) != "") {
$remarque = $request->get('remarque-' . $line->getId());
}
if ($newQuantite > $quantite) {
$newQuantite = $quantite;
}
$isValide = 0;
if ($request->get('valide-' . $line->getId()) != null) {
$isValide = 1;
}
if ($request->request->has('prisencharge-' . $line->getId())) {
if ($request->get('prisencharge-' . $line->getId()) != null) {
$isPrisencharge = 1;
}
}
$line->setIsValide($isValide)->setQuantite($newQuantite)->setPrixunitaire($prix)->setRemarque($remarque)->setIsPrisencharge($isPrisencharge);
$this->em->persist($line);
}
}
if ($request->request->has('prisencharge')) {
if ($request->get('prisencharge') != "" && $request->get('prisencharge') != 0) {
$prisencharge = $commande->getPrisencharge();
if ($prisencharge != null) {
$partielementPayer = $ictusEtatPaiementRepo->find(3);
$etat = $etatPrisenchargeRepo->find(2);
$prisencharge->setEtat($etat)->setPrisencharge($request->get('prisencharge'));
$this->em->persist($prisencharge);
$historiquePaiement = new IctusHistoriquePaiement();
$montant = $commande->getTotalCommande(true) * $request->get('prisencharge') / 100;
$historiquePaiement->setCommande($commande)->setMontant($montant);
$this->em->persist($historiquePaiement);
$commande->setEtatpaiement($partielementPayer);
}
}
}
$commandeRemise = null;
if ($request->get('remise') !== null && $request->get('remise') != "") {
$commandeRemise = $request->get('remise');
}
$commande->setIsValide(true)->setRemise($commandeRemise);
$this->em->persist($commande);
$this->em->flush();
$factureService->editPatient($commande, $prisencharge);
$raison = 'Profit Ictuspharma sur la commande du ' . date("d M Y") . ', Référence :/cmd {{' . $commande->getId() . '}}';
$montantDebit = $ictocoinService->montantIctocoin($commande->getPharmacie()->getid(), $commande->getTotalCommande());
$ictocoinService->debiter($this->getUser()->getIctusPharmacie(), $montantDebit, $raison);
$to = $commande->getUser()->getEmail();
$from = "siteweb@ictuspharma.com";
$subject = "VALIDATION COMMANDE";
$templateMail = 'emails/validationCommande.html.twig';
$paramsMail = [
'link' => "https://ictuspharm.com/commande/historique/non-payer",
'numeroCommande' => "ICT_CMD_" . $commande->getId(),
'pharmacy' => $commande->getPharmacie()->getDesignation()
];
$mailerServices->send($mi, $to, $from, $subject, $templateMail, $paramsMail);
//envoye message livreur de la societe de livraison choisi
$ictusCommande = $ictusCommandeRepo->findById($id);
$sl = null;
$parcours = $ictusCommande->getParcours();
if ($parcours!= null) {
$sl = $parcours->getLivraison()->getSocieteLivraison();
}
//dd($sl2->getUsers()[0]);
//$sl = $ictusCommande->getSocieteLivraison();
//$pt = $ictusCommande->getUser();
if ($sl) {
$user_sl = $sl->getUsers()[0];
$mobileAppareils = $mobileAppareilRepo->findAllToArray($user_sl);
$array_cfm_token = array_unique((array_column($mobileAppareils, "cfm_tokem")));
if (!empty($array_cfm_token)) {
$data = [
'type' => 'delivery_request',
'status' => 'validated_by_pharmacy',
'click_action' => 'FLUTTER_NOTIFICATION_CLICK', // utile si tu as une app Flutter
];
foreach ($array_cfm_token as $token) {
$notificationSLService->sendNotification(
$token,
'Nouvelle demande de livraison',
'Demande validée par la pharmacie, veuillez attribuer un livreur.',
$data
);
}
}
}
/*Livraison*/
//if commande.livraison is not null envoie notification User Societe de livraison $user[0] where role ROLE_SOCIETE_LIVRAISON
//Message : Demande valider par la pharmacie, veuillez attribuer un livreur a cette demande
/*Livraison*/
//SEND NOTIFICATION DANS PATIENT
/* $notificationService->pushNotification($commande, $mobileAppareilRepo, $subject); */
//Fin envoie notification
return $this->redirectToRoute('app_ictus_commande_patient_liste');
}
}
/**
* @Route("/pharmacie/validation/commande/{code}/{codeSecret}", name="app_pharmacie_validation_commande")
*/
public function validationCommande($code, $codeSecret, IctusPharmacieRepository $ictusPharmacieRepo, IctusCommandeRepository $ictusCommandeRepo, UserRepository $userRepo, SocieteLivraisonRepository $societeLivraisonRepo): Response
{
if (!$this->getUser()) {
return $this->redirectToRoute('login');
} else {
$user = $this->getUser();
$ictusPharmacie = $ictusPharmacieRepo->findById($user->getIctusPharmacie()->getId());
$commande = $ictusCommandeRepo->findIctusCommandeByCodeEtCodeSecretPharmacie($code, $codeSecret, $ictusPharmacie);
if ($commande) {
$commande->setIsRecuperer(1);
$ictusCommandeRepo->ReinitCodeCodeSecret($commande->getId());
} else {
dd("a verifier ");
}
}
}
/**
* @Route("/pharmacie/validation/manuel/{id}" ,name="validation_manuel")
*/
public function validationCommandeManuel($id, Request $request, IctusTypePaiementRepository $ictusTypePaiementRepo, IctusPharmacieRepository $ictusPharmacieRepo, IctusCommandeRepository $ictusCommandeRepo, UserRepository $userRepo, SocieteLivraisonRepository $societeLivraisonRepo, IctusEtatPaiementRepository $ictusEtatPaiementRepo)
{
$role = $request->get('role');
$codeSecret = $request->get('codeSecret');
$user = $this->getUser();
$ictusPharmacie = $ictusPharmacieRepo->findById($user->getIctusPharmacie()->getId());
$commande = $ictusCommandeRepo->findIctusCommandeByCodeEtCodeSecretPharmacie($id, $codeSecret, $ictusPharmacie);
if ($commande && $commande->isIsValide() == true) {
$paiement = $ictusEtatPaiementRepo->find(2);
if ($role == 'patient') {
$commande->setIsLivrer(1);
//add historique
$historiquePaiement = new IctusHistoriquePaiement();
$dateNow = new DateTime();
$typeEspece = $ictusTypePaiementRepo->find(1);
$historiquePaiement->setCreatedAt($dateNow)->setCommande($commande)->setMontant($commande->getTotalCommande())->setIctusTypePaiement($typeEspece);
$this->em->persist($historiquePaiement);
$ictusCommandeRepo->ReinitCodeCodeSecret($commande->getId());
} elseif ($role == 'livreur') {
$commande->setIsRecuperer(1);
$ictusCommandeRepo->ReinitCodeCodeSecret($commande->getId());
}
$commande->setEtatpaiement($paiement);
$this->em->persist($commande);
$this->em->flush($commande);
$this->addFlash('success', 'La commande a été marquée comme récupérée.');
return $this->redirectToRoute('app_ictus_commande_patient_liste');
} else {
$this->addFlash('success', 'La commande n\'a pas encore été validée.');
return $this->redirectToRoute('app_ictus_commande_patient_detail', ['id' => $id]);
}
}
/**
* @Route("/recuperer-commande-bycode/{commande}", name="recuperer_commande_bycode")
*/
public function recupererCommandeBycode(IctusCommande $commande, Request $request, IctusEtatPaiementRepository $ictusEtatPaiementRepo)
{
if ($commande) {
if ($commande->getCodeSecret() == $request->get("secret")) {
$paiement = $ictusEtatPaiementRepo->find(2);
$commande->setIsLivrer(true)->setEtatpaiement($paiement);
$this->em->persist($commande);
$this->em->flush($commande);
$this->addFlash('success', 'La commande a été marquée comme récupérée.');
} else {
$this->addFlash('error', 'Erreur de code secret');
return $this->redirectToRoute('app_ictus_commande_patient_liste');
}
}
}
/**
* @Route("facture/pdf/{facturepatient}", name="facture_pdf")
*/
public function facturePdf(FacturePatient $facturepatient, DomPDFService $pdfService): Response
{
$project_dir = $this->params->get('kernel.project_dir');
$logo = $project_dir . "/public/assets/img/logo-mini.webp";
$render_template = 'ictus_commande/facturePdf.html.twig';
$titre = "FACT_PHARM_MD_" . $facturepatient->getPharmacie()->getId() . "_" . $facturepatient->getId();
$file_name = $titre;
$data = [
'facture' => $facturepatient,
'logo' => $logo
];
$pdfService->export($file_name, $render_template, $file_name, $data);
return new Response(json_encode("OK"));
}
}