<?php
namespace App\Form;
use App\Entity\Appointment;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TimeType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
class AppointmentType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$availableDates = $this->getAvailableDates($options['days_of_week']);
$availableTimes = $this->getAvailableTimes();
$builder
->add('firstName')
->add('surname')
->add('phoneNumber')
->add('email')
->add('message')
->add('date', ChoiceType::class, [
'mapped' => false,
'label' => 'Date of appointment',
'choices' => $availableDates,
'attr' => [
'class' => 'form-control',
],
])
->add('time', ChoiceType::class, [
'label' => 'Time of appointment',
'choices' => $availableTimes,
'attr' => [
'class' => 'form-control',
],
])
;
// Event listener to set the date from the choice
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
$date = $data['date']; // Get the selected date from the form data
$appointment = $form->getData();
$appointment->setDate(new \DateTime($date)); // Set the selected date on the Appointment entity
$event->setData($data);
});
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Appointment::class,
'days_of_week' => [2, 4], // Tuesday (2), Thursday (4)
]);
}
/**
* Get available dates (Tuesdays and Thursdays) for the next two weeks.
*/
private function getAvailableDates(array $daysOfWeek): array
{
$availableDates = [];
$currentDate = new \DateTime();
$interval = new \DateInterval('P1D');
$endDate = (clone $currentDate)->modify('+2 weeks');
while ($currentDate <= $endDate) {
if (in_array($currentDate->format('N'), $daysOfWeek)) { // Filter by Tuesday and Thursday
$label = $currentDate->format('l d-m-Y'); // e.g., "Tuesday 12-07-2024"
$value = $currentDate->format('Y-m-d'); // e.g., "2024-07-12"
$availableDates[$label] = $value;
}
$currentDate->add($interval);
}
return $availableDates;
}
/**
* Get available time slots for the appointment.
*/
private function getAvailableTimes(): array
{
return [
'9:30 AM - 10:30 AM' => '09:30',
'10:30 AM - 11:30 AM' => '10:30',
'11:30 AM - 12:30 PM' => '11:30',
'12:30 PM - 1:30 PM' => '12:30',
'1:30 PM - 2:30 PM' => '13:30',
'2:30 PM - 3:30 PM' => '14:30',
'3:30 PM - 4:30 PM' => '15:30',
];
}
}