setTime((int)$timeParts[0], (int)($timeParts[1] ?? 0), 0); $diffToday = $nowDt->getTimestamp() - $targetTodayDt->getTimestamp(); // Check if within 15 minutes (900 seconds) after the target time AND not sent today if ($diffToday >= 0 && $diffToday <= 900 && $lastReportDate !== $nowDt->format('Y-m-d')) { cron_log("Condition met: sending daily report for " . $nowDt->format('Y-m-d')); $pdo = db(); $today = $nowDt->format('Y-m-d'); // 1. Calculate Stats // Total Revenue Today $stmt = $pdo->prepare("SELECT SUM(total_amount) FROM orders WHERE DATE(created_at) = ? AND status != 'cancelled'"); $stmt->execute([$today]); $revenueToday = $stmt->fetchColumn() ?: 0; // Total Orders Today $stmt = $pdo->prepare("SELECT COUNT(*) FROM orders WHERE DATE(created_at) = ? AND status != 'cancelled'"); $stmt->execute([$today]); $ordersToday = $stmt->fetchColumn(); // Total Expenses Today $stmt = $pdo->prepare("SELECT SUM(amount) FROM expenses WHERE DATE(expense_date) = ?"); $stmt->execute([$today]); $expensesToday = $stmt->fetchColumn() ?: 0; // Currency $currency = $settings['currency_symbol'] ?? '$'; // 2. Format Message $message = "๐Ÿ“… *Daily Report* ๐Ÿ“…\n"; $message .= "Date: " . $today . "\n\n"; $message .= "๐Ÿ’ฐ *Sales:* " . format_currency_simple($revenueToday, $settings) . "\n"; $message .= "๐Ÿงพ *Orders:* " . $ordersToday . "\n"; $message .= "๐Ÿ’ธ *Expenses:* " . format_currency_simple($expensesToday, $settings) . "\n"; $message .= "\n--------------------------\n"; $message .= "๐Ÿค– Auto-generated message"; // 3. Send Message $wablas = new WablasService($pdo); // Handle multiple recipients (comma separated) $recipients = explode(',', $settings['whatsapp_report_number']); $anySuccess = false; foreach ($recipients as $recipient) { $recipient = trim($recipient); if (empty($recipient)) continue; cron_log("Sending report to: " . $recipient); $result = $wablas->sendMessage($recipient, $message); if (!empty($result['success']) && $result['success'] == true) { cron_log("Report sent successfully to " . $recipient); $anySuccess = true; } else { cron_log("Failed to send report to " . $recipient . ": " . ($result['message'] ?? 'Unknown error')); } } if ($anySuccess) { file_put_contents($lastReportFile, $today); } } // Else: silent skip } catch (Exception $e) { cron_log("CRITICAL ERROR: " . $e->getMessage()); } function format_currency_simple($amount, $settings) { $symbol = $settings['currency_symbol'] ?? '$'; $decimals = (int)($settings['currency_decimals'] ?? 2); $position = $settings['currency_position'] ?? 'before'; $formatted = number_format((float)$amount, $decimals); return ($position === 'after') ? "$formatted $symbol" : "$symbol $formatted"; }