Forráskód Böngészése

cross-shopping, bbticket_invoiceprinting fixes

Szollosi.Laszlo 1 éve
szülő
commit
cf192479d2

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 447 - 407
custom/bbus/class/api_bbus.class.php


+ 97 - 1
custom/bbus/class/api_bbus_helper.class.php

@@ -3,9 +3,17 @@
 use Luracast\Restler\RestException;
 
 include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
+require_once DOL_DOCUMENT_ROOT . '/custom/settlements/class/groupusers.class.php';
+require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/userloginnaplo.class.php';
+require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbticket.class.php';
+require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbticketinvoiceprinting.class.php';
+require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_curl.class.php';
+
 
 class ApiBBusHelper
 {
+	use CurlApi;
+
 	public $db;
 	const EMAIL_TEMPLATE = 'multiticketprinting';
 	const GLOBAL_CONF_SEND_TO_EMAIL = 'BBUS_INVOICE_PRINTING_ALERT_EMAIL';
@@ -139,9 +147,10 @@ class ApiBBusHelper
 	{
 		global $db;
 		$sql = "SELECT * FROM llx_facture WHERE ref = '{$ref}'";
+		ApiBbusLog::appLog("{$sql}");
 		$resultBBT = $db->query($sql);
 		if (pg_num_rows($resultBBT) < 1) {
-			throw new RestException(404, 'Invoice not found');
+			return [];
 		}
 		while ($row = pg_fetch_assoc($resultBBT)) {
 			return $row['rowid'];
@@ -160,8 +169,10 @@ class ApiBBusHelper
 		$newCopy->product_id = $ticket->ticket_id; // product -> rowid = bbticket->ticket_id
 		$newCopy->invoice_number = $ref; // product -> rowid = bbticket->ticket_id
 		if ($newCopy->create($user) > 0) {
+			ApiBbusLog::appLog("Invoiceprinting saved");
 			// successful saving
 		} else {
+			ApiBbusLog::appLog("Invoiceprinting Insert failed");
 			dol_syslog("Nem sikerult a bbticketinvoiceprinting insertje. facture_id: {$facture_id} datetime: {$datetime}");
 			throw new RestException(404, 'Insert failed');
 		}
@@ -177,6 +188,22 @@ class ApiBBusHelper
 		return $bbTicketHandler->addTicketForPrinting($object);
 	}
 
+	public function getTicketIdsForCrossShopping($ref)
+	{
+		ApiBbusLog::appLog("getTicketIdsForCrossShopping");
+		$object = new stdClass();
+		$object->invoice_number = $ref;
+		$object->fk_product = $this->curlGetproductIdFromFActuredet($ref);
+		$bbTicketHandler = new BbTicketHandler();
+		// uj rekordot veszek fel a bbticket tablaba és visszaterek a rogzitett rekordok roid-javal
+		return $bbTicketHandler->addTicketForPrintingCrossShopping($object);
+	}
+	
+	function curlGetproductIdFromFActuredet($ref){
+		$params = '{"ref":"' . $ref . '"}';
+		return $this->curlRunner('bbus/curlgetproductidfromfacturedet', $params, 'POST', true);
+	}
+
 	private function getproductIdFromFActuredet($facture_id)
 	{
 		global $db;
@@ -412,4 +439,73 @@ class ApiBBusHelper
 
 		return $result;
 	}
+
+	public function getGroupUserIdByUserId($user_id)
+	{
+		global $db;
+		$groupUsersObj = new GroupUsers($db);
+		$result = $groupUsersObj->fetchAll('DESC', 'rowid', 1, 0, ["customsql" => "fk_user = {$user_id}"]);
+		if (!empty($result)) {
+			foreach ($result as $record) {
+				return $record->fk_settlements_group;
+			}
+		}
+		return -1;
+	}
+
+	public function isLastStatusLogout($user)
+	{
+		global $db;
+		$userLoginNaplo = new UserLoginNaplo($db);
+		$result = $userLoginNaplo->fetchAll('DESC', 'date_creation', 1, 0, array('user_id' => $user->id));
+		foreach ($result as $lastrecord) {
+			return $lastrecord->login_logout_status == 1 ? $lastrecord->date_creation : '';
+		}
+	}
+
+	public function factureUpdate($sql, $facture_id)
+	{
+		$updated = $this->db->query($sql);
+		if (!$updated) {
+			dol_syslog("Nem sikerult a facture updateje. rowid: " . $facture_id, LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
+			throw new RestException(404, 'Update failed');
+		}
+	}
+
+	public function checkResult($result, $tableName)
+	{
+		if (!is_array($result) || empty($result)) {
+			dol_syslog("A megadott szuresi adatokhoz nem tartozik rekord ({$tableName}).", LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
+			throw new RestException(404, "A megadott szuresi adatokhoz nem tartozik rekord ({$tableName}).");
+		}
+	}
+
+	public function getTicketsByFacture($facture_id)
+	{
+		$bbticket = new BbTicket($this->db);
+		$bbTicketsByFacture = $bbticket->fetchAll('', '', 0, 0, ['customsql' => 'fk_facture = ' . intval($facture_id)]);
+		if ($bbTicketsByFacture < 1) {
+			throw new RestException(404, 'BBTicket not found');
+		}
+		return $bbTicketsByFacture;
+	}
+
+	public function checkPrintedCopies($facture_id)
+	{
+		$bbticketinvoiceprinting = new BbTicketInvoicePrinting($this->db);
+		$copies = $bbticketinvoiceprinting->fetchAll('ASC', 'rowid', 0, 0, ['customsql' => 'fk_facture = ' . intval($facture_id)]);
+		return (is_array($copies)) ? count($copies) : 0;
+	}
+
+	public function getbookingHistoryId($ref){
+		$sql = "SELECT rowid FROM llx_booking_bookinghistory WHERE invoice_number = '{$ref}' ORDER BY rowid DESC LIMIT 1";
+		$result = $this->db->query($sql);
+		if($this->db->num_rows($result) < 1){
+			return '';
+		}else{
+			while($row = $this->db->fetch_object($result)){
+				return $row->rowid;
+			}
+		}
+	}
 }

+ 5 - 4
custom/bbus/class/api_curl.class.php

@@ -13,7 +13,8 @@ trait CurlApi
 		$curl = curl_init();
 
 		curl_setopt_array($curl, array(
-			CURLOPT_URL => 'http://dolibarr-bbusdev-imap-cron-soap/api/index.php/' . $route,
+			//CURLOPT_URL => 'http://dolibarr-bbusdev-imap-cron-soap/api/index.php/' . $route,
+			CURLOPT_URL => 'http://bbusdevszollosil/api/index.php/' . $route,
 			CURLOPT_RETURNTRANSFER => true,
 			CURLOPT_VERBOSE => true,
 			CURLOPT_SSL_VERIFYPEER => false,
@@ -27,7 +28,7 @@ trait CurlApi
 			CURLOPT_USERAGENT => "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
 			CURLOPT_POSTFIELDS => $postFields,
 			CURLOPT_HTTPHEADER => array(
-				'DOLAPIKEY: XLUBwCnkVOoX',
+				'DOLAPIKEY: VXG0isGJwn0U2WJ17dkN27vV3blH64xr',
 				'Content-Type: application/json'
 			),
 		));
@@ -38,7 +39,7 @@ trait CurlApi
 	{
 		$curl = $this->curlInit($route, $postFields, $request);
 		$response = curl_exec($curl);
-		print_r($response);
+		//ApiBbusLog::appLog("{$response}");
 		curl_close($curl);
 		return $decode ? json_decode($response) : $response;
 	}
@@ -84,7 +85,7 @@ trait CurlApi
 
 
 
-	private function getServerHost($type_id)
+	public function getServerHost($type_id)
 	{
 		$basicServices = new BasicServices($this->db);
 		$resultBS = $basicServices->fetch($type_id);

+ 25 - 1
custom/bbus/class/bbtickethandler.class.php

@@ -1,6 +1,7 @@
 <?php
 
 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
+require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_curl.class.php';
 
 
 // require_once DOL_DOCUMENT_ROOT.'//class/.class.php';
@@ -10,6 +11,9 @@ require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
 
 class BbTicketHandler
 {
+
+    use CurlApi;
+
     private $user;
     private $db;
     private $datec;
@@ -82,6 +86,23 @@ class BbTicketHandler
         }
     }
 
+    public function addTicketForPrintingCrossShopping($object){
+        $helper = new ApiBBusHelper();
+        $ticketIds = [];
+        $this->getProductAssociationFils($object);
+        $params = '{"ref":"' . $object->invoice_number . '"}';
+		$this->datec = $this->curlRunner('bbus/curlgetdatecfromfacture', $params, 'POST', true);
+        $booking_history = $helper->getbookingHistoryId($object->invoice_number);
+        foreach ($object->fk_product as $record) {
+            $ticket = $this->createTicketObject($this->pere[0], $record, null, $object->invoice_number, 10000, $booking_history);
+            $insertedTicket = $ticket->create($this->user);
+            if ($insertedTicket == -1) {
+                dol_syslog("Nem sikerult a ticketek mentese. facture_id: " . $object->invoice_number);
+            }
+            $ticketIds[$insertedTicket] = $record;
+        }
+        return $ticketIds;
+    }
 
     public function addTicketForPrinting($object)
     {
@@ -156,7 +177,7 @@ class BbTicketHandler
         }
     }
  */
-    private function createTicketObject($pere, $ticket_id, $facture_id)
+    private function createTicketObject($pere, $ticket_id, $facture_id = null, $ref = null, $group_id = null, $booking_history = null)
     {
         $this->getDurationFromProductsByFilsID($ticket_id);
         $ticket = new BbTicket($this->db);
@@ -165,7 +186,10 @@ class BbTicketHandler
         $ticket->usable_occasions = $this->occasions;
         $ticket->usage = '0';
         $ticket->available_at = $this->getAvailableAtDate($this->datec, $this->validperiod);
+        $ticket->invoice_number = $ref;
+        $ticket->fk_settlements_group_id = $group_id;
         $ticket->ticket_id = $ticket_id;
+        $ticket->booking_history_id = $booking_history;
         return $ticket;
     }
 

+ 119 - 674
custom/booking/booking_agenda.php

@@ -105,7 +105,7 @@ $action = GETPOST('action', 'aZ09');
 
 $mode = GETPOST('mode', 'aZ09');
 if (empty($mode) && preg_match('/show_/', $action)) {
-    $mode = $action;	// For backward compatibility
+    $mode = $action;    // For backward compatibility
 }
 $resourceid = GETPOST("search_resourceid", "int");
 $year = GETPOST("year", "int") ? GETPOST("year", "int") : date("Y");
@@ -145,18 +145,9 @@ if (empty($mode) && !GETPOSTISSET('mode')) {
     //$mode = $defaultview;
     $mode = 'show_day';
 }
-if ($mode == 'default') {	// When action is default, we want a calendar view and not the list
+if ($mode == 'default') {    // When action is default, we want a calendar view and not the list
     $mode = (($defaultview != 'show_list') ? $defaultview : 'show_month');
 }
-if (GETPOST('viewcal', 'int') && GETPOST('mode', 'alpha') != 'show_day' && GETPOST('mode', 'alpha') != 'show_week') {
-    $mode = 'show_month';
-    $day = '';
-} // View by month
-if (GETPOST('viewweek', 'int') || GETPOST('mode', 'alpha') == 'show_week') {
-    $mode = 'show_week';
-    $week = ($week ? $week : date("W"));
-    $day = ($day ? $day : date("d"));
-} // View by week
 if (GETPOST('viewday', 'int') || GETPOST('mode', 'alpha') == 'show_day') {
     $mode = 'show_day';
     $day = ($day ? $day : date("d"));
@@ -434,26 +425,6 @@ if ($mode == 'show_day' || $mode == 'show_week' || $mode == 'show_month') {
 }
 
 // Show navigation bar
-if (empty($mode) || $mode == 'show_month') {
-    $nav = "<a href=\"?year=" . $prev_year . "&month=" . $prev_month . $param . "\"><i class=\"fa fa-chevron-left\"></i></a> &nbsp;\n";
-    $nav .= " <span id=\"month_name\">" . dol_print_date(dol_mktime(0, 0, 0, $month, 1, $year), "%b %Y");
-    $nav .= " </span>\n";
-    $nav .= " &nbsp; <a href=\"?year=" . $next_year . "&month=" . $next_month . $param . "\"><i class=\"fa fa-chevron-right\"></i></a>\n";
-    if (empty($conf->dol_optimize_smallscreen)) {
-        $nav .= " &nbsp; <a href=\"?year=" . $nowyear . "&month=" . $nowmonth . $param . "\">" . $langs->trans("Today") . "</a> ";
-    }
-    $picto = 'calendar';
-}
-if ($mode == 'show_week') {
-    $nav = "<a href=\"?year=" . $prev_year . "&month=" . $prev_month . "&day=" . $prev_day . $param . "\"><i class=\"fa fa-chevron-left\" title=\"" . dol_escape_htmltag($langs->trans("Previous")) . "\"></i></a> &nbsp;\n";
-    $nav .= " <span id=\"month_name\">" . dol_print_date(dol_mktime(0, 0, 0, $first_month, $first_day, $first_year), "%Y") . ", " . $langs->trans("Week") . " " . $week;
-    $nav .= " </span>\n";
-    $nav .= " &nbsp; <a href=\"?year=" . $next_year . "&month=" . $next_month . "&day=" . $next_day . $param . "\"><i class=\"fa fa-chevron-right\" title=\"" . dol_escape_htmltag($langs->trans("Next")) . "\"></i></a>\n";
-    if (empty($conf->dol_optimize_smallscreen)) {
-        $nav .= " &nbsp; <a href=\"?year=" . $nowyear . "&month=" . $nowmonth . "&day=" . $nowday . $param . "\">" . $langs->trans("Today") . "</a> ";
-    }
-    $picto = 'calendarweek';
-}
 if ($mode == 'show_day') {
     $nav = "<a href=\"?year=" . $prev_year . "&month=" . $prev_month . "&day=" . $prev_day . $param . "\"><i class=\"fa fa-chevron-left\"></i></a> &nbsp;\n";
     $nav .= " <span id=\"month_name\">" . dol_print_date(dol_mktime(0, 0, 0, $month, $day, $year), "daytextshort");
@@ -543,7 +514,7 @@ if (empty($reshook)) {
     $viewmode = $hookmanager->resPrint;
 }
 
-$viewmode .= '<span class="marginrightonly"></span>';	// To add a space before the navigation tools
+$viewmode .= '<span class="marginrightonly"></span>';    // To add a space before the navigation tools
 
 
 $newcardbutton = '';
@@ -554,7 +525,7 @@ if ($user->rights->agenda->myactions->create || $user->rights->agenda->allaction
     $newparam .= '&month=' . ((int) $month) . '&year=' . ((int) $tmpforcreatebutton['year']) . '&mode=' . urlencode($mode);
 
     //$param='month='.$monthshown.'&year='.$year;
-    $hourminsec = dol_print_date(dol_mktime(10, 0, 0, 1, 1, 1970, 'gmt'), '%H', 'gmt') . '0000';	// Set $hourminsec to '100000' to auto set hour to 10:00 at creation
+    $hourminsec = dol_print_date(dol_mktime(10, 0, 0, 1, 1, 1970, 'gmt'), '%H', 'gmt') . '0000';    // Set $hourminsec to '100000' to auto set hour to 10:00 at creation
 
     $newcardbutton .= dolGetButtonTitle($langs->trans("AddAction"), '', 'fa fa-plus-circle', DOL_URL_ROOT . '/custom/booking/booking_card.php?action=create&datep=' . sprintf("%04d%02d%02d", $tmpforcreatebutton['year'], $tmpforcreatebutton['mon'], $tmpforcreatebutton['mday']) . $hourminsec . '&backtopage=' . urlencode($_SERVER["PHP_SELF"] . ($newparam ? '?' . $newparam : '')));
 }
@@ -565,7 +536,7 @@ $link = '';
 
 $showextcals = $listofextcals;
 
-if (!empty($conf->use_javascript_ajax)) {	// If javascript on
+if (!empty($conf->use_javascript_ajax)) {    // If javascript on
     $s .= "\n" . '<!-- Div to calendars selectors -->' . "\n";
     $s .= '<script type="text/javascript">' . "\n";
     $s .= 'jQuery(document).ready(function () {' . "\n";
@@ -827,7 +798,7 @@ if ($resql) {
         // event->datep and event->datef must be GMT date.
         if ($event->fulldayevent) {
             $tzforfullday = getDolGlobalString('MAIN_STORE_FULL_EVENT_IN_GMT');
-            $event->datep = $db->jdate($obj->datep, $tzforfullday ? 'tzuser' : 'tzserver');	// If saved in $tzforfullday = gmt, we must invert date to be in user tz
+            $event->datep = $db->jdate($obj->datep, $tzforfullday ? 'tzuser' : 'tzserver');    // If saved in $tzforfullday = gmt, we must invert date to be in user tz
             $event->datef = $db->jdate($obj->datep2, $tzforfullday ? 'tzuser' : 'tzserver');
         } else {
             // Example: $obj->datep = '1970-01-01 01:00:00', jdate will return 0 if TZ of PHP server is Europe/Berlin (+1)
@@ -901,8 +872,8 @@ if ($resql) {
             // Loop on each day covered by action to prepare an index to show on calendar
             $loop = true;
             $j = 0;
-            $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee, 'gmt');	// $mois, $jour, $annee has been set for user tz
-            $daykeyend = dol_mktime(0, 0, 0, $moisend, $jourend, $anneeend, 'gmt');	// $moisend, $jourend, $anneeend has been set for user tz
+            $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee, 'gmt');    // $mois, $jour, $annee has been set for user tz
+            $daykeyend = dol_mktime(0, 0, 0, $moisend, $jourend, $anneeend, 'gmt');    // $moisend, $jourend, $anneeend has been set for user tz
             /*
                       print 'GMT '.$event->date_start_in_calendar.' '.dol_print_date($event->date_start_in_calendar, 'dayhour', 'gmt').'<br>';
                       print 'TZSERVER '.$event->date_start_in_calendar.' '.dol_print_date($event->date_start_in_calendar, 'dayhour', 'tzserver').'<br>';
@@ -944,7 +915,7 @@ $sql .= " AND (x.statut = '2' OR x.statut = '3')"; // Show only public leaves (2
 
 if ($mode == 'show_day') {
     // Request only leaves for the current selected day
-    $sql .= " AND '" . $db->escape($year) . "-" . $db->escape($month) . "-" . $db->escape($day) . "' BETWEEN x.date_debut AND x.date_fin";	// date_debut and date_fin are date without time
+    $sql .= " AND '" . $db->escape($year) . "-" . $db->escape($month) . "-" . $db->escape($day) . "' BETWEEN x.date_debut AND x.date_fin";    // date_debut and date_fin are date without time
 } elseif ($mode == 'show_week') {
     // TODO: Add filter to reduce database request
 } elseif ($mode == 'show_month') {
@@ -1010,289 +981,6 @@ if ($resql) {
 
 // EXTERNAL CALENDAR
 // Complete $eventarray with external import Ical
-if (count($listofextcals)) {
-    require_once DOL_DOCUMENT_ROOT . '/comm/action/class/ical.class.php';
-    foreach ($listofextcals as $extcal) {
-        $url = $extcal['src']; // Example: https://www.google.com/calendar/ical/eldy10%40gmail.com/private-cde92aa7d7e0ef6110010a821a2aaeb/basic.ics
-        $namecal = $extcal['name'];
-        $offsettz = $extcal['offsettz'];
-        $colorcal = $extcal['color'];
-        $buggedfile = $extcal['buggedfile'];
-
-        $ical = new ICal();
-        $ical->parse($url);
-
-        // After this $ical->cal['VEVENT'] contains array of events, $ical->cal['DAYLIGHT'] contains daylight info, $ical->cal['STANDARD'] contains non daylight info, ...
-        //var_dump($ical->cal); exit;
-        $icalevents = array();
-        if (is_array($ical->get_event_list())) {
-            $icalevents = array_merge($icalevents, $ical->get_event_list()); // Add $ical->cal['VEVENT']
-        }
-        if (is_array($ical->get_freebusy_list())) {
-            $icalevents = array_merge($icalevents, $ical->get_freebusy_list()); // Add $ical->cal['VFREEBUSY']
-        }
-
-        if (count($icalevents) > 0) {
-            // Duplicate all repeatable events into new entries
-            $moreicalevents = array();
-            foreach ($icalevents as $icalevent) {
-                if (isset($icalevent['RRULE']) && is_array($icalevent['RRULE'])) { //repeatable event
-                    //if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar=$firstdaytoshow;
-                    //if ($event->date_end_in_calendar > $lastdaytoshow) $event->date_end_in_calendar=($lastdaytoshow-1);
-                    if ($icalevent['DTSTART;VALUE=DATE']) { //fullday event
-                        $datecurstart = dol_stringtotime($icalevent['DTSTART;VALUE=DATE'], 1);
-                        $datecurend = dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1) - 1; // We remove one second to get last second of day
-                    } elseif (is_array($icalevent['DTSTART']) && !empty($icalevent['DTSTART']['unixtime'])) {
-                        $datecurstart = $icalevent['DTSTART']['unixtime'];
-                        $datecurend = $icalevent['DTEND']['unixtime'];
-                        if (!empty($ical->cal['DAYLIGHT']['DTSTART']) && $datecurstart) {
-                            //var_dump($ical->cal);
-                            $tmpcurstart = $datecurstart;
-                            $tmpcurend = $datecurend;
-                            $tmpdaylightstart = dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['DAYLIGHT']['DTSTART'];
-                            $tmpdaylightend = dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['STANDARD']['DTSTART'];
-                            //var_dump($tmpcurstart);var_dump($tmpcurend); var_dump($ical->cal['DAYLIGHT']['DTSTART']);var_dump($ical->cal['STANDARD']['DTSTART']);
-                            // Edit datecurstart and datecurend
-                            if ($tmpcurstart >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) {
-                                $datecurstart -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36;
-                            } else {
-                                $datecurstart -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36;
-                            }
-                            if ($tmpcurend >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) {
-                                $datecurend -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36;
-                            } else {
-                                $datecurend -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36;
-                            }
-                        }
-                        // datecurstart and datecurend are now GMT date
-                        //var_dump($datecurstart); var_dump($datecurend); exit;
-                    } else {
-                        // Not a recongized record
-                        dol_syslog("Found a not recognized repeatable record with unknown date start", LOG_ERR);
-                        continue;
-                    }
-                    //print 'xx'.$datecurstart;exit;
-
-                    $interval = (empty($icalevent['RRULE']['INTERVAL']) ? 1 : $icalevent['RRULE']['INTERVAL']);
-                    $until = empty($icalevent['RRULE']['UNTIL']) ? 0 : dol_stringtotime($icalevent['RRULE']['UNTIL'], 1);
-                    $maxrepeat = empty($icalevent['RRULE']['COUNT']) ? 0 : $icalevent['RRULE']['COUNT'];
-                    if ($until && ($until + ($datecurend - $datecurstart)) < $firstdaytoshow) {
-                        continue; // We discard repeatable event that end before start date to show
-                    }
-                    if ($datecurstart >= $lastdaytoshow) {
-                        continue; // We discard repeatable event that start after end date to show
-                    }
-
-                    $numofevent = 0;
-                    while (($datecurstart < $lastdaytoshow) && (empty($maxrepeat) || ($numofevent < $maxrepeat))) {
-                        if ($datecurend >= $firstdaytoshow) {    // We add event
-                            $newevent = $icalevent;
-                            unset($newevent['RRULE']);
-                            if ($icalevent['DTSTART;VALUE=DATE']) {
-                                $newevent['DTSTART;VALUE=DATE'] = dol_print_date($datecurstart, '%Y%m%d');
-                                $newevent['DTEND;VALUE=DATE'] = dol_print_date($datecurend + 1, '%Y%m%d');
-                            } else {
-                                $newevent['DTSTART'] = $datecurstart;
-                                $newevent['DTEND'] = $datecurend;
-                            }
-                            $moreicalevents[] = $newevent;
-                        }
-                        // Jump on next occurence
-                        $numofevent++;
-                        $savdatecurstart = $datecurstart;
-                        if ($icalevent['RRULE']['FREQ'] == 'DAILY') {
-                            $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'd');
-                            $datecurend = dol_time_plus_duree($datecurend, $interval, 'd');
-                        }
-                        if ($icalevent['RRULE']['FREQ'] == 'WEEKLY') {
-                            $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'w');
-                            $datecurend = dol_time_plus_duree($datecurend, $interval, 'w');
-                        } elseif ($icalevent['RRULE']['FREQ'] == 'MONTHLY') {
-                            $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'm');
-                            $datecurend = dol_time_plus_duree($datecurend, $interval, 'm');
-                        } elseif ($icalevent['RRULE']['FREQ'] == 'YEARLY') {
-                            $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'y');
-                            $datecurend = dol_time_plus_duree($datecurend, $interval, 'y');
-                        }
-                        // Test to avoid infinite loop ($datecurstart must increase)
-                        if ($savdatecurstart >= $datecurstart) {
-                            dol_syslog("Found a rule freq " . $icalevent['RRULE']['FREQ'] . " not managed by dolibarr code. Assume 1 week frequency.", LOG_ERR);
-                            $datecurstart += 3600 * 24 * 7;
-                            $datecurend += 3600 * 24 * 7;
-                        }
-                    }
-                }
-            }
-            $icalevents = array_merge($icalevents, $moreicalevents);
-
-            // Loop on each entry into cal file to know if entry is qualified and add an ActionComm into $eventarray
-            foreach ($icalevents as $icalevent) {
-                //var_dump($icalevent);
-
-                //print $icalevent['SUMMARY'].'->';
-                //var_dump($icalevent);exit;
-                if (!empty($icalevent['RRULE'])) {
-                    continue; // We found a repeatable event. It was already split into unitary events, so we discard general rule.
-                }
-
-                // Create a new object action
-                $event = new ActionComm($db);
-                $addevent = false;
-                if (isset($icalevent['DTSTART;VALUE=DATE'])) { // fullday event
-                    // For full day events, date are also GMT but they wont but converted using tz during output
-                    $datestart = dol_stringtotime($icalevent['DTSTART;VALUE=DATE'], 1);
-                    if (empty($icalevent['DTEND;VALUE=DATE'])) {
-                        $dateend = $datestart + 86400 - 1;
-                    } else {
-                        $dateend = dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1) - 1; // We remove one second to get last second of day
-                    }
-                    //print 'x'.$datestart.'-'.$dateend;exit;
-                    //print dol_print_date($dateend,'dayhour','gmt');
-                    $event->fulldayevent = 1;
-                    $addevent = true;
-                } elseif (!is_array($icalevent['DTSTART'])) { // not fullday event (DTSTART is not array. It is a value like '19700101T000000Z' for 00:00 in greenwitch)
-                    $datestart = $icalevent['DTSTART'];
-                    $dateend = empty($icalevent['DTEND']) ? $datestart : $icalevent['DTEND'];
-
-                    $datestart += +($offsettz * 3600);
-                    $dateend += +($offsettz * 3600);
-
-                    $addevent = true;
-                    //var_dump($offsettz);
-                    //var_dump(dol_print_date($datestart, 'dayhour', 'gmt'));
-                } elseif (isset($icalevent['DTSTART']['unixtime'])) {	// File contains a local timezone + a TZ (for example when using bluemind)
-                    $datestart = $icalevent['DTSTART']['unixtime'];
-                    $dateend = $icalevent['DTEND']['unixtime'];
-
-                    $datestart += +($offsettz * 3600);
-                    $dateend += +($offsettz * 3600);
-
-                    // $buggedfile is set to uselocalandtznodaylight if conf->global->AGENDA_EXT_BUGGEDFILEx = 'uselocalandtznodaylight'
-                    if ($buggedfile === 'uselocalandtznodaylight') {	// unixtime is a local date that does not take daylight into account, TZID is +1 for example for 'Europe/Paris' in summer instead of 2
-                        // TODO
-                    }
-                    // $buggedfile is set to uselocalandtzdaylight if conf->global->AGENDA_EXT_BUGGEDFILEx = 'uselocalandtzdaylight' (for example with bluemind)
-                    if ($buggedfile === 'uselocalandtzdaylight') {	// unixtime is a local date that does take daylight into account, TZID is +2 for example for 'Europe/Paris' in summer
-                        $localtzs = new DateTimeZone(preg_replace('/"/', '', $icalevent['DTSTART']['TZID']));
-                        $localtze = new DateTimeZone(preg_replace('/"/', '', $icalevent['DTEND']['TZID']));
-                        $localdts = new DateTime(dol_print_date($datestart, 'dayrfc', 'gmt'), $localtzs);
-                        $localdte = new DateTime(dol_print_date($dateend, 'dayrfc', 'gmt'), $localtze);
-                        $tmps = -1 * $localtzs->getOffset($localdts);
-                        $tmpe = -1 * $localtze->getOffset($localdte);
-                        $datestart += $tmps;
-                        $dateend += $tmpe;
-                        //var_dump($datestart);
-                    }
-                    $addevent = true;
-                }
-
-                if ($addevent) {
-                    $event->id = $icalevent['UID'];
-                    $event->ref = $event->id;
-                    $userId = $userstatic->findUserIdByEmail($namecal);
-                    if (!empty($userId) && $userId > 0) {
-                        $event->userassigned[$userId] = $userId;
-                        $event->percentage = -1;
-                    }
-
-                    $event->type_code = "ICALEVENT";
-                    $event->type_label = $namecal;
-                    $event->type_color = $colorcal;
-                    $event->type = 'icalevent';
-                    $event->type_picto = 'rss';
-
-                    $event->icalname = $namecal;
-                    $event->icalcolor = $colorcal;
-                    $usertime = 0; // We dont modify date because we want to have date into memory datep and datef stored as GMT date. Compensation will be done during output.
-                    $event->datep = $datestart + $usertime;
-                    $event->datef = $dateend + $usertime;
-
-                    if ($icalevent['SUMMARY']) {
-                        $event->label = dol_string_nohtmltag($icalevent['SUMMARY']);
-                    } elseif ($icalevent['DESCRIPTION']) {
-                        $event->label = dol_nl2br(dol_string_nohtmltag($icalevent['DESCRIPTION']), 1);
-                    } else {
-                        $event->label = $langs->trans("ExtSiteNoLabel");
-                    }
-
-                    // Priority (see https://www.kanzaki.com/docs/ical/priority.html)
-                    // LOW      = 0 to 4
-                    // MEDIUM   = 5
-                    // HIGH     = 6 to 9
-                    if (!empty($icalevent['PRIORITY'])) {
-                        $event->priority = $icalevent['PRIORITY'];
-                    }
-
-                    // Transparency (see https://www.kanzaki.com/docs/ical/transp.html)
-                    if (!empty($icalevent['TRANSP'])) {
-                        if ($icalevent['TRANSP'] == "TRANSPARENT") {
-                            $event->transparency = 0; // 0 = available / free
-                        }
-                        if ($icalevent['TRANSP'] == "OPAQUE") {
-                            $event->transparency = 1; // 1 = busy
-                        }
-
-                        // TODO: MS outlook states
-                        // X-MICROSOFT-CDO-BUSYSTATUS:FREE      + TRANSP:TRANSPARENT => Available / Free
-                        // X-MICROSOFT-CDO-BUSYSTATUS:FREE      + TRANSP:OPAQUE      => Work another place
-                        // X-MICROSOFT-CDO-BUSYSTATUS:TENTATIVE + TRANSP:OPAQUE      => With reservations
-                        // X-MICROSOFT-CDO-BUSYSTATUS:BUSY      + TRANSP:OPAQUE      => Busy
-                        // X-MICROSOFT-CDO-BUSYSTATUS:OOF       + TRANSP:OPAQUE      => Away from the office / off-site
-                    }
-
-                    if (!empty($icalevent['LOCATION'])) {
-                        $event->location = $icalevent['LOCATION'];
-                    }
-
-                    $event->date_start_in_calendar = $event->datep;
-
-                    if ($event->datef != '' && $event->datef >= $event->datep) {
-                        $event->date_end_in_calendar = $event->datef;
-                    } else {
-                        $event->date_end_in_calendar = $event->datep;
-                    }
-
-                    // Add event into $eventarray if date range are ok.
-                    if ($event->date_end_in_calendar < $firstdaytoshow || $event->date_start_in_calendar >= $lastdaytoshow) {
-                        //print 'x'.$datestart.'-'.$dateend;exit;
-                        //print 'x'.$datestart.'-'.$dateend;exit;
-                        //print 'x'.$datestart.'-'.$dateend;exit;
-                        // This record is out of visible range
-                    } else {
-                        if ($event->date_start_in_calendar < $firstdaytoshow) {
-                            $event->date_start_in_calendar = $firstdaytoshow;
-                        }
-                        if ($event->date_end_in_calendar >= $lastdaytoshow) {
-                            $event->date_end_in_calendar = ($lastdaytoshow - 1);
-                        }
-
-                        // Add an entry in actionarray for each day
-                        $daycursor = $event->date_start_in_calendar;
-                        $annee = dol_print_date($daycursor, '%Y', 'tzuserrel');
-                        $mois = dol_print_date($daycursor, '%m', 'tzuserrel');
-                        $jour = dol_print_date($daycursor, '%d', 'tzuserrel');
-
-                        // Loop on each day covered by action to prepare an index to show on calendar
-                        $loop = true;
-                        $j = 0;
-                        // daykey must be date that represent day box in calendar so must be a user time
-                        $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee, 'gmt');
-                        $daykeygmt = dol_mktime(0, 0, 0, $mois, $jour, $annee, 'gmt');
-                        do {
-                            //if ($event->fulldayevent) print dol_print_date($daykeygmt,'dayhour','gmt').'-'.dol_print_date($daykey,'dayhour','gmt').'-'.dol_print_date($event->date_end_in_calendar,'dayhour','gmt').' ';
-                            $eventarray[$daykey][] = $event;
-                            $daykey += 60 * 60 * 24;
-                            $daykeygmt += 60 * 60 * 24; // Add one day
-                            if (($event->fulldayevent ? $daykeygmt : $daykey) > $event->date_end_in_calendar) {
-                                $loop = false;
-                            }
-                        } while ($loop);
-                    }
-                }
-            }
-        }
-    }
-}
 
 
 
@@ -1336,360 +1024,118 @@ print_barre_liste($langs->trans("Agenda"), $page, $_SERVER["PHP_SELF"], $param,
 // Show div with list of calendars
 print $s;
 
-
-if (empty($mode) || $mode == 'show_month') {      // View by month
-    $newparam = $param; // newparam is for birthday links
-    $newparam = preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done
-    $newparam = preg_replace('/mode=show_month&?/i', '', $newparam);
-    $newparam = preg_replace('/mode=show_week&?/i', '', $newparam);
-    $newparam = preg_replace('/day=[0-9]+&?/i', '', $newparam);
-    $newparam = preg_replace('/month=[0-9]+&?/i', '', $newparam);
-    $newparam = preg_replace('/year=[0-9]+&?/i', '', $newparam);
-    $newparam = preg_replace('/viewcal=[0-9]+&?/i', '', $newparam);
-    $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter
-    $newparam .= '&viewcal=1';
-
-    /* print '<div class="liste_titre liste_titre_bydiv centpercent">';
-       print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid);
-       print '</div>'; */
-
-    print '<div class="div-table-responsive-no-min sectioncalendarbymonth maxscreenheightless300">';
-    print '<table class="centpercent noborder nocellnopadd cal_pannel cal_month">';
-    print ' <tr class="liste_titre">';
-    // Column title of weeks numbers
-    echo '  <td class="center">#</td>';
-    $i = 0;
-    while ($i < 7) {
-        print '  <td class="center bold uppercase tdfordaytitle' . ($i == 0 ? ' borderleft' : '') . '">';
-        $numdayinweek = (($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7);
-        if (!empty($conf->dol_optimize_smallscreen)) {
-            $labelshort = array(0 => 'SundayMin', 1 => 'MondayMin', 2 => 'TuesdayMin', 3 => 'WednesdayMin', 4 => 'ThursdayMin', 5 => 'FridayMin', 6 => 'SaturdayMin');
-            print $langs->trans($labelshort[$numdayinweek]);
-        } else {
-            print $langs->trans("Day" . $numdayinweek);
-        }
-        print '  </td>' . "\n";
-        $i++;
-    }
-    echo ' </tr>' . "\n";
-
-    $todayarray = dol_getdate($now, 'fast');
-    $todaytms = dol_mktime(0, 0, 0, $todayarray['mon'], $todayarray['mday'], $todayarray['year']);
-
-    // In loops, tmpday contains day nb in current month (can be zero or negative for days of previous month)
-    //var_dump($eventarray);
-    for ($iter_week = 0; $iter_week < 6; $iter_week++) {
-        echo " <tr>\n";
-        // Get date of the current day, format 'yyyy-mm-dd'
-        if ($tmpday <= 0) { // If number of the current day is in previous month
-            $currdate0 = sprintf("%04d", $prev_year) . sprintf("%02d", $prev_month) . sprintf("%02d", $max_day_in_prev_month + $tmpday);
-        } elseif ($tmpday <= $max_day_in_month) { // If number of the current day is in current month
-            $currdate0 = sprintf("%04d", $year) . sprintf("%02d", $month) . sprintf("%02d", $tmpday);
-        } else // If number of the current day is in next month
-        {
-            $currdate0 = sprintf("%04d", $next_year) . sprintf("%02d", $next_month) . sprintf("%02d", $tmpday - $max_day_in_month);
-        }
-        // Get week number for the targeted date '$currdate0'
-        $numweek0 = date("W", strtotime(date($currdate0)));
-        // Show the week number, and define column width
-        echo ' <td class="center weeknumber opacitymedium" width="2%">' . $numweek0 . '</td>';
-
-        for ($iter_day = 0; $iter_day < 7; $iter_day++) {
-            if ($tmpday <= 0) {
-                /* Show days before the beginning of the current month (previous month)  */
-                $style = 'cal_other_month cal_past';
-                if ($iter_day == 6) {
-                    $style .= ' cal_other_month_right';
-                }
-                echo '  <td class="' . $style . ' nowrap tdtop" width="14%">';
-                show_day_events($db, $max_day_in_prev_month + $tmpday, $prev_month, $prev_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam);
-                echo "  </td>\n";
-            } elseif ($tmpday <= $max_day_in_month) {
-                /* Show days of the current month */
-                $curtime = dol_mktime(0, 0, 0, $month, $tmpday, $year);
-                $style = 'cal_current_month';
-                if ($iter_day == 6) {
-                    $style .= ' cal_current_month_right';
-                }
-                $today = 0;
-                if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $month && $todayarray['year'] == $year) {
-                    $today = 1;
-                }
-                if ($today) {
-                    $style = 'cal_today';
-                }
-                if ($curtime < $todaytms) {
-                    $style .= ' cal_past';
-                }
-                //var_dump($todayarray['mday']."==".$tmpday." && ".$todayarray['mon']."==".$month." && ".$todayarray['year']."==".$year.' -> '.$style);
-                echo '  <td class="' . $style . ' nowrap tdtop" width="14%">';
-                show_day_events($db, $tmpday, $month, $year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam);
-                echo "</td>\n";
-            } else {
-                /* Show days after the current month (next month) */
-                $style = 'cal_other_month';
-                if ($iter_day == 6) {
-                    $style .= ' cal_other_month_right';
-                }
-                echo '  <td class="' . $style . ' nowrap tdtop" width="14%">';
-                show_day_events($db, $tmpday - $max_day_in_month, $next_month, $next_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam);
-                echo "</td>\n";
-            }
-            $tmpday++;
-        }
-        echo " </tr>\n";
-    }
-    print "</table>\n";
-    print '</div>';
-
-    print '<input type="hidden" name="actionmove" value="mupdate">';
-    print '<input type="hidden" name="backtopage" value="' . dol_escape_htmltag($_SERVER['PHP_SELF']) . '?mode=show_month&' . dol_escape_htmltag($_SERVER['QUERY_STRING']) . '">';
-    print '<input type="hidden" name="newdate" id="newdate">';
-} elseif ($mode == 'show_week') {
-    // View by week
-    $newparam = $param; // newparam is for birthday links
-    $newparam = preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done
-    $newparam = preg_replace('/mode=show_month&?/i', '', $newparam);
-    $newparam = preg_replace('/mode=show_week&?/i', '', $newparam);
-    $newparam = preg_replace('/day=[0-9]+&?/i', '', $newparam);
-    $newparam = preg_replace('/month=[0-9]+&?/i', '', $newparam);
-    $newparam = preg_replace('/year=[0-9]+&?/i', '', $newparam);
-    $newparam = preg_replace('/viewweek=[0-9]+&?/i', '', $newparam);
-    $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter
-    $newparam .= '&viewweek=1';
-
-    /* print '<div class="liste_titre liste_titre_bydiv centpercent"><div class="divsearchfield">';
+// View by day
+$newparam = $param; // newparam is for birthday links
+$newparam = preg_replace('/mode=show_month&?/i', '', $newparam);
+$newparam = preg_replace('/mode=show_week&?/i', '', $newparam);
+$newparam = preg_replace('/viewday=[0-9]+&?/i', '', $newparam);
+$newparam .= '&viewday=1';
+// Code to show just one day
+$style = 'cal_current_month cal_current_month_oneday';
+$today = 0;
+$todayarray = dol_getdate($now, 'fast');
+if ($todayarray['mday'] == $day && $todayarray['mon'] == $month && $todayarray['year'] == $year) {
+    $today = 1;
+}
+//if ($today) $style='cal_today';
+
+$timestamp = dol_mktime(12, 0, 0, $month, $day, $year);
+$arraytimestamp = dol_getdate($timestamp);
+
+/* print '<div class="liste_titre liste_titre_bydiv centpercent"><div class="divsearchfield">';
        print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid);
        print '</div></div>'; */
 
-    print '<div class="div-table-responsive-no-min sectioncalendarbyweek maxscreenheightless300">';
-    print '<table class="centpercent noborder nocellnopadd cal_pannel cal_month">';
-    print ' <tr class="liste_titre">';
-    $i = 0;
-    while ($i < 7) {
-        echo '  <td class="center bold uppercase tdfordaytitle">' . $langs->trans("Day" . (($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7)) . "</td>\n";
-        $i++;
-    }
-    echo " </tr>\n";
+print '<div class="div-table-responsive-no-min sectioncalendarbyday maxscreenheightless300">';
+echo '<table class="tagtable centpercent noborder nocellnopadd cal_pannel cal_month noborderbottom" style="margin-bottom: 5px !important;">';
 
-    echo " <tr>\n";
+echo ' <tr class="tagtr liste_titre">';
+echo '  <td class="tagtd center bold uppercase">' . $langs->trans("Day" . $arraytimestamp['wday']) . "</td>\n";
+echo " </td>\n";
 
-    for ($iter_day = 0; $iter_day < 7; $iter_day++) {
-        // Show days of the current week
-        $curtime = dol_time_plus_duree($firstdaytoshow, $iter_day, 'd');		// $firstdaytoshow is in timezone of server
-        $tmpday = dol_print_date($curtime, '%d', 'tzuserrel');
-        $tmpmonth = dol_print_date($curtime, '%m', 'tzuserrel');
-        $tmpyear = dol_print_date($curtime, '%Y', 'tzuserrel');
+echo '</table>';
+print '</div>';
 
-        $style = 'cal_current_month';
-        if ($iter_day == 6) {
-            $style .= ' cal_other_month_right';
-        }
+$eventdayDates = $bookingAgendaHelper->getEventDayDates($year, $month, $day);
 
-        $today = 0;
-        $todayarray = dol_getdate($now, 'fast');
-        if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $tmpmonth && $todayarray['year'] == $tmpyear) {
-            $today = 1;
-        }
-        if ($today) {
-            $style = 'cal_today';
-        }
+print '<div id="dateview">Updated content: ' . date("Y-m-d H:i:s") . '</div>';
+print $eventdayDates['eventdayprint'];
 
-        echo '  <td class="' . $style . '" width="14%" valign="top">';
-        show_day_events($db, $tmpday, $tmpmonth, $tmpyear, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300);
+print '<input type="hidden" id="jsyear" name="jsyear" value="' . $year . '">
+<input type="hidden" id="jsmonth" name="jsmonth" value="' . $month . '">
+<input type="hidden" id="jsday" name="jsday" value="' . $day . '">
+<input type="hidden" id="selectedEvent" name="selectedEvent" value="">';
+print '<div id="dayviewdiv" class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
+$bookingAgendaHelper->showTable($eventdayDates, $selectedEvent);
+print '</div>';
+print '<div id="eventdetailviewdiv"></div>';
 
-        echo "  </td>\n";
+print "\n" . '</form>';
+?>
+<script>
+    $(document).ready(function() {
+        console.log("ready!");
+        const selectedEvent = document.getElementById('selectedEvent');
+        const value = selectedEvent.value;
+        console.log(value);
+    });
+
+    function ShoMeTheEventDeatils(id) {
+        const eventdetailviewdiv = document.getElementById('eventdetailviewdiv');
+        $('#selectedEvent').attr('value', id);
+
+        const xhr = new XMLHttpRequest();
+        xhr.open('GET', 'booking_agenda_event_details_view.php?event=' + id, true);
+
+        xhr.onload = function() {
+            if (xhr.status === 200) {
+                eventdetailviewdiv.innerHTML = xhr.responseText;
+            } else {
+                console.error('Error fetching content:', xhr.status, xhr.statusText);
+            }
+        };
+        xhr.send();
     }
-    echo " </tr>\n";
 
-    print "</table>\n";
-    print '</div>';
+    function formatDate(date) {
+        const year = date.getFullYear();
+        const month = String(date.getMonth() + 1).padStart(2, '0'); // Hónap 0-alapú, ezért +1
+        const day = String(date.getDate()).padStart(2, '0');
+        const hours = String(date.getHours()).padStart(2, '0');
+        const minutes = String(date.getMinutes()).padStart(2, '0');
+        const seconds = String(date.getSeconds()).padStart(2, '0');
 
-    echo '<input type="hidden" name="actionmove" value="mupdate">';
-    echo '<input type="hidden" name="backtopage" value="' . dol_escape_htmltag($_SERVER['PHP_SELF']) . '?mode=show_week&' . dol_escape_htmltag($_SERVER['QUERY_STRING']) . '">';
-    echo '<input type="hidden" name="newdate" id="newdate">';
-} else { // View by day
-    $newparam = $param; // newparam is for birthday links
-    $newparam = preg_replace('/mode=show_month&?/i', '', $newparam);
-    $newparam = preg_replace('/mode=show_week&?/i', '', $newparam);
-    $newparam = preg_replace('/viewday=[0-9]+&?/i', '', $newparam);
-    $newparam .= '&viewday=1';
-    // Code to show just one day
-    $style = 'cal_current_month cal_current_month_oneday';
-    $today = 0;
-    $todayarray = dol_getdate($now, 'fast');
-    if ($todayarray['mday'] == $day && $todayarray['mon'] == $month && $todayarray['year'] == $year) {
-        $today = 1;
+        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
     }
-    //if ($today) $style='cal_today';
-
-    $timestamp = dol_mktime(12, 0, 0, $month, $day, $year);
-    $arraytimestamp = dol_getdate($timestamp);
-
-    /* print '<div class="liste_titre liste_titre_bydiv centpercent"><div class="divsearchfield">';
-       print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid);
-       print '</div></div>'; */
-
-    print '<div class="div-table-responsive-no-min sectioncalendarbyday maxscreenheightless300">';
-    echo '<table class="tagtable centpercent noborder nocellnopadd cal_pannel cal_month noborderbottom" style="margin-bottom: 5px !important;">';
-
-    echo ' <tr class="tagtr liste_titre">';
-    echo '  <td class="tagtd center bold uppercase">' . $langs->trans("Day" . $arraytimestamp['wday']) . "</td>\n";
-    echo " </td>\n";
-
-    /*
-        echo ' <div class="tagtr">';
-        echo '  <div class="tagtd width100"></div>';
-        echo '  <div class="tagtd center">';
-        echo show_day_events($db, $day, $month, $year, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, -1);
-        echo '  </div>'."\n";
-        echo " </div>\n";
-        */
-
-    echo '</table>';
-    print '</div>';
 
-    /* WIP View per hour */
-    $useviewhour = 0;
-    if ($useviewhour) {
-        print '<div class="div-table-responsive-no-min borderbottom">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
-
-        $maxheightwin = (isset($_SESSION["dol_screenheight"]) && $_SESSION["dol_screenheight"] > 500) ? ($_SESSION["dol_screenheight"] - 200) : 660; // Also into index.php file
-
-        echo '<div style="max-height: ' . $maxheightwin . 'px;">';
-        echo '<div class="tagtable centpercent calendarviewcontainer">';
-
-        $maxnbofchar = 80;
-
-        $tmp = explode('-', $conf->global->MAIN_DEFAULT_WORKING_HOURS);
-        $minhour = round($tmp[0], 0);
-        $maxhour = round($tmp[1], 0);
-        if ($minhour > 23) {
-            $minhour = 23;
-        }
-        if ($maxhour < 1) {
-            $maxhour = 1;
-        }
-        if ($maxhour <= $minhour) {
-            $maxhour = $minhour + 1;
-        }
-
-        $i = 0;
-        $j = 0;
-        while ($i < 24) {
-            echo ' <div class="tagtr calendarviewcontainertr">' . "\n";
-            echo '  <div class="tagtd width100 tdtop">' . dol_print_date($i * 3600, 'hour', 'gmt') . '</div>';
-            echo '  <div class="tagtd ' . $style . ' tdtop"></div>' . "\n";
-            echo ' </div>' . "\n";
-            $i++;
-            $j++;
-        }
-
-        echo '</div></div>';
-
-        show_day_events($db, $day, $month, $year, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, 1);
-
-        print '</div>';
-    } else {
-        $eventdayDates = $bookingAgendaHelper->getEventDayDates($year, $month, $day);
-
-        print $eventdayDates['eventdayprint'];
-        $k = 0;
-        $dailyStartTime = 9;
-        $dailyEndTime = 21;
-        $eventsArray = [];
-        $daysql = "SELECT 
-            ed.rowid as eventdetail_id, 
-            ed.label as eventdetail_label,
-            ac.id as actioncomm_id,
-            ac.datep,
-            ac.datep2,
-            ac.durationp,
-            ace.buffer,
-            ace.max_num,
-            ace.participants,
-            ed.fk_elventlocation_departure
-        FROM llx_eventwizard_eventdetails as ed 
-        INNER JOIN llx_actioncomm as ac ON ac.fk_element = ed.rowid
-        INNER JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
-        WHERE ed.type IN (3,4)
-        AND ac.code = 'AC_EVENT'
-        AND ac.datep BETWEEN '{$eventdayDates['from']}' AND '{$eventdayDates['to']}'
-        AND ace.participants IS NOT NULL
-        ORDER BY ac.id DESC";
-
-        //print $daysql;
-
-        $eventsArray = $bookingAgendaHelper->getOneColumnFromTable($daysql, $eventsArray, 'actioncomm_id');
-        $locationArray = $bookingAgendaHelper->getlocations();
-
-        print '<div class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
-        print '<table style="width:100%">';
-        print '<tr class="firstcolumn">
-        <td style="width:15%">' . $langs->trans('Location') . '</td>
-        <td style="width:7%">' . $langs->trans('Status') . '</td>';
-        for ($i = 9; $i < 21; $i++) {
-            $hourText = $i < 10 ? '0' . $i : $i;
-            //print '<td>' . $hourText . ':00 - ' . $hourText . ':59</td>';
-            print '<td>' . $hourText . '</td>';
-            $k++;
-        }
-        $k = $k + 2;
-        print '<tr class="elvalaszto"><td colspan="' . $k . '"></td></tr>';
-        print '</tr>';
-        /* print '<tr class="trheight">
-            <td class="firstcolumn"></td>
-            <td class="center">Max. létszám</td>';
-        $rowcolorCounter = 0;
-        for ($i = $dailyStartTime; $i < $dailyEndTime; $i++) {
-            $backgroundColor = $bookingAgendaHelper->getBGColor($rowcolorCounter);
-            $hourText = $bookingAgendaHelper->getHourText($i);
-            print '<td class="center" style="background-color: ' . $backgroundColor . ';">' . $bookingAgendaHelper->getMaxNumFromEVENT($eventsArray) . '</td>';
-            $rowcolorCounter++;
-        }
-        print '</tr>'; */
-        foreach ($eventsArray as $event) {
-            print '<tr class="trheight">
-            <td class="firstcolumn"></td>
-            <td class="center">Foglalás</td>';
-            $rowcolorCounter = 0;
-            for ($i = $dailyStartTime; $i < $dailyEndTime; $i++) {
-                $backgroundColor = $bookingAgendaHelper->getBGColor($rowcolorCounter);
-                $hourText = $bookingAgendaHelper->getHourText($i);
-                print '<td class="center" style="background-color: ' . $backgroundColor . ';">' . $bookingAgendaHelper->getsumReservation($event, $eventdayDates['eventday'], $hourText) . '</td>';
-                $rowcolorCounter++;
-            }
-            print '</tr>';
-            print '<tr class="trheight foglaltsag">
-            <td class="location firstcolumn">' . $locationArray[$bookingAgendaHelper->getLocationLabel($event)] . '</td>
-            <td class="center">Foglalt</td>';
-            $rowcolorCounter = 0;
-            for ($i = $dailyStartTime; $i < $dailyEndTime; $i++) {
-                $backgroundColor = $bookingAgendaHelper->getBGColor($rowcolorCounter);
-                $hourText = $bookingAgendaHelper->getHourText($i);
-                print '<td class="center" style="background-color: ' . $backgroundColor . ';">' . $bookingAgendaHelper->getsumOccupied($event, $eventdayDates['eventday'], $hourText) . '</td>';
-                $rowcolorCounter++;
-            }
-            print '</tr>';
-            print '<tr class="trheight">
-            <td class="firstcolumn"></td>
-            <td class="center">Szervíz</td>';
-            $rowcolorCounter = 0;
-            for ($i = $dailyStartTime; $i < $dailyEndTime; $i++) {
-                $backgroundColor = $bookingAgendaHelper->getBGColor($rowcolorCounter);
-                $hourText = $bookingAgendaHelper->getHourText($i);
-                print '<td class="center" style="background-color: ' . $backgroundColor . ';">' . $bookingAgendaHelper->getsumService($event, $eventdayDates['eventday'], $hourText) . '</td>';
-                $rowcolorCounter++;
+    function updateDivContent() {
+        const selectedEvent = document.getElementById('selectedEvent');
+        const value = selectedEvent.value;
+        const dateview = document.getElementById('dateview');
+        const dayviewdiv = document.getElementById('dayviewdiv');
+        var year = document.getElementById('jsyear');
+        var month = document.getElementById('jsmonth');
+        var day = document.getElementById('jsday');
+        const now = new Date();
+        document.getElementById('dateview').innerText = 'Updated content: ' + formatDate(now);
+        const xhr = new XMLHttpRequest();
+        xhr.open('GET', 'booking_agenda_table_view.php?year=' + year.value + '&month=' + month.value + '&day=' + day.value, true);
+
+        xhr.onload = function() {
+            if (xhr.status === 200) {
+                dayviewdiv.innerHTML = xhr.responseText;
+            } else {
+                console.error('Error fetching content:', xhr.status, xhr.statusText);
             }
-            print '</tr>';
-            print '<tr class="elvalaszto"><td colspan="' . $k . '"></td></tr>';
+        };
+        xhr.send();
+        if (value != '') {
+            console.log(value);
+            ShoMeTheEventDeatils(value);
         }
-        print '</div>';
     }
-}
-
-print "\n" . '</form>';
-?>
+    setInterval(updateDivContent, 1000);
+</script>
 <style>
     .trheight {
         height: 50px;
@@ -1744,7 +1190,7 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa
     global $theme_datacolor;
     global $cachethirdparties, $cachecontacts, $cacheusers, $colorindexused;
 
-    if ($conf->use_javascript_ajax) {	// Enable the "Show more button..."
+    if ($conf->use_javascript_ajax) {    // Enable the "Show more button..."
         $conf->global->MAIN_JS_SWITCH_AGENDA = 1;
     }
 
@@ -1810,10 +1256,10 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa
     include_once DOL_DOCUMENT_ROOT . '/holiday/class/holiday.class.php';
     $tmpholiday = new Holiday($db);
 
-    foreach ($eventarray as $daykey => $notused) {		// daykey is the 'YYYYMMDD' to show according to user
-        $annee = dol_print_date($daykey, '%Y', 'gmt');	// We use gmt because we want the value represented by string 'YYYYMMDD'
-        $mois = dol_print_date($daykey, '%m', 'gmt');	// We use gmt because we want the value represented by string 'YYYYMMDD'
-        $jour = dol_print_date($daykey, '%d', 'gmt');	// We use gmt because we want the value represented by string 'YYYYMMDD'
+    foreach ($eventarray as $daykey => $notused) {        // daykey is the 'YYYYMMDD' to show according to user
+        $annee = dol_print_date($daykey, '%Y', 'gmt');    // We use gmt because we want the value represented by string 'YYYYMMDD'
+        $mois = dol_print_date($daykey, '%m', 'gmt');    // We use gmt because we want the value represented by string 'YYYYMMDD'
+        $jour = dol_print_date($daykey, '%d', 'gmt');    // We use gmt because we want the value represented by string 'YYYYMMDD'
 
         //print 'event daykey='.$daykey.' dol_print_date(daykey)='.dol_print_date($daykey, 'dayhour', 'gmt').' jour='.$jour.' mois='.$mois.' annee='.$annee."<br>\n";
 
@@ -1875,7 +1321,7 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa
                         }
                     }
 
-                    if ($color < 0) {	// Color was not set on user card. Set color according to color index.
+                    if ($color < 0) {    // Color was not set on user card. Set color according to color index.
                         // Define color index if not yet defined
                         $idusertouse = ($event->userownerid ? $event->userownerid : 0);
                         if (isset($colorindexused[$idusertouse])) {
@@ -1966,7 +1412,7 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa
                     //var_dump($event->userassigned);
                     //var_dump($event->transparency);
                     print '<table class="centpercent cal_event';
-                    print (empty($event->transparency) ? ' cal_event_notbusy' : ' cal_event_busy');
+                    print(empty($event->transparency) ? ' cal_event_notbusy' : ' cal_event_busy');
                     //if (empty($event->transparency) && empty($conf->global->AGENDA_NO_TRANSPARENT_ON_NOT_BUSY)) print ' opacitymedium';	// Not busy
                     print '" style="' . $h;
                     $colortouse = $color;
@@ -1991,9 +1437,9 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa
 
                     $daterange = '';
 
-                    if ($event->type_code == 'BIRTHDAY') { 			// It's birthday calendar
+                    if ($event->type_code == 'BIRTHDAY') {             // It's birthday calendar
                         print $event->getNomUrl(1, $maxnbofchar, 'cal_event', 'birthday', 'contact');
-                    } elseif ($event->type_code == 'HOLIDAY') {		// It's holiday calendar
+                    } elseif ($event->type_code == 'HOLIDAY') {        // It's holiday calendar
                         $tmpholiday->fetch($event->id);
 
                         print $tmpholiday->getNomUrl(1);
@@ -2008,7 +1454,7 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa
                         $listofusertoshow = '';
                         $listofusertoshow .= '<br>' . $cacheusers[$tmpid]->getNomUrl(-1, '', 0, 0, 0, 0, '', 'paddingright valigntextbottom');
                         print $listofusertoshow;
-                    } else {										// Other calendar
+                    } else {                                        // Other calendar
                         // Picto
                         if (empty($event->fulldayevent)) {
                             //print $event->getNomUrl(2).' ';
@@ -2059,7 +1505,7 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa
                         if ($event->type_code != 'ICALEVENT') {
                             $savlabel = $event->label ? $event->label : $event->libelle;
                             $event->label = $titletoshow;
-                            $event->libelle = $titletoshow;		// deprecatd
+                            $event->libelle = $titletoshow;        // deprecatd
                             // Note: List of users are inside $event->userassigned. Link may be clickable depending on permissions of user.
                             //$titletoshow = (($event->type_picto || $event->type_code) ? $event->getTypePicto() : '');
                             $titletoshow .= $event->getNomUrl(0, $maxnbofchar, 'cal_event cal_event_title', '', 0, 0);
@@ -2165,9 +1611,9 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa
                 } else {
                     print '<a href="' . DOL_URL_ROOT . '/custom/booking/booking_agenda.php?mode=' . $mode . '&maxprint=0&month=' . ((int) $monthshown) . '&year=' . ((int) $year);
                     print ($status ? '&status=' . $status : '') . ($filter ? '&filter=' . urlencode($filter) : '');
-                    print ($filtert ? '&search_filtert=' . urlencode($filtert) : '');
-                    print ($usergroup ? '&search_usergroup=' . urlencode($usergroup) : '');
-                    print ($actioncode != '' ? '&search_actioncode=' . urlencode($actioncode) : '');
+                    print($filtert ? '&search_filtert=' . urlencode($filtert) : '');
+                    print($usergroup ? '&search_usergroup=' . urlencode($usergroup) : '');
+                    print($actioncode != '' ? '&search_actioncode=' . urlencode($actioncode) : '');
                     print '">' . img_picto("all", "1downarrow_selected.png") . ' ...';
                     print ' +' . (count($eventarray[$daykey]) - $maxprint);
                     print '</a>';
@@ -2179,7 +1625,7 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa
             break;
         }
     }
-    if (!$i) {	// No events
+    if (!$i) {    // No events
         print '&nbsp;';
     }
 
@@ -2210,7 +1656,6 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa
     print "\n";
 }
 
-
 /**
  * Change color with a delta
  *

+ 64 - 0
custom/booking/booking_agenda_event_details_view.php

@@ -0,0 +1,64 @@
+<?php
+$res = 0;
+// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
+if (!$res && !empty ($_SERVER["CONTEXT_DOCUMENT_ROOT"])) {
+    $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"] . "/main.inc.php";
+}
+// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
+$tmp = empty ($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME'];
+$tmp2 = realpath(__FILE__);
+$i = strlen($tmp) - 1;
+$j = strlen($tmp2) - 1;
+while ($i > 0 && $j > 0 && isset ($tmp[$i]) && isset ($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
+    $i--;
+    $j--;
+}
+if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1)) . "/main.inc.php")) {
+    $res = @include substr($tmp, 0, ($i + 1)) . "/main.inc.php";
+}
+if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1))) . "/main.inc.php")) {
+    $res = @include dirname(substr($tmp, 0, ($i + 1))) . "/main.inc.php";
+}
+// Try main.inc.php using relative path
+if (!$res && file_exists("../main.inc.php")) {
+    $res = @include "../main.inc.php";
+}
+if (!$res && file_exists("../../main.inc.php")) {
+    $res = @include "../../main.inc.php";
+}
+if (!$res && file_exists("../../../main.inc.php")) {
+    $res = @include "../../../main.inc.php";
+}
+if (!$res) {
+    die ("Include of main fails");
+}
+$event = $_GET['event'];
+
+require_once DOL_DOCUMENT_ROOT . '/custom/booking/class/booking_agenda_helper.class.php';
+$bookingAgendaHelper = new BookingAgendaHelper($db);
+$bookingAgendaHelper->getSelectedEvents($event);
+?>
+<style>
+    .trheight {
+        height: 50px;
+    }
+
+    .elvalaszto {
+        background-color: grey;
+    }
+
+    .foglaltsag {
+        color: red;
+    }
+
+    .location {
+        color: black;
+    }
+
+    .firstcolumn {
+        background-color: lightgrey;
+        text-align: center;
+        font-weight: bold;
+    }
+</style>
+

+ 67 - 0
custom/booking/booking_agenda_table_view.php

@@ -0,0 +1,67 @@
+<?php
+$res = 0;
+// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
+if (!$res && !empty ($_SERVER["CONTEXT_DOCUMENT_ROOT"])) {
+    $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"] . "/main.inc.php";
+}
+// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
+$tmp = empty ($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME'];
+$tmp2 = realpath(__FILE__);
+$i = strlen($tmp) - 1;
+$j = strlen($tmp2) - 1;
+while ($i > 0 && $j > 0 && isset ($tmp[$i]) && isset ($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
+    $i--;
+    $j--;
+}
+if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1)) . "/main.inc.php")) {
+    $res = @include substr($tmp, 0, ($i + 1)) . "/main.inc.php";
+}
+if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1))) . "/main.inc.php")) {
+    $res = @include dirname(substr($tmp, 0, ($i + 1))) . "/main.inc.php";
+}
+// Try main.inc.php using relative path
+if (!$res && file_exists("../main.inc.php")) {
+    $res = @include "../main.inc.php";
+}
+if (!$res && file_exists("../../main.inc.php")) {
+    $res = @include "../../main.inc.php";
+}
+if (!$res && file_exists("../../../main.inc.php")) {
+    $res = @include "../../../main.inc.php";
+}
+if (!$res) {
+    die ("Include of main fails");
+}
+$year = GETPOST('year', 'aZ09');
+$month = GETPOST('month', 'aZ09');
+$day = GETPOST('day', 'aZ09');
+
+require_once DOL_DOCUMENT_ROOT . '/custom/booking/class/booking_agenda_helper.class.php';
+$bookingAgendaHelper = new BookingAgendaHelper($db);
+$eventdayDates = $bookingAgendaHelper->getEventDayDates($year, $month, $day);
+$bookingAgendaHelper->showTable($eventdayDates, $selectedEvent);
+?>
+<style>
+    .trheight {
+        height: 50px;
+    }
+
+    .elvalaszto {
+        background-color: grey;
+    }
+
+    .foglaltsag {
+        color: red;
+    }
+
+    .location {
+        color: black;
+    }
+
+    .firstcolumn {
+        background-color: lightgrey;
+        text-align: center;
+        font-weight: bold;
+    }
+</style>
+

+ 363 - 352
custom/booking/class/api_booking.class.php

@@ -68,6 +68,172 @@ class BookingApi extends DolibarrApi
 		// $this->bookinglog = new BookingLog($this->db);
 	}
 
+	#-------------------------------------------------
+	#	Vásárlási folyamat részei
+	#-------------------------------------------------
+
+	/**
+	 * Get all free spaces on a selected date
+	 *
+	 * Return an array with details
+	 *
+	 * @return 	array|mixed data without useless information
+	 *
+	 * @param 	string 	date_from
+	 * @param 	string 	date_to
+	 * @param 	int 	product_id
+	 * @param 	int 	participant_number
+	 * 
+	 * @url	POST getavailablespaces
+	 *
+	 * @throws RestException 401 Not allowed
+	 * @throws RestException 404 Not found
+	 */
+	public function getAvailableSpaces(string $date_from, string $date_to, int $product_id, int $participant_number, string $type_id = null)
+	{
+		ApiBbusLog::appLog("getAvailableSpaces");
+		/* ApiBbusLog::appLog("type_id: {$type_id}");
+		ApiBbusLog::appLog("date_from: {$date_from}");
+		ApiBbusLog::appLog("date_to: {$date_to}");
+		ApiBbusLog::appLog("product_id: {$product_id}");
+		ApiBbusLog::appLog("participant_number: {$participant_number}"); */
+		$basicServices = new BasicServices($this->db);
+		$resultBS = $basicServices->fetch($type_id);
+		if ($basicServices->server_host == 'excelia') {
+			return $this->localAvailablePlaces($date_from, $date_to, $product_id, $participant_number);
+		} else {
+			return $this->curlAvailablePlaces($date_from, $date_to, $product_id, $participant_number);
+		}
+	}
+
+	/**
+	 * First step of the eventhandling
+	 * {"fk_event":669,"reservations":1,"product_id":2,"sendId":"12121212"}
+	 *
+	 * Return an array with details
+	 *
+	 * @return 	array|mixed data without useless information
+	 *
+	 * @param 	int 	$fk_event			//selected evet from llx_event
+	 * @param 	int 	$reservations		//numbers of reservations
+	 * @param 	int 	$product_id			//Product
+	 * @param 	string	$sendId				//ID
+	 * 
+	 * @url	POST firsteventstep
+	 * @access protected
+	 * @throws RestException 401 Not allowed
+	 * @throws RestException 404 Not found
+	 * @throws RestException 506 No available spaces
+	 * 
+	 */
+	public function firstEventStep(int $fk_event, int $reservations, int $product_id, string $sendId)
+	{
+		ApiBbusLog::eventLog("fk_event: {$fk_event}");
+		ApiBbusLog::eventLog("reservations: {$reservations}");
+		ApiBbusLog::eventLog("product_id: {$product_id}");
+		ApiBbusLog::eventLog("sendId: {$sendId}");
+		$eventHelper = new EventHelper;
+		if ($eventHelper->noEmptySpaces($fk_event, $reservations)) {
+			throw new RestException(506, 'No available spaces');
+		}
+
+		if (!DolibarrApiAccess::$user->rights->facture->creer) {
+			ApiBbusLog::eventLog("{$sendId} Insufficient rights");
+			throw new RestException(401, 'Insufficient rights');
+		}
+		/**
+		 * LOG SECTION
+		 */
+		ApiBbusLog::eventLog("{$sendId} === NEW INVOICE ===");
+		dol_syslog("{$sendId} === NEW INVOICE ===", LOG_INFO, 0);
+		ApiBbusLog::eventLog("{$sendId} REQUEST: {$sendId}");
+		dol_syslog("{$sendId} REQUEST: {$sendId}", LOG_INFO, 0);
+		ApiBbusLog::eventLog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})");
+		dol_syslog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})", LOG_INFO, 0);
+		ApiBbusLog::eventLog("{$sendId} " . json_encode([
+			'fk_event' => $fk_event,
+			'reservations' => $reservations,
+			'product_id' => $product_id,
+			'sendId' => $sendId,
+		]));
+
+		$apiInvoiceHelper = new ApiInvoiceHelper;
+		$createdPreOrderOBJ = [];
+
+		for ($i = 1; $i <= $reservations; $i++) {
+			dol_include_once('/comm/action/class/actioncomm.class.php');
+			dol_include_once('/custom/booking/class/preorder.class.php');
+			$apiInvoiceHelper->increaseParticipant($fk_event);
+
+			$lines = $apiInvoiceHelper->getProductLines($product_id);
+			foreach ($lines as $line) {
+				$preOrderObj = new PreOrder($this->db);
+				$preOrderObj->ref = $this->generateRandomString();
+				$preOrderObj->fk_event = $fk_event;
+				$preOrderObj->fk_product = $product_id;
+				$result = $preOrderObj->create($this->user);
+				if ($result > 0) {
+					$createdPreOrderOBJ[] = [
+						'id' => $preOrderObj->id,
+						'ref' => $preOrderObj->ref,
+					];
+				} else {
+					ApiBbusLog::eventLog(json_encode(['error' => $preOrderObj->errors]));
+					ApiBbusLog::eventLog("Unsaved event: " . $fk_event);
+					throw new RestException(401, 'Unsaved event: ' . $fk_event);
+				}
+			}
+		}
+		return $createdPreOrderOBJ;
+	}
+
+	/**
+	 * Validate and save invoice
+	 * {"cardPaymentLog": "","sendId": "Xune5nQb","payment": {"datepaye": 1720005853,"paymentid": 4,"accountid": 2,"closepaidinvoices": "yes"},"preorder": [23]}
+	 *
+	 * Return an array with details
+	 *
+	 * @return 	array|mixed data without useless information
+	 *
+	 * @param 	string	$sendId				sendID
+	 * @param  	array 	$payment			Invoice payment
+	 * @param  	array 	$preorder			preorder
+	 * @param  	array 	$invoice			Invoice
+	 * @param  	string 	$cardPaymentLog		Card payment log data
+	 * 
+	 * @url	POST validateandsaveinvoice
+	 * @access protected
+
+	 * @throws RestException 401 Not allowed
+	 * @throws RestException 404 Not found
+	 * @throws RestException 506 No available spaces
+	 * 
+	 */
+	public function validateandsaveinvoice(string $sendId, array $payment, array $preorder, array $invoice, string $cardPaymentLog = '')
+	{
+		global $user, $db;
+		$createdInvoiceData = [];
+		$apiInvoiceHelper = new ApiInvoiceHelper;
+		$bbusApi = new BBus();
+		foreach ($preorder as $order) {
+			$sql = "SELECT fk_product, fk_event  FROM llx_booking_preorder WHERE rowid = {$order}";
+			//print $sql . "\r\n";
+			$data = $db->query($sql);
+			if ($db->num_rows($data) > 0) {
+				while ($row = $db->fetch_object($data)) {
+					//print_r($row);
+					$lines = $apiInvoiceHelper->getProductLines($row->fk_product);
+					$createdInvoiceArray = $bbusApi->invoice($invoice, $lines, $payment, $cardPaymentLog = '', $sendId = '');
+					$createdInvoiceData[] = $createdInvoiceArray;
+					$bookingHistory = $this->saveEventData((int)$row->fk_event, $createdInvoiceArray['invoice']['ref'], $createdInvoiceArray['invoice']['id']);
+					$this->updateBbticket($bookingHistory, $createdInvoiceArray['invoice']);
+					$this->deletePreorder($preorder);
+				}
+			}
+		}
+		return $createdInvoiceData;
+	}
+
 	//P4NR6zhWHage
 	//!!!types:
 
@@ -526,160 +692,6 @@ class BookingApi extends DolibarrApi
 		return $productsArray;
 	}
 
-	/**
-	 * First step of the eventhandling
-	 * {"invoice":{"array_options_app_facture":1,"array_options_customer_data_zip":6782,"multicurrency_code":"HUF","fk_multicurrency":3,"mode_reglement_id":14,"cond_reglement_id":14,"fk_account":4},"fk_event":82586,"reservations":1,"sendId":12121212,"product_id":155}
-	 *
-	 * Return an array with details
-	 *
-	 * @return 	array|mixed data without useless information
-	 *
-	 * @param  array 	$invoice			Invoice data
-	 * @param 	int 	$fk_event			//selected evet from llx_event
-	 * @param 	int 	$reservations		//numbers of reservations
-	 * @param 	int 	$product_id			//Product
-	 * @param 	string	$sendId				//ID
-	 * 
-	 * @url	POST firsteventstepold
-	 * @access protected
-	 * @throws RestException 401 Not allowed
-	 * @throws RestException 404 Not found
-	 * @throws RestException 506 No available spaces
-	 * 
-	 */
-	public function firstEventStepOld(array $invoice, int $fk_event, int $reservations, int $product_id, string $sendId)
-	{
-		$eventHelper = new EventHelper;
-		if ($eventHelper->noEmptySpaces($fk_event, $reservations)) {
-			throw new RestException(506, 'No available spaces');
-		}
-
-		if (!DolibarrApiAccess::$user->rights->facture->creer) {
-			ApiBbusLog::eventLog("{$sendId} Insufficient rights");
-			throw new RestException(401, 'Insufficient rights');
-		}
-		/**
-		 * LOG SECTION
-		 */
-		ApiBbusLog::eventLog("{$sendId} === NEW INVOICE ===");
-		dol_syslog("{$sendId} === NEW INVOICE ===", LOG_INFO, 0);
-		ApiBbusLog::eventLog("{$sendId} REQUEST: {$sendId}");
-		dol_syslog("{$sendId} REQUEST: {$sendId}", LOG_INFO, 0);
-		ApiBbusLog::eventLog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})");
-		dol_syslog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})", LOG_INFO, 0);
-		ApiBbusLog::eventLog("{$sendId} " . json_encode([
-			'invoice' => $invoice,
-			'fk_event' => $fk_event,
-			'reservations' => $reservations,
-			'product_id' => $product_id,
-			'sendId' => $sendId,
-		]));
-
-		$apiInvoiceHelper = new ApiInvoiceHelper;
-		$createdInvoicePROVs = [];
-
-		for ($i = 1; $i <= $reservations; $i++) {
-			dol_include_once('/comm/action/class/actioncomm.class.php');
-			$apiInvoiceHelper->increaseParticipant($fk_event);
-			$invoiceObj = $apiInvoiceHelper->createInvoicePROV($invoice, $sendId);
-			$createdInvoicePROVs[] = [
-				'id' => $invoiceObj->id,
-				'ref' => $invoiceObj->ref,
-			];
-			ApiBbusLog::eventLog("{$sendId} - Invoice PROV created - " . $invoiceObj->id . ' - ' . $invoiceObj->ref);
-			$lines = $apiInvoiceHelper->getProductLines($product_id);
-			foreach ($lines as $line) {
-				$invoiceLineObj = $apiInvoiceHelper->addLineToInvoice($invoiceObj, $line, $sendId);
-				$this->saveEventData($fk_event, $invoiceObj->id, $fk_eventproduct = 1);
-			}
-			$invoiceLineObj->fetch_lines();
-		}
-		print_r($createdInvoicePROVs);
-		exit;
-		return $createdInvoicePROVs;
-	}
-
-	/**
-	 * First step of the eventhandling
-	 * {"fk_event":669,"reservations":1,"product_id":2,"sendId":"12121212"}
-	 *
-	 * Return an array with details
-	 *
-	 * @return 	array|mixed data without useless information
-	 *
-	 * @param 	int 	$fk_event			//selected evet from llx_event
-	 * @param 	int 	$reservations		//numbers of reservations
-	 * @param 	int 	$product_id			//Product
-	 * @param 	string	$sendId				//ID
-	 * 
-	 * @url	POST firsteventstep
-	 * @access protected
-	 * @throws RestException 401 Not allowed
-	 * @throws RestException 404 Not found
-	 * @throws RestException 506 No available spaces
-	 * 
-	 */
-	public function firstEventStep(int $fk_event, int $reservations, int $product_id, string $sendId)
-	{
-		ApiBbusLog::eventLog("fk_event: {$fk_event}");
-		ApiBbusLog::eventLog("reservations: {$reservations}");
-		ApiBbusLog::eventLog("product_id: {$product_id}");
-		ApiBbusLog::eventLog("sendId: {$sendId}");
-		$eventHelper = new EventHelper;
-		if ($eventHelper->noEmptySpaces($fk_event, $reservations)) {
-			throw new RestException(506, 'No available spaces');
-		}
-
-		if (!DolibarrApiAccess::$user->rights->facture->creer) {
-			ApiBbusLog::eventLog("{$sendId} Insufficient rights");
-			throw new RestException(401, 'Insufficient rights');
-		}
-		/**
-		 * LOG SECTION
-		 */
-		ApiBbusLog::eventLog("{$sendId} === NEW INVOICE ===");
-		dol_syslog("{$sendId} === NEW INVOICE ===", LOG_INFO, 0);
-		ApiBbusLog::eventLog("{$sendId} REQUEST: {$sendId}");
-		dol_syslog("{$sendId} REQUEST: {$sendId}", LOG_INFO, 0);
-		ApiBbusLog::eventLog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})");
-		dol_syslog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})", LOG_INFO, 0);
-		ApiBbusLog::eventLog("{$sendId} " . json_encode([
-			'fk_event' => $fk_event,
-			'reservations' => $reservations,
-			'product_id' => $product_id,
-			'sendId' => $sendId,
-		]));
-
-		$apiInvoiceHelper = new ApiInvoiceHelper;
-		$createdPreOrderOBJ = [];
-
-		for ($i = 1; $i <= $reservations; $i++) {
-			dol_include_once('/comm/action/class/actioncomm.class.php');
-			dol_include_once('/custom/booking/class/preorder.class.php');
-			$apiInvoiceHelper->increaseParticipant($fk_event);
-
-			$lines = $apiInvoiceHelper->getProductLines($product_id);
-			foreach ($lines as $line) {
-				$preOrderObj = new PreOrder($this->db);
-				$preOrderObj->ref = $this->generateRandomString();
-				$preOrderObj->fk_event = $fk_event;
-				$preOrderObj->fk_product = $product_id;
-				$result = $preOrderObj->create($this->user);
-				if ($result > 0) {
-					$createdPreOrderOBJ[] = [
-						'id' => $preOrderObj->id,
-						'ref' => $preOrderObj->ref,
-					];
-				} else {
-					ApiBbusLog::eventLog(json_encode(['error' => $preOrderObj->errors]));
-					ApiBbusLog::eventLog("Unsaved event: " . $fk_event);
-					throw new RestException(401, 'Unsaved event: ' . $fk_event);
-				}
-			}
-		}
-		return $createdPreOrderOBJ;
-	}
-
 	function generateRandomString($length = 10)
 	{
 		$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
@@ -687,184 +699,54 @@ class BookingApi extends DolibarrApi
 		$randomString = '';
 		for ($i = 0; $i < $length; $i++) {
 			$randomString .= $characters[rand(0, $charactersLength - 1)];
-		}
-
-		return $randomString;
-	}
-
-	/**
-	 * Save event data in Bookinghistory
-	 *
-	 * Return an array with details
-	 *
-	 * @return 	array|mixed data without useless information
-	 *
-	 * @param 	string 	$fk_event			//selected evet from llx_event
-	 * @param 	string 	$fk_facture			//facture rowid from llx_facture
-	 * @param 	string 	$fk_eventproduct	//eventproduct rowid from llx_eventwizard_eventproduct
-	 * @param 	string 	$ref
-	 * 
-	 * @url	POST saveeventdata
-	 * @access protected
-	 * @throws RestException 401 Not allowed
-	 * @throws RestException 404 Not found
-	 */
-	public function saveEventData(string $fk_event, string $ref, string $fk_facture = null, string $fk_eventproduct = null)
-	{
-		dol_include_once('/custom/booking/class/bookinghistory.class.php');
-		dol_include_once('/comm/action/class/actioncomm.class.php');
-		$actionCommObj = new ActionComm($this->db);
-		$sql = "SELECT fk_element, datep, datep2 FROM " . MAIN_DB_PREFIX . $actionCommObj->table_element . " WHERE id = {$fk_event}";
-		$result = $this->db->query($sql);
-		if ($this->db->num_rows($result) > 0) {
-			$row = $this->db->fetch_object($result);
-			$BookingHistory = new BookingHistory($this->db);
-			$BookingHistory->fk_event = (int)$fk_event;
-			$BookingHistory->fk_facture = (int)$fk_facture;
-			$BookingHistory->fk_event_detail = $row->fk_element;
-			$BookingHistory->fk_eventproduct = (int)$fk_eventproduct;
-			$BookingHistory->date_start = strtotime($row->datep);
-			$BookingHistory->date_end = strtotime($row->datep2);
-			$BookingHistory->invoice_number = $ref;
-			$result = $BookingHistory->create($this->user);
-			if ($result > 0) {
-				return $BookingHistory->id;
-			} else {
-				throw new RestException(401, 'Unsaved');
-			}
-		} else {
-			throw new RestException(401, 'No Event record');
-		}
-	}
-
-	/**
-	 * Validate and save invoice
-	 * {"facture_id":41968,"cardPaymentLog":"","sendId":"K1pfFPlT","payment":{"datepaye":1716388707,"paymentid":14,"accountid":4,"closepaidinvoices":"yes"}}
-	 *
-	 * Return an array with details
-	 *
-	 * @return 	array|mixed data without useless information
-	 *
-	 * @param  	int 	$facture_id			//facture_id
-	 * @param  	array 	$payment			Invoice payment
-	 * @param  	string 	$cardPaymentLog		Card payment log data
-	 * @param 	string	$sendId				//ID
-	 * 
-	 * @url	POST validateandsaveinvoiceold
-	 * @access protected
-
-	 * @throws RestException 401 Not allowed
-	 * @throws RestException 404 Not found
-	 * @throws RestException 506 No available spaces
-	 * 
-	 */
-	public function validateandsaveinvoiceOld(int $facture_id, array $payment, string $cardPaymentLog = '', string $sendId = '')
-	{
-		global $user;
-		ApiBbusLog::eventLog("{$sendId} === VALIDATE INVOICE ===");
-		dol_syslog("{$sendId} === VALIDATE INVOICE ===", LOG_INFO, 0);
-		ApiBbusLog::eventLog("{$sendId} REQUEST: {$sendId}");
-		dol_syslog("{$sendId} REQUEST: {$sendId}", LOG_INFO, 0);
-		ApiBbusLog::eventLog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})");
-		dol_syslog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})", LOG_INFO, 0);
-		ApiBbusLog::eventLog("{$sendId} " . json_encode([
-			'facture_id' => $facture_id,
-			'payement' => $payment,
-			'cardPayementLog' => $cardPaymentLog,
-			'sendId' => $sendId,
-		]));
-		$products = [];
-		$invoiceObj = new Facture($this->db);
-		$apiInvoiceHelper = new ApiInvoiceHelper;
-		$invoiceObj->fetch($facture_id);
-
-		foreach ($invoiceObj->lines as $line) {
-			$product = $apiInvoiceHelper->loadProductToResult(get_object_vars($line));
-			if (!empty($product)) {
-				$products[] = $product;
-			}
-		}
-
-		foreach ($products as &$row) {
-			foreach ($invoiceObj->lines as $line) {
-				if ($line->product_ref == $row['ref']) {
-					//$row['price'] = $line->total_ttc;
-					$row['price'] = $line->multicurrency_total_ttc;
-					$row['total_tva'] = $line->total_tva;
-					//$row['total_tva'] = $line->multicurrency_total_tva;
-				}
-			}
-		}
-
-		$invoiceObj = $apiInvoiceHelper->validateInvoiceFromPROV($invoiceObj, $sendId, $facture_id);
-		$apiInvoiceHelper->setPaymentFromPROV($invoiceObj, $payment, $sendId);
-		if (!empty($cardPaymentLog)) {
-			$invoiceObj = $apiInvoiceHelper->saveCardPaymentLog($invoiceObj, $cardPaymentLog, $sendId);
-		}
-
-		ApiBbusLog::eventLog("{$sendId} Invoice created. ID: {$invoiceObj->id} REF: {$invoiceObj->ref} REQ: {$sendId}");
-		dol_syslog("{$sendId} Invoice created. ID: {$invoiceObj->id} REF: {$invoiceObj->ref} REQ: {$sendId}", LOG_INFO, 0);
-		//$bbApiLock->delete($user);
-
-		ApiBbusLog::eventLog("{$sendId}####################################################################");
-		dol_syslog("{$sendId}####################################################################", LOG_INFO, 0);
-
-		return [
-			'sendId' => $sendId,
-			'invoice' => [
-				'id' => $invoiceObj->id,
-				'ref' => $invoiceObj->ref,
-				'total' => $invoiceObj->multicurrency_total_ttc
-			],
-			'products' => $products,
-		];
+		}
+
+		return $randomString;
 	}
 
 	/**
-	 * Validate and save invoice
-	 * {"cardPaymentLog": "","sendId": "Xune5nQb","payment": {"datepaye": 1720005853,"paymentid": 4,"accountid": 2,"closepaidinvoices": "yes"},"preorder": [23]}
+	 * Save event data in Bookinghistory
 	 *
 	 * Return an array with details
 	 *
 	 * @return 	array|mixed data without useless information
 	 *
-	 * @param 	string	$sendId				sendID
-	 * @param  	array 	$payment			Invoice payment
-	 * @param  	array 	$preorder			preorder
-	 * @param  	array 	$invoice			Invoice
-	 * @param  	string 	$cardPaymentLog		Card payment log data
+	 * @param 	string 	$fk_event			//selected evet from llx_event
+	 * @param 	string 	$fk_facture			//facture rowid from llx_facture
+	 * @param 	string 	$fk_eventproduct	//eventproduct rowid from llx_eventwizard_eventproduct
+	 * @param 	string 	$ref
 	 * 
-	 * @url	POST validateandsaveinvoice
+	 * @url	POST saveeventdata
 	 * @access protected
-
 	 * @throws RestException 401 Not allowed
 	 * @throws RestException 404 Not found
-	 * @throws RestException 506 No available spaces
-	 * 
 	 */
-	public function validateandsaveinvoice(string $sendId, array $payment, array $preorder, array $invoice, string $cardPaymentLog = '')
+	public function saveEventData(string $fk_event, string $ref, string $fk_facture = null, string $fk_eventproduct = null)
 	{
-		global $user, $db;
-		$createdInvoiceData = [];
-		$apiInvoiceHelper = new ApiInvoiceHelper;
-		$bbusApi = new BBus();
-		foreach ($preorder as $order) {
-			$sql = "SELECT fk_product, fk_event  FROM llx_booking_preorder WHERE rowid = {$order}";
-			//print $sql . "\r\n";
-			$data = $db->query($sql);
-			if ($db->num_rows($data) > 0) {
-				while ($row = $db->fetch_object($data)) {
-					//print_r($row);
-					$lines = $apiInvoiceHelper->getProductLines($row->fk_product);
-					$createdInvoiceArray = $bbusApi->invoice($invoice, $lines, $payment, $cardPaymentLog = '', $sendId = '');
-					$createdInvoiceData[] = $createdInvoiceArray;
-					$bookingHistory = $this->saveEventData((int)$row->fk_event, $createdInvoiceArray['invoice']['ref'], $createdInvoiceArray['invoice']['id']);
-					$this->updateBbticket($bookingHistory, $createdInvoiceArray['invoice']);
-					$this->deletePreorder($preorder);
-				}
+		dol_include_once('/custom/booking/class/bookinghistory.class.php');
+		dol_include_once('/comm/action/class/actioncomm.class.php');
+		$actionCommObj = new ActionComm($this->db);
+		$sql = "SELECT fk_element, datep, datep2 FROM " . MAIN_DB_PREFIX . $actionCommObj->table_element . " WHERE id = {$fk_event}";
+		$result = $this->db->query($sql);
+		if ($this->db->num_rows($result) > 0) {
+			$row = $this->db->fetch_object($result);
+			$BookingHistory = new BookingHistory($this->db);
+			$BookingHistory->fk_event = (int)$fk_event;
+			$BookingHistory->fk_facture = (int)$fk_facture;
+			$BookingHistory->fk_event_detail = $row->fk_element;
+			$BookingHistory->fk_eventproduct = (int)$fk_eventproduct;
+			$BookingHistory->date_start = strtotime($row->datep);
+			$BookingHistory->date_end = strtotime($row->datep2);
+			$BookingHistory->invoice_number = $ref;
+			$result = $BookingHistory->create($this->user);
+			if ($result > 0) {
+				return $BookingHistory->id;
+			} else {
+				throw new RestException(401, 'Unsaved');
 			}
+		} else {
+			throw new RestException(401, 'No Event record');
 		}
-		return $createdInvoiceData;
 	}
 
 	public function updateBbticket($fk_booking_history, $invoice)
@@ -1066,40 +948,6 @@ class BookingApi extends DolibarrApi
 		];
 	}
 
-	/**
-	 * Get all free spaces on a selected date
-	 *
-	 * Return an array with details
-	 *
-	 * @return 	array|mixed data without useless information
-	 *
-	 * @param 	string 	date_from
-	 * @param 	string 	date_to
-	 * @param 	int 	product_id
-	 * @param 	int 	participant_number
-	 * 
-	 * @url	POST getavailablespaces
-	 *
-	 * @throws RestException 401 Not allowed
-	 * @throws RestException 404 Not found
-	 */
-	public function getAvailableSpaces(string $date_from, string $date_to, int $product_id, int $participant_number, string $type_id = null)
-	{
-		ApiBbusLog::appLog("getAvailableSpaces");
-		/* ApiBbusLog::appLog("type_id: {$type_id}");
-		ApiBbusLog::appLog("date_from: {$date_from}");
-		ApiBbusLog::appLog("date_to: {$date_to}");
-		ApiBbusLog::appLog("product_id: {$product_id}");
-		ApiBbusLog::appLog("participant_number: {$participant_number}"); */
-		$basicServices = new BasicServices($this->db);
-		$resultBS = $basicServices->fetch($type_id);
-		if ($basicServices->server_host == 'excelia') {
-			return $this->localAvailablePlaces($date_from, $date_to, $product_id, $participant_number);
-		} else {
-			return $this->curlAvailablePlaces($date_from, $date_to, $product_id, $participant_number);
-		}
-	}
-
 	/**
 	 * Get all free spaces on a selected date
 	 *
@@ -1391,12 +1239,14 @@ class BookingApi extends DolibarrApi
 	{
 		global $user;
 		$sql = "SELECT rowid FROM llx_bbus_bbticket WHERE invoice_number = '{$invoice['id']}'";
+		ApiBbusLog::appLog("curlUpdateBbticket SELECT: {$sql}");
 		$data = $this->db->query($sql);
 		if ($this->db->num_rows($data) > 0) {
 			while ($row = $this->db->fetch_object($data)) {
 				$sql = "UPDATE llx_bbus_bbticket
 				SET booking_history_id = {$fk_booking_history}, invoice_number = '{$invoice['ref']}'
 				WHERE rowid = {$row->rowid}";
+				ApiBbusLog::appLog("curlUpdateBbticket UPDATE: {$sql}");
 				$this->db->query($sql);
 			}
 		}
@@ -1415,9 +1265,10 @@ class BookingApi extends DolibarrApi
 	 * @throws RestException 401 Not allowed
 	 * @throws RestException 404 Not found
 	 */
-	public function curlDeletePreorder($preorder_id)
+	public function curlDeletePreorder($rowid)
 	{
-		$sql = "DELETE FROM llx_booking_preorder WHERE rowid = {$preorder_id}";
+		$sql = "DELETE FROM llx_booking_preorder WHERE rowid = {$rowid}";
+		ApiBbusLog::appLog("{$sql}");
 		$this->db->query($sql);
 	}
 
@@ -1466,4 +1317,164 @@ class BookingApi extends DolibarrApi
 		$array['ticket_id'] = $ticket->ticket_id;
 		return $array;
 	}
+
+	#-------------------------------------------------
+	#	OLD functions
+	#-------------------------------------------------
+
+	/**
+	 * Validate and save invoice
+	 * {"facture_id":41968,"cardPaymentLog":"","sendId":"K1pfFPlT","payment":{"datepaye":1716388707,"paymentid":14,"accountid":4,"closepaidinvoices":"yes"}}
+	 *
+	 * Return an array with details
+	 *
+	 * @return 	array|mixed data without useless information
+	 *
+	 * @param  	int 	$facture_id			//facture_id
+	 * @param  	array 	$payment			Invoice payment
+	 * @param  	string 	$cardPaymentLog		Card payment log data
+	 * @param 	string	$sendId				//ID
+	 * 
+	 * @url	POST validateandsaveinvoiceold
+	 * @access protected
+
+	 * @throws RestException 401 Not allowed
+	 * @throws RestException 404 Not found
+	 * @throws RestException 506 No available spaces
+	 * 
+	 */
+	public function validateandsaveinvoiceOld(int $facture_id, array $payment, string $cardPaymentLog = '', string $sendId = '')
+	{
+		global $user;
+		ApiBbusLog::eventLog("{$sendId} === VALIDATE INVOICE ===");
+		dol_syslog("{$sendId} === VALIDATE INVOICE ===", LOG_INFO, 0);
+		ApiBbusLog::eventLog("{$sendId} REQUEST: {$sendId}");
+		dol_syslog("{$sendId} REQUEST: {$sendId}", LOG_INFO, 0);
+		ApiBbusLog::eventLog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})");
+		dol_syslog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})", LOG_INFO, 0);
+		ApiBbusLog::eventLog("{$sendId} " . json_encode([
+			'facture_id' => $facture_id,
+			'payement' => $payment,
+			'cardPayementLog' => $cardPaymentLog,
+			'sendId' => $sendId,
+		]));
+		$products = [];
+		$invoiceObj = new Facture($this->db);
+		$apiInvoiceHelper = new ApiInvoiceHelper;
+		$invoiceObj->fetch($facture_id);
+
+		foreach ($invoiceObj->lines as $line) {
+			$product = $apiInvoiceHelper->loadProductToResult(get_object_vars($line));
+			if (!empty($product)) {
+				$products[] = $product;
+			}
+		}
+
+		foreach ($products as &$row) {
+			foreach ($invoiceObj->lines as $line) {
+				if ($line->product_ref == $row['ref']) {
+					//$row['price'] = $line->total_ttc;
+					$row['price'] = $line->multicurrency_total_ttc;
+					$row['total_tva'] = $line->total_tva;
+					//$row['total_tva'] = $line->multicurrency_total_tva;
+				}
+			}
+		}
+
+		$invoiceObj = $apiInvoiceHelper->validateInvoiceFromPROV($invoiceObj, $sendId, $facture_id);
+		$apiInvoiceHelper->setPaymentFromPROV($invoiceObj, $payment, $sendId);
+		if (!empty($cardPaymentLog)) {
+			$invoiceObj = $apiInvoiceHelper->saveCardPaymentLog($invoiceObj, $cardPaymentLog, $sendId);
+		}
+
+		ApiBbusLog::eventLog("{$sendId} Invoice created. ID: {$invoiceObj->id} REF: {$invoiceObj->ref} REQ: {$sendId}");
+		dol_syslog("{$sendId} Invoice created. ID: {$invoiceObj->id} REF: {$invoiceObj->ref} REQ: {$sendId}", LOG_INFO, 0);
+		//$bbApiLock->delete($user);
+
+		ApiBbusLog::eventLog("{$sendId}####################################################################");
+		dol_syslog("{$sendId}####################################################################", LOG_INFO, 0);
+
+		return [
+			'sendId' => $sendId,
+			'invoice' => [
+				'id' => $invoiceObj->id,
+				'ref' => $invoiceObj->ref,
+				'total' => $invoiceObj->multicurrency_total_ttc
+			],
+			'products' => $products,
+		];
+	}
+
+	/**
+	 * First step of the eventhandling
+	 * {"invoice":{"array_options_app_facture":1,"array_options_customer_data_zip":6782,"multicurrency_code":"HUF","fk_multicurrency":3,"mode_reglement_id":14,"cond_reglement_id":14,"fk_account":4},"fk_event":82586,"reservations":1,"sendId":12121212,"product_id":155}
+	 *
+	 * Return an array with details
+	 *
+	 * @return 	array|mixed data without useless information
+	 *
+	 * @param  array 	$invoice			Invoice data
+	 * @param 	int 	$fk_event			//selected evet from llx_event
+	 * @param 	int 	$reservations		//numbers of reservations
+	 * @param 	int 	$product_id			//Product
+	 * @param 	string	$sendId				//ID
+	 * 
+	 * @url	POST firsteventstepold
+	 * @access protected
+	 * @throws RestException 401 Not allowed
+	 * @throws RestException 404 Not found
+	 * @throws RestException 506 No available spaces
+	 * 
+	 */
+	public function firstEventStepOld(array $invoice, int $fk_event, int $reservations, int $product_id, string $sendId)
+	{
+		$eventHelper = new EventHelper;
+		if ($eventHelper->noEmptySpaces($fk_event, $reservations)) {
+			throw new RestException(506, 'No available spaces');
+		}
+
+		if (!DolibarrApiAccess::$user->rights->facture->creer) {
+			ApiBbusLog::eventLog("{$sendId} Insufficient rights");
+			throw new RestException(401, 'Insufficient rights');
+		}
+		/**
+		 * LOG SECTION
+		 */
+		ApiBbusLog::eventLog("{$sendId} === NEW INVOICE ===");
+		dol_syslog("{$sendId} === NEW INVOICE ===", LOG_INFO, 0);
+		ApiBbusLog::eventLog("{$sendId} REQUEST: {$sendId}");
+		dol_syslog("{$sendId} REQUEST: {$sendId}", LOG_INFO, 0);
+		ApiBbusLog::eventLog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})");
+		dol_syslog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})", LOG_INFO, 0);
+		ApiBbusLog::eventLog("{$sendId} " . json_encode([
+			'invoice' => $invoice,
+			'fk_event' => $fk_event,
+			'reservations' => $reservations,
+			'product_id' => $product_id,
+			'sendId' => $sendId,
+		]));
+
+		$apiInvoiceHelper = new ApiInvoiceHelper;
+		$createdInvoicePROVs = [];
+
+		for ($i = 1; $i <= $reservations; $i++) {
+			dol_include_once('/comm/action/class/actioncomm.class.php');
+			$apiInvoiceHelper->increaseParticipant($fk_event);
+			$invoiceObj = $apiInvoiceHelper->createInvoicePROV($invoice, $sendId);
+			$createdInvoicePROVs[] = [
+				'id' => $invoiceObj->id,
+				'ref' => $invoiceObj->ref,
+			];
+			ApiBbusLog::eventLog("{$sendId} - Invoice PROV created - " . $invoiceObj->id . ' - ' . $invoiceObj->ref);
+			$lines = $apiInvoiceHelper->getProductLines($product_id);
+			foreach ($lines as $line) {
+				$invoiceLineObj = $apiInvoiceHelper->addLineToInvoice($invoiceObj, $line, $sendId);
+				$this->saveEventData($fk_event, $invoiceObj->id, $fk_eventproduct = 1);
+			}
+			$invoiceLineObj->fetch_lines();
+		}
+		print_r($createdInvoicePROVs);
+		exit;
+		return $createdInvoicePROVs;
+	}
 }

+ 151 - 19
custom/booking/class/booking_agenda_helper.class.php

@@ -35,67 +35,78 @@ class BookingAgendaHelper
     function getsumReservation($eventsArray, $eventday, $hourText)
     {
         $count = 0;
+        $actionCommIds = [];
         $from = strtotime($eventday . ' ' . $hourText . ':00:00');
         $to = strtotime($eventday . ' ' . $hourText . ':59:59');
         foreach ($eventsArray as $event) {
             $event_from = strtotime($event['datep']);
             $event_to = strtotime($event['datep2']);
             if (($from <= $event_from && $to >= $event_from) || $from >= $event_from && $to + 1 <= $event_to) {
-                //print $eventday . ' ' . $fromtime . ' - ' . $eventday . ' ' . $totime . '<br>';
-                //print ' - ' . $event['datep'] . ' - ' . $event['datep2'] . '<br>';
                 $count = $count + (int)$event['participants'];
+                $actionCommIds[] = (int)$event['actioncomm_id'];
             }
-            
         }
-        return $count > 0 ? $count : '-';
+        $array['count'] = $count > 0 ? $count : '-';
+        $array['ids'] = implode(',', $actionCommIds);
+        return $array;
     }
 
     function getsumOccupied($eventsArray, $eventday, $hourText)
     {
         $count = 0;
+        $actionCommIds = [];
         $from = strtotime($eventday . ' ' . $hourText . ':00:00');
         $to = strtotime($eventday . ' ' . $hourText . ':59:59');
         foreach ($eventsArray as $event) {
             $event_from = strtotime($event['datep']);
             $event_to = strtotime($event['datep2']);
-            if($from == $event_to){
+            if ($from == $event_to) {
                 $count = $count + (int)$event['participants'];
+                $actionCommIds[] = (int)$event['actioncomm_id'];
             }
             if (($from <= $event_from && $to >= $event_from) || $from >= $event_from && $to + 1 <= $event_to) {
                 $count = $count + (int)$event['participants'];
+                $actionCommIds[] = (int)$event['actioncomm_id'];
             }
-            
         }
-        return $count > 0 ? $count : '-';
+        $array['count'] = $count > 0 ? $count : '-';
+        $array['ids'] = implode(',', $actionCommIds);
+        return $array;
     }
 
     function getsumService($eventsArray, $eventday, $hourText)
     {
         $count = 0;
+        $actionCommIds = [];
         $from = strtotime($eventday . ' ' . $hourText . ':00:00');
         foreach ($eventsArray as $event) {
             $event_to = strtotime($event['datep2']);
-            if($from == $event_to){
+            if ($from == $event_to) {
                 $count = $count + (int)$event['participants'];
-            }   
+                $actionCommIds[] = (int)$event['actioncomm_id'];
+            }
         }
-        return $count > 0 ? $count : '-';
+        $array['count'] = $count > 0 ? $count : '-';
+        $array['ids'] = implode(',', $actionCommIds);
+        return $array;
     }
 
-    function getlocations(){
+    function getlocations()
+    {
         $locationArray = [];
         $eventwizardLocationsObj = new EventLocation($this->db);
         $result = $eventwizardLocationsObj->fetchAll('ASC', 'label', 0, 0);
-        if(count($result) > 0){
-            foreach($result as $location){
+        if (count($result) > 0) {
+            foreach ($result as $location) {
                 $locationArray[$location->id] = $location->label;
             }
         }
         return $locationArray;
     }
 
-    function getLocationLabel($event){
-        foreach($event as $eventDetail){
+    function getLocationLabel($event)
+    {
+        foreach ($event as $eventDetail) {
             return $eventDetail['fk_elventlocation_departure'];
         }
     }
@@ -111,12 +122,133 @@ class BookingAgendaHelper
         return $array;
     }
 
-    function getBGColor($rowcolorCounter){
+    function getBGColor($rowcolorCounter)
+    {
         return $rowcolorCounter % 2 ? 'white' : 'Gainsboro';
     }
-    
-    function getHourText($hour){
+
+    function getHourText($hour)
+    {
         return $hour < 10 ? '0' . $hour : $hour;
     }
 
-}
+    private function getActionCommID($event)
+    {
+        return array_key_first($event);
+    }
+
+    function showTable($eventdayDates, $selectedEvent)
+    {
+        global $langs, $db;
+        //$this = new this($db);
+        $k = 0;
+        $dailyStartTime = 9;
+        $dailyEndTime = 21;
+        $eventsArray = [];
+        $daysql = "SELECT 
+                    ed.rowid as eventdetail_id, 
+                    ed.label as eventdetail_label,
+                    ac.id as actioncomm_id,
+                    ac.datep,
+                    ac.datep2,
+                    ac.durationp,
+                    ace.buffer,
+                    ace.max_num,
+                    ace.participants,
+                    ed.fk_elventlocation_departure
+                FROM llx_eventwizard_eventdetails as ed 
+                INNER JOIN llx_actioncomm as ac ON ac.fk_element = ed.rowid
+                INNER JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
+                WHERE ed.type IN (3,4)
+                AND ac.code = 'AC_EVENT'
+                AND ac.datep BETWEEN '{$eventdayDates['from']}' AND '{$eventdayDates['to']}'
+                AND ace.participants IS NOT NULL
+                ORDER BY ac.id DESC";
+                //print $daysql;
+        $eventsArray = $this->getOneColumnFromTable($daysql, $eventsArray, 'actioncomm_id');
+        $locationArray = $this->getlocations();
+        print '<table style="width:100%">';
+        print '<tr class="firstcolumn">
+        <td style="width:15%">' . $langs->trans('Location') . '</td>
+        <td style="width:7%">' . $langs->trans('Status') . '</td>';
+        for ($i = 9; $i < 21; $i++) {
+            $hourText = $i < 10 ? '0' . $i : $i;
+            print '<td>' . $hourText . '</td>';
+            $k++;
+        }
+        $k = $k + 2;
+        print '<tr class="elvalaszto"><td colspan="' . $k . '"></td></tr>';
+        print '</tr>';
+
+        foreach ($eventsArray as $event) {
+            print '<tr class="trheight">
+            <td class="firstcolumn"></td>
+            <td class="center">Foglalás</td>';
+            $rowcolorCounter = 0;
+            print '<br>';
+            for ($i = $dailyStartTime; $i < $dailyEndTime; $i++) {
+                $backgroundColor = $this->getBGColor($rowcolorCounter);
+                $hourText = $this->getHourText($i);
+                $ReservationArray = $this->getsumReservation($event, $eventdayDates['eventday'], $hourText);
+                $sumNumber = $ReservationArray['count'];
+                $cursor = $sumNumber > 0 ? 'pointer' : '';
+                print '<td class="center" style="background-color: ' . $backgroundColor . '; cursor:' . $cursor . ';" onclick="ShoMeTheEventDeatils(\'' . (string)$ReservationArray['ids'] . '\')">' . $sumNumber . '</td>';
+                $rowcolorCounter++;
+            }
+            print '</tr>';
+            print '<tr class="trheight foglaltsag">
+            <td class="location firstcolumn">' . $locationArray[$this->getLocationLabel($event)] . '</td>
+            <td class="center">Foglalt</td>';
+            $rowcolorCounter = 0;
+            for ($i = $dailyStartTime; $i < $dailyEndTime; $i++) {
+                $backgroundColor = $this->getBGColor($rowcolorCounter);
+                $hourText = $this->getHourText($i);
+                $OccupiedArray = $this->getsumOccupied($event, $eventdayDates['eventday'], $hourText);
+                $sumNumber = $OccupiedArray['count'];
+                $cursor = $sumNumber > 0 ? 'pointer' : '';
+                print '<td class="center" style="background-color: ' . $backgroundColor . '; cursor:' . $cursor . ';" onclick="ShoMeTheEventDeatils(\'' . (string)$OccupiedArray['ids'] . '\')">' . $sumNumber . '</td>';
+                $rowcolorCounter++;
+            }
+            print '</tr>';
+            print '<tr class="trheight">
+            <td class="firstcolumn"></td>
+            <td class="center">Szervíz</td>';
+            $rowcolorCounter = 0;
+            for ($i = $dailyStartTime; $i < $dailyEndTime; $i++) {
+                $backgroundColor = $this->getBGColor($rowcolorCounter);
+                $hourText = $this->getHourText($i);
+                $ServiceArray = $this->getsumService($event, $eventdayDates['eventday'], $hourText);
+                $sumNumber = $ServiceArray['count'];
+                $cursor = $sumNumber > 0 ? 'pointer' : '';
+                print '<td class="center" style="background-color: ' . $backgroundColor . '; cursor:' . $cursor . ';" onclick="ShoMeTheEventDeatils(\'' . (string)$ServiceArray['ids'] . '\')">' . $sumNumber . '</td>';
+                $rowcolorCounter++;
+            }
+            print '</tr>';
+            print '<tr class="elvalaszto"><td colspan="' . $k . '"></td></tr>';
+        }
+        print '</table>';
+    }
+
+    public function getSelectedEvents($event)
+    {
+        global $db;
+        $eventsArray = explode(',', $event);
+        $everything = [];
+        foreach ($eventsArray as $eventdetail) {
+            $sql = "SELECT ac.id, ac.datep, ac.datep2, ac.durationp, bh.fk_facture, bh.invoice_number, pr.label
+            FROM llx_actioncomm as ac 
+            INNER JOIN llx_booking_bookinghistory as bh ON bh.fk_event = ac.id
+            INNER JOIN llx_eventwizard_eventdetails as ed ON bh.fk_event_detail = ed.rowid
+            INNER JOIN llx_eventwizard_eventproduct as ep ON ep.fk_eventdetails = ed.rowid
+            INNER JOIN llx_product as pr ON pr.rowid = ep.fk_product
+            WHERE ac.id = {$eventdetail} ORDER BY fk_facture DESC";
+            $result = $db->query($sql);
+            if ($db->num_rows($result) > 0) {
+                while ($row = $db->fetch_object($result)) {
+                    print '<div>' . $row->invoice_number . ' ' . $row->label . ' ' . $row->datep . '-' . $row->datep2 . '</div>';
+
+                }
+            }
+        }
+    }
+}

Nem az összes módosított fájl került megjelenítésre, mert túl sok fájl változott