<?php
namespace App\Entity\Formation;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Entity\User;
use App\Repository\Formation\ClasseRepository;
use App\Traits\Actions;
use App\Entity\Schoolyear;
use DateInterval;
use DatePeriod;
use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: ClasseRepository::class)]
#[ORM\Table(name: 'hs_tc_formation_classe')]
#[ApiResource]
class Classe implements \Stringable
{
use Actions;
#[ORM\ManyToOne(inversedBy: 'classes')]
private ?Activity $activity = null;
#[ORM\ManyToOne(targetEntity: Schoolyear::class)]
#[ORM\JoinColumn(nullable: true)]
private ?Schoolyear $schoolyear = null;
#[ORM\OneToMany(mappedBy: "classe", targetEntity: Participant::class)]
#[ORM\OrderBy(["regNumber" => "ASC"])]
private Collection $participants;
#[ORM\OneToMany(mappedBy: "classe", targetEntity: Attribution::class, cascade: ["persist"], orphanRemoval: true)]
private Collection $attributions;
#[ORM\OneToMany(mappedBy: "classe", targetEntity: Timetable::class, cascade: ["persist"], orphanRemoval: true)]
private Collection $timetables;
#[ORM\ManyToOne(targetEntity: User::class, inversedBy: "classes")]
#[ORM\JoinColumn(nullable: true)]
private ?User $responsable;
#[ORM\Column(type: "string", nullable: true)]
private ?string $label;
#[ORM\Column(name: 'start_at', type: 'datetime')]
private \DateTime $startAt;
#[ORM\Column(name: 'end_at', type: 'datetime')]
private \DateTime $endAt;
#[ORM\Column(name: "monthly_payment", type: "float", nullable: true)]
private ?float $monthlyPayment;
#[ORM\Column(name: "register_costs", type: "float", nullable: true)]
private ?float $registerCosts;
#[ORM\Column(name: "other_costs", type: "string", nullable: true)]
private ?string $otherCosts;
#[ORM\Column(type: "integer", nullable: true)]
private int $nbrMonths=0;
#[ORM\Column(type: "json", nullable: true)]
private array $listMonths=[];
#[ORM\Column(name: 'graduation_at', type: 'datetime', nullable: true)]
private ?\DateTime $graduationAt=null;
#[ORM\Column(type: 'boolean')]
private bool $opened = false;
public function __construct()
{
$this->participants = new ArrayCollection();
// date_default_timezone_set('Africa/Casablanca');
$this->createAt=new \DateTime('now');
$this->published=true;
}
/**
* Set activity
*
*
* @return Classe
*/
public function setActivity(Activity $activity)
{
$this->activity = $activity;
return $this;
}
/**
* Get activity
*
* @return Activity
*/
public function getActivity()
{
return $this->activity;
}
/**
* @return Schoolyear
*/
public function getSchoolyear()
{
return $this->schoolyear;
}
/**
* @param Schoolyear|null $schoolyear
* @return Classe
*/
public function setSchoolyear(Schoolyear $schoolyear=null)
{
$this->schoolyear = $schoolyear;
return $this;
}
public function getLabel(): ?string
{
return $this->label;
}
public function setLabel(?string $label): void
{
$this->label = $label;
}
/**
* Add participant
*
*
* @return Classe
*/
public function addParticipant(Participant $participant)
{
$participant->setClasse($this);
$this->participants[] = $participant;
return $this;
}
/**
* Remove participant
*/
public function removeParticipant(Participant $participant)
{
$this->participants->removeElement($participant);
}
/**
* Get participants
*
* @return ArrayCollection
*/
public function getParticipants()
{
return $this->participants;
}
public function getNbrParticipants(){
//$month=(new \DateTime('now'))->format('m-y');
$n=0;
/** @var Participant $participant */
foreach ($this->participants as $participant){
if($participant->getStatus()!="Abandonné") $n++;
}
return $n;
}
public function getNbrAbandonnes(){
//$month=(new \DateTime('now'))->format('m-y');
$n=0;
/** @var Participant $participant */
foreach ($this->participants as $participant){
if($participant->getStatus()=="Abandonné") $n++;
}
return $n;
}
/**
* Add attribution
*
*
* @return Classe
*/
public function addAttribution(Attribution $attribution)
{
$attribution->setClasse($this);
$this->attributions[] = $attribution;
return $this;
}
/**
* Remove attribution
*/
public function removeAttribution(Attribution $attribution)
{
$this->attributions->removeElement($attribution);
}
/**
* Get attributions
*
* @return Collection
*/
public function getAttributions()
{
return $this->attributions;
}
/**
* Add timetable
*
*
* @return Classe
*/
public function addTimetable(Timetable $timetable)
{
$timetable->setClasse($this);
$this->timetables[] = $timetable;
return $this;
}
/**
* Remove timetable
*/
public function removeTimetable(Timetable $timetable)
{
$this->timetables->removeElement($timetable);
}
/**
* Get timetables
*
* @return Collection
*/
public function getTimetables()
{
return $this->timetables;
}
public function getResponsable(): ?User
{
return $this->responsable;
}
public function setResponsable(?User $responsable): void
{
$this->responsable = $responsable;
}
public function getMonthlyPayment(): ?float
{
return $this->monthlyPayment;
}
public function setMonthlyPayment(?float $monthlyPayment): void
{
$this->monthlyPayment = $monthlyPayment;
}
public function getRegisterCosts(): ?float
{
return $this->registerCosts;
}
public function setRegisterCosts(?float $registerCosts): void
{
$this->registerCosts = $registerCosts;
}
public function getNbrMonths(): int
{
return $this->nbrMonths;
}
public function setNbrMonths(int $nbrMonths): void
{
$this->nbrMonths = $nbrMonths;
}
public function getListMonths(): array
{
return $this->listMonths;
}
public function setListMonths(array $listMmonths): Classe
{
$this->listMonths = $listMmonths;
return $this;
}
public function getStartAt(): \DateTime
{
return $this->startAt;
}
public function setStartAt(\DateTime $startAt): void
{
$this->startAt = $startAt;
}
public function getEndAt(): \DateTime
{
return $this->endAt;
}
public function setEndAt(\DateTime $endAt): void
{
$this->endAt = $endAt;
}
public function getGraduationAt(): ?\DateTime
{
return $this->graduationAt;
}
public function setGraduationAt(?\DateTime $graduationAt): void
{
$this->graduationAt = $graduationAt;
}
public function isOpened(): bool
{
return $this->opened;
}
public function setOpened(bool $opened): void
{
$this->opened = $opened;
}
public function setPublished(bool $published): void
{
if(!$published) $this->opened = false;
$this->published = $published;
}
public function getOtherCosts(): ?string
{
return $this->otherCosts;
}
public function setOtherCosts(?string $otherCosts): void
{
$this->otherCosts = $otherCosts;
}
public function getOtherCostsArray()
{
$costs=[];
if(trim($this->getOtherCosts())!=null){
$otherCosts=explode(';', trim($this->getOtherCosts()));
if(count($otherCosts)>0){
foreach ($otherCosts as $otherCost) {
if (trim($otherCost)!='') {
$costArray=explode('=>',trim($otherCost));
if(count($costArray)==2){
if(trim($costArray[0])!='' && intval(trim($costArray[1]))>0){
$costs[]=[trim($costArray[0]),intval(trim($costArray[1]))];
}
}
}
}
}
}
return $costs;
}
public function getMonths(): array
{
$months = [];
$start = $this->getStartAt();
$end = $this->getEndAt();
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $date) {
$months[] = $date->format('m/y');
}
return $months;
}
public function getDiplome(){
return $this->getActivity()->getDiploma();
}
public function getButtonOpened()
{
$confirm="data-toggle='confirmation'
data-btn-ok-label='Oui'
data-btn-ok-icon='glyphicon glyphicon-ok'
data-btn-ok-class='btn-success'
data-btn-cancel-label='Non'
data-btn-cancel-icon='glyphicon glyphicon-remove'
data-btn-cancel-class='btn-danger'
data-title=\"Ouvrir l'inscription ?\"
data-popout='true'
data-content=\"Voulez-vous vraiment ouvrir l'inscription pour cet année scolaire actuelle ? \"";
if($this->opened)
$btn="<a ".$confirm." href='javascript:void(0)' class='boledit-redirect' data-id='".$this->id."' data-route='".$this->getRoute('opened')."'><i class=\"text-green fa fa-toggle-on\"> Oui</i></a>";
else
$btn="<a ".$confirm." href='javascript:void(0)' class='boledit-redirect' data-id='".$this->id."' data-route='".$this->getRoute('opened')."'><i class=\"text-red fa fa-toggle-off\"> Non</i></a>";
return $btn;
}
public function getActionsS($actionsItems=['edit','show','remove','add_participant'])
{
$actions="<div class='btn-group'>" .
"<button type='button' class='btn btn-default btn-flat dropdown-toggle' data-toggle='dropdown' aria-expanded='false'>" .
"<span class='fa fa-ellipsis-v'></span>" .
"<span class='sr-only'>Toggle Dropdown</span>" .
"</button>" .
"<ul class='dropdown-menu dropdown-menu-right' role='menu'>";
if(in_array('edit', $actionsItems))
$actions.="<li><a title='Modifier' class='action' target='_self' href='javascript:void(0)' data-id='".$this->id."' data-route='".$this->getRoute('edit')."'>"
."<i class='fa text-warning fa-fw fa-edit'></i> Modifier</a></li>";
if(in_array('show', $actionsItems))
$actions.="<li><a title='Afficher' class='action' target='_self' href='javascript:void(0)' data-id='".$this->id."' data-route='".$this->getRoute('show')."'>"
."<i class='fa text-info fa-fw fa-eye'></i> Afficher</a></li>";
if(in_array('remove', $actionsItems))
$actions.="<li><a title='Supprimer ?'
data-toggle='confirmation'
data-btn-ok-label='Supprimer'
data-btn-ok-icon='glyphicon glyphicon-ok'
data-btn-ok-class='btn-success'
data-btn-cancel-label='Annuler'
data-btn-cancel-icon='glyphicon glyphicon-remove'
data-btn-cancel-class='btn-danger'
data-title='Supprimer ?'
data-popout='true'
data-content='Voulez-vous vraiment supprimer cet élément ?'
class='action' target='_self' href='javascript:void(0)' data-id='".$this->id."' data-route='".$this->getRoute('remove')."'>"
."<i class='fa text-red fa-fw fa-trash-o'></i> Supprimer</a></li>";
// $actions.="<li><a title='Liste des stagiaires' class='action' target='_self' href='javascript:void(0)' data-id='".$this->id."' data-route='hs_activity_center_participant_list'>"
// ."<i class='fa text-info fa-fw fa-list-alt'></i> Stagiaires</a></li>";
if(in_array('add_participant', $actionsItems))
$actions.="<li><a title='Ajouter un nouveau participant' class='action' target='_self' href='javascript:void(0)' data-id='".$this->id."' data-route='hs_training_center_participant_new'>"
."<i class='fa text-success fa-fw fa-plus'></i> Participant</a></li>";
// $actions.="<li><a title='Ajouter un nouveau stagiaire' class='action' target='_self' href='javascript:void(0)' data-id='".$this->id."' data-route='hs_tc_faabsence_index'>"
// ."<i class='fa fa-check-circle'></i> Marquer l'aabsence</a></li>";
$actions.="</ul></div>";
return $actions;
}
public function getPay(){
$pay=0;
foreach ($this->getParticipants() as $participant) {
$pay+=$participant->getPay();
}
return $pay;
}
public function getBgClass($m){
if($this->getCurrent()==$m){
return 'bg-yellow';
}
elseif($this->getCurrent()=='before'){
return 'bg-red';
}
else return 'bg-gray';
}
public function getCurrent(){
// date_default_timezone_set('Africa/Casablanca');
$now=new \DateTime('now');
$endAt= clone $this->getEndAt();
//$endAt->modify('+1 years');
if($now<$this->getStartAt()) return 'before';
elseif($now>$endAt) return 'after';
else return $now->format('m-y');
}
public function __toString(): string
{
return $this->label??$this->activity->getTitle()." ".$this->schoolyear;
}
function getAbreviation() {
$mots = explode(' ', $this);
$abreviation = '';
foreach ($mots as $mot) {
$abreviation .= strtoupper($mot[0]);
}
return $abreviation;
}
public function getParticipantsSortedByAbsence($nombre, $startAt, $endAt){
// Récupérer tous les stagiaires
$participants = $this->getParticipants();
// Créer un tableau associatif pour stocker le nombre d'absences de chaque stagiaire
$participantAbsences = [];
/** @var Participant $participant */
foreach ($participants as $participant) {
// Compter les absences pour chaque stagiaire
if($participant->getStatus()!="Abandonné")
$participantAbsences[] = [
'participant' => $participant,
'absenceCount' => count($participant->getAbsencesByPeriod($startAt, $endAt)),
];
}
usort($participantAbsences, function ($a, $b) {
return $b['absenceCount'] <=> $a['absenceCount'];
});
// Extraire les 10 stagiaires avec le plus d'absences
$top10Participants = array_slice($participantAbsences, 0, $nombre, true);
return array_column($top10Participants, 'participant');
}
public function getUnitesSortedByAbsence($nombre){
// Récupérer tous les stagiaires
$assigns = $this->getAttributions();
// Créer un tableau associatif pour stocker le nombre d'absences de chaque stagiaire
$assignsAbsences = [];
/** @var Participant $participant */
foreach ($assigns as $assign) {
// Compter les absences pour chaque stagiaire
$assignsAbsences[] = [
'assign' => $assign,
'absenceCount' => count($assign->getAbsences()),
];
}
usort($assignsAbsences, function ($a, $b) {
return $b['absenceCount'] <=> $a['absenceCount'];
});
// Extraire les 10 stagiaires avec le plus d'absences
$top10Assigns = array_slice($assignsAbsences, 0, $nombre, true);
return array_column($top10Assigns, 'assign');
}
public function getSeances()
{
$allSeances = [];
foreach ($this->getAttributions() as $assign) {
$allSeances=array_merge($allSeances, $assign->getSeances());
}
usort($allSeances, function($a, $b) {
$dateA = DateTime::createFromFormat('d-m-Y H:i', $a->getTakesplaceOn()->format('d-m-Y').' '.$a->getStartAt());
$dateB = DateTime::createFromFormat('d-m-Y H:i', $b->getTakesplaceOn()->format('d-m-Y').' '.$b->getStartAt());
return $dateA <=> $dateB;
});
return $allSeances;
}
public function getSeancesCancelled()
{
$allSeances = [];
foreach ($this->getAttributions() as $assign) {
$allSeances=array_merge($allSeances, $assign->getSeancesCancelled());
}
usort($allSeances, function($a, $b) {
$dateA = DateTime::createFromFormat('d-m-Y H:i', $a['seanceDate'].' '.$a['timetableitem']->getStartAt());
$dateB = DateTime::createFromFormat('d-m-Y H:i', $b['seanceDate'].' '.$b['timetableitem']->getStartAt());
return $dateA <=> $dateB;
});
return $allSeances;
}
public function getSeancesNotCreate()
{
$allSeances = [];
foreach ($this->getAttributions() as $assign) {
$allSeances=array_merge($allSeances, $assign->getSeancesNotCreate());
}
usort($allSeances, function($a, $b) {
$dateA = DateTime::createFromFormat('d-m-Y H:i', $a['seanceDate'].' '.$a['timetableitem']->getStartAt());
$dateB = DateTime::createFromFormat('d-m-Y H:i', $b['seanceDate'].' '.$b['timetableitem']->getStartAt());
return $dateA <=> $dateB;
});
return $allSeances;
}
public function getToPay($type){
$mCosts=0;
foreach ($this->participants as $participant) {
$mCosts+=$participant->getPay($type);
}
return $mCosts;
}
public function getTotalPay($costs){
$m=0;
/** @var Participant $participant */
foreach ($this->participants as $participant) {
$m+=$participant->getTotalPay($costs);
}
return $m;
}
public function getTotalPayByMonth($month)
{
$sum=0;
/** @var Participant $participant */
foreach ($this->participants as $participant){
if ($participant->getCostByMonth($month)!==null)
$sum+=$participant->getCostByMonth($month)->amountPaied();
}
return $sum;
}
public function getRestPay($costs){
$m=0;
foreach ($this->participants as $participant) {
$m+=$participant->getRestPay($costs);
}
return $m;
}
public function getNbrRetard($costs){
$m=0;
foreach ($this->participants as $participant) {
$m=$participant->getRestPay($costs)>0?$m+1:$m;
}
return $m;
}
public function getAdvance($costs){
$m=0;
foreach ($this->participants as $participant) {
$m+=$participant->getAdvance($costs);
}
return $m;
}
}