49 lines
2.1 KiB
PHP
Executable File
49 lines
2.1 KiB
PHP
Executable File
<?php
|
|
|
|
if (!function_exists('calculateNextSendTime')) {
|
|
/**
|
|
* Calcula la próxima fecha y hora de envío para un mensaje recurrente.
|
|
*
|
|
* @param array $recurringDays Un array de enteros representando los días de la semana (0=Domingo, 6=Sábado).
|
|
* @param string $recurringTime La hora del día en formato HH:MM.
|
|
* @param string $timezone La zona horaria a utilizar.
|
|
* @return string La próxima fecha y hora de envío en formato Y-m-d H:i:s.
|
|
* @throws Exception Si no se puede determinar la próxima fecha de envío.
|
|
*/
|
|
function calculateNextSendTime(array $recurringDays, string $recurringTime, string $timezone = 'America/Mexico_City'): string {
|
|
$tz = new DateTimeZone($timezone);
|
|
$now = new DateTime('now', $tz);
|
|
list($hour, $minute) = explode(':', $recurringTime);
|
|
|
|
sort($recurringDays); // Ensure days are sorted
|
|
|
|
$nextSendTime = null;
|
|
|
|
// 1. Check for today's occurrence first
|
|
$todayDayOfWeek = (int)$now->format('w');
|
|
$potentialTodaySendTime = (clone $now)->setTime((int)$hour, (int)$minute, 0);
|
|
|
|
if (in_array($todayDayOfWeek, $recurringDays) && $potentialTodaySendTime > $now) {
|
|
// If today is a recurring day and the time hasn't passed yet, this is the next send time
|
|
$nextSendTime = $potentialTodaySendTime;
|
|
} else {
|
|
// 2. Look for the next recurring day, starting from tomorrow
|
|
for ($i = 1; $i <= 7; $i++) { // Check next 7 days
|
|
$checkDate = (clone $now)->modify("+$i days");
|
|
$dayOfWeek = (int)$checkDate->format('w');
|
|
|
|
if (in_array($dayOfWeek, $recurringDays)) {
|
|
$nextSendTime = (clone $checkDate)->setTime((int)$hour, (int)$minute, 0);
|
|
break; // Found the earliest future recurring day
|
|
}
|
|
}
|
|
}
|
|
|
|
if ($nextSendTime === null) {
|
|
throw new Exception('No se pudo determinar la próxima fecha de envío para la configuración recurrente proporcionada.');
|
|
}
|
|
|
|
return $nextSendTime->format('Y-m-d H:i:s');
|
|
}
|
|
}
|
|
?>
|