'Calculate, Save and Display Bookings in a Specific Table

I am trying to calculate the best possible car booking arrangements and display them.
I have Bookings and Cars, I need to assign each booking to a car depending on its availability.

The bookings are stored in a database consisting of Date In Date Out Car Group and possibly a PreBooked tag along with other information.
Where:
Date In = datetime from when the car is picked up
Date Out = datetime from when the car is dropped off
Car Group = A enum value defining each cars class (A, B, C, C1, D, D1, E, E1, D, D1, M, M1)
PreBooked = text (a pre booked number plate or set to NO PLATE )

Now I have the following HTML table that needs to be filled:

Empty HTML Table Each of the cars "Plates" also has a Car Groupso that not just any booking can be assigned to a Car, only bookings matching their Car Group
(In this case PLATE 1234&PLATE 5678 are group A and PLATE 9101 B)

On the right are the dates going from 1-31 (For the images february has only 10 days :)
Maybe it's also possible to generate separate tables for each month? Or a 365 column wide one :p

I am trying to think of a way to automatically assign bookings to cars with the following bookings:
Booking 1 (Date In: 01/02/2022 Date Out: 07/02/2022 Car Group A
Booking 2 (Date In: 04/02/2022 Date Out: 06/02/2022 Car Group A
Booking 3 (Date In: 09/02/2022 Date Out: 25/02/2022 Car Group A
Booking 4 (Date In: 01/02/2022 Date Out: 09/02/2022 Car Group B
And place them according to dates and Car Groups into the table

(Booking 1 and Booking 3 are assigned to the first car since dates don't overlap and they have booked the same Car Group,
while Booking 2 is assigned to the next car with available dates and same Car Group.
As well as Booking 4 which is assigned to an available group B car)

So the Table would now should look something like this:

Booking Table w. Data

I need a way to check for possible booking date overlaps and if there is no overlap assign the booking to a car with same Car Group if no PreBooked plate it set.
If there is a PreBooked plate set, force assign it first to the specific car before calculating and assigning other bookings for that car.

And then display each booking with information nicely in-between date colums with colspan="" and to possibly be able to save the current table and not have it re-calculate on each page refresh...



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source