yogibook_aury_new/public/promemoria-cron.php

182 lines
7.3 KiB
PHP

<?php
// Abilita visualizzazione errori PHP (solo per debug)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
include('include/headscript.php');
// Includi PHPMailer una sola volta, all'inizio dello script
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';
// Verifica connessione al database
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connessione al database fallita: " . $conn->connect_error);
}
// Inizializza contatore e log
$emailCount = 0;
$errors = [];
$logFile = 'promemoria_cron_log.txt';
$logMessage = "Esecuzione cron: " . date('Y-m-d H:i:s') . "\n";
// Genera UUID per tutti i record senza token
$updateQuery = "UPDATE bookingclass
SET cancellation_token = UUID()
WHERE status = 'booked'
AND cancellation_token IS NULL";
$updateStmt = $conn->prepare($updateQuery);
if ($updateStmt) {
$updateStmt->execute();
$affectedRows = $updateStmt->affected_rows;
$logMessage .= "Generati $affectedRows token UUID per prenotazioni senza token.\n";
} else {
$errors[] = "Errore preparazione query per generazione token: " . $conn->error;
$logMessage .= "Errore generazione token: " . $conn->error . "\n";
}
// Seleziona prenotazioni per domani (dalle 17:00 in poi) e dopodomani (fino alle 16:59)
$tomorrow = date('Y-m-d', strtotime('+1 day'));
$dayAfterTomorrow = date('Y-m-d', strtotime('+2 days'));
$query = "SELECT bc.*, au.email, au.first_name, s.servicename
FROM bookingclass bc
LEFT JOIN auth_users au ON bc.iduser = au.id
LEFT JOIN service s ON bc.idservice = s.idservice
WHERE bc.status = 'booked' AND (
(DATE(bc.bookingstart) = ? AND TIME(bc.bookingstart) >= '17:00:00') OR
(DATE(bc.bookingstart) = ? AND TIME(bc.bookingstart) <= '16:59:59')
)";
$stmt = $conn->prepare($query);
if (!$stmt) {
$errors[] = "Errore preparazione query: " . $conn->error;
file_put_contents($logFile, $logMessage . "Errore query: " . $conn->error . "\n", FILE_APPEND);
echo "Errore preparazione query: " . $conn->error;
exit;
}
$stmt->bind_param("ss", $tomorrow, $dayAfterTomorrow);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0) {
$logMessage .= "Nessuna prenotazione trovata per domani (dalle 17:00) o dopodomani (fino alle 16:59).\n";
file_put_contents($logFile, $logMessage, FILE_APPEND);
echo "Nessuna prenotazione trovata.\n";
exit;
}
while ($row = $result->fetch_assoc()) {
$idbookingclass = $row['idbookingclass'];
$token = $row['cancellation_token'];
// Verifica che il token esista
if (empty($token)) {
$errors[] = "Token mancante per ID $idbookingclass dopo aggiornamento UUID.";
$logMessage .= "Token mancante per ID $idbookingclass dopo aggiornamento UUID.\n";
continue;
}
$firstname = $row['first_name'] ?? 'Utente';
$emailuser = $row['email'];
$servicename = $row['servicename'] ?? 'Sconosciuta';
$bookingstart = $row['bookingstart'];
$dataformat = date("d-m-Y H:i", strtotime($bookingstart));
// Determina il limite di cancellazione in base all'orario della lezione
$lessonTime = new DateTime($bookingstart);
$isTomorrow = $lessonTime->format('Y-m-d') === $tomorrow;
$hour = (int)$lessonTime->format('H');
$minute = (int)$lessonTime->format('i');
$isBefore1700 = ($hour < 17) || ($hour === 17 && $minute === 0);
$cancellationDeadline = $isBefore1700 ? "00:01" : "12:00";
// Verifica email valida
if (!filter_var($emailuser, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Email non valida per ID $idbookingclass: $emailuser";
$logMessage .= "Email non valida per ID $idbookingclass: $emailuser\n";
continue;
}
// Link cancellazione
$link = "https://yogibook.yogasoul.it/cancella-prenotazione.php?idbookingclass=$idbookingclass&token=$token";
// Messaggio email
$message = "<p style='font-size: 14px; line-height: 190%;'><span style='font-size: 18px; line-height: 34.2px;'><strong>Ciao $firstname,</strong></span></p>
<p style='font-size: 14px; line-height: 190%;'><span style='font-size: 16px; line-height: 30.4px;'>Promemoria: hai la lezione $servicename del $dataformat.</span></p>
<p style='font-size: 14px; line-height: 190%;'><span style='font-size: 16px; line-height: 30.4px;'>Puoi cancellarla fino alle $cancellationDeadline del giorno della lezione cliccando qui:</span></p>
<a href='$link' target='_blank'>Cancella prenotazione</a>
<br>
<p style='font-size: 14px; line-height: 190%;'><span style='font-size: 16px; line-height: 30.4px;'>Ci vediamo sul tappetino!</span></p>
<p style='font-size: 14px; line-height: 190%;'><span style='font-size: 16px; line-height: 30.4px;'>Il Team Yogasoul</span></p>";
// Definisci $messageedit per il template
$messageedit = $message;
// Definisci $buttonedit
$buttonedit = "<a href='https://yogibook.yogasoul.it/' target='_blank' class='v-button v-font-size' style='box-sizing: border-box;display: inline-block;text-decoration: none;-webkit-text-size-adjust: none;text-align: center;color: #FFFFFF; background-color: #3AAEE0; border-radius: 4px;-webkit-border-radius: 4px; -moz-border-radius: 4px; width:auto; max-width:100%; overflow-wrap: break-word; word-break: break-word; word-wrap:break-word; mso-border-alt: none;font-size: 14px;'>
<span style='display:block;padding:10px 20px;line-height:120%;'><span style='line-height: 16.8px;'>YogiBook - YogaSoul</span></span>
</a>";
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'mail.yogasoul.it';
$mail->SMTPAuth = true;
$mail->Username = 'info@yogasoul.it';
$mail->Password = '!Testolina88';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
if (!file_exists('mail/emailtemplate2.php')) {
throw new Exception("File emailtemplate2.php non trovato.");
}
include('mail/emailtemplate2.php');
if (!isset($mailmessage1)) {
throw new Exception("Variabile \$mailmessage1 non definita in emailtemplate2.php.");
}
$htmlContent = str_replace('{message}', $message, $mailmessage1);
$mail->From = 'info@yogasoul.it';
$mail->FromName = 'YogiBook [YogaSoul]';
$mail->addAddress($emailuser);
$mail->Subject = "YogiBook - Promemoria lezione!";
$mail->Body = $htmlContent;
$mail->AltBody = 'Promemoria lezione.';
$mail->send();
$emailCount++;
$logMessage .= "Email inviata a $emailuser per lezione ID $idbookingclass ($dataformat)\n";
} catch (Exception $e) {
$errors[] = "Errore invio email a $emailuser (ID $idbookingclass): " . $mail->ErrorInfo;
$logMessage .= "Errore invio a $emailuser (ID $idbookingclass): " . $mail->ErrorInfo . "\n";
}
sleep(2);
}
// Scrivi log
file_put_contents($logFile, $logMessage, FILE_APPEND);
// Output debug
echo "Esecuzione completata: $emailCount email inviate.\n";
if (!empty($errors)) {
echo "Errori rilevati:\n";
foreach ($errors as $error) {
echo "- $error\n";
}
} else {
echo "Nessun errore.\n";
}
echo "Dettagli nel file di log: $logFile\n";
$conn->close();